@chrischall/microsoft-teams-mcp 0.3.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.
- package/.claude-plugin/marketplace.json +4 -4
- package/.claude-plugin/plugin.json +2 -2
- package/README.md +577 -93
- package/dist/auth-fetchproxy.js +138 -0
- package/dist/bundle.js +44324 -37483
- package/dist/capture-window.js +41 -0
- package/dist/chatsvc.js +580 -0
- package/dist/compose.js +241 -0
- package/dist/deps.js +1 -0
- package/dist/index.js +35 -6
- package/dist/model.js +603 -0
- package/dist/sharepoint-auth.js +162 -0
- package/dist/sharepoint-token-cache.js +105 -0
- package/dist/sharepoint.js +289 -0
- package/dist/substrate-auth.js +104 -0
- package/dist/substrate-token-cache.js +64 -0
- package/dist/substrate.js +319 -0
- package/dist/token-cache.js +67 -0
- package/dist/tools/activity.js +155 -19
- package/dist/tools/attachment.js +174 -0
- package/dist/tools/changes.js +241 -0
- package/dist/tools/channels.js +62 -44
- package/dist/tools/chat-search.js +65 -0
- package/dist/tools/chat.js +121 -41
- package/dist/tools/confirm.js +188 -0
- package/dist/tools/conversation.js +394 -30
- package/dist/tools/cursor.js +43 -0
- package/dist/tools/errors.js +18 -17
- package/dist/tools/format.js +135 -0
- package/dist/tools/healthcheck.js +91 -27
- package/dist/tools/limit.js +43 -12
- package/dist/tools/listing.js +180 -0
- package/dist/tools/markread.js +246 -0
- package/dist/tools/react.js +217 -0
- package/dist/tools/roots.js +73 -0
- package/dist/tools/search.js +426 -0
- package/dist/tools/send.js +309 -0
- package/dist/tools/timezone.js +38 -0
- package/dist/tools/titles.js +180 -0
- package/dist/tools/unread.js +263 -0
- package/dist/tools/untrusted.js +16 -1
- package/dist/version.js +1 -1
- package/mint.yaml +75 -20
- package/package.json +1 -2
- package/server.json +87 -3
- package/skills/teams-fpx/SKILL.md +111 -92
- package/skills/teams-fpx/references/chatsvc-recipes.md +151 -0
- package/skills/teams-fpx/references/teams-env.sh +146 -0
- package/dist/client.js +0 -290
- package/skills/teams-fpx/references/dom-list-recipes.md +0 -81
|
@@ -1,29 +1,93 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
1
|
+
import { toolAnnotations } from '@chrischall/mcp-utils';
|
|
2
|
+
import { credentialHealthcheckDescription, runCredentialHealthcheck } from '@chrischall/mcp-utils/healthcheck';
|
|
3
|
+
const HOST_LABEL = 'teams.cloud.microsoft';
|
|
4
|
+
const TITLE = 'Verify the Teams chat-service token and API end-to-end';
|
|
5
|
+
/**
|
|
6
|
+
* Static note on the SharePoint path: a separate token, captured on demand per
|
|
7
|
+
* host and short-lived, that `teams_get_attachment` uses for shared-file
|
|
8
|
+
* download. Not probed here — a healthy result never depends on it existing.
|
|
9
|
+
*/
|
|
10
|
+
const SHAREPOINT_NOTE = 'Shared-file download (teams_get_attachment) uses a separate SharePoint token, captured on ' +
|
|
11
|
+
'demand per SharePoint host and short-lived (~53 min). None is held until you open a file, and ' +
|
|
12
|
+
'this healthcheck neither mints nor requires one.';
|
|
13
|
+
/** Static note on the search path. Not probed — a healthy result never depends on it. */
|
|
14
|
+
const SUBSTRATE_NOTE = 'Search (teams_search_messages) uses a separate Microsoft Substrate token for substrate.office.com, ' +
|
|
15
|
+
'captured on demand when you run a search in a Teams tab (the bridge pairing must trust ' +
|
|
16
|
+
'substrate.office.com). Without one, search falls back to a scan of recent conversations; this ' +
|
|
17
|
+
'healthcheck neither mints nor requires one.';
|
|
18
|
+
export function registerHealthcheckTool(server, { chatsvc }) {
|
|
19
|
+
server.registerTool('teams_healthcheck', {
|
|
20
|
+
title: TITLE,
|
|
21
|
+
description: `${credentialHealthcheckDescription(HOST_LABEL)} The credential is the Teams chat-service ` +
|
|
22
|
+
'token behind every tool; the probe is one conversations listing. Also reports the ' +
|
|
23
|
+
'token\'s source (browser capture through the ContextMint Bridge, or TEAMS_ACCESS_TOKEN), ' +
|
|
24
|
+
'its expiry, and how many conversations the listing returned — never the token itself. ' +
|
|
25
|
+
'Call this when a real tool fails and you want to know which hop broke.',
|
|
26
|
+
annotations: toolAnnotations({ title: TITLE, readOnly: true, idempotent: true, openWorld: true }),
|
|
27
|
+
inputSchema: {},
|
|
28
|
+
}, async () => {
|
|
29
|
+
// Set only by a probe that got as far as a listing.
|
|
30
|
+
let conversations = null;
|
|
31
|
+
// TEAMS_CHATSVC_BASE can point the client elsewhere; report what it really talks to.
|
|
32
|
+
const base = new URL(chatsvc.apiBase);
|
|
33
|
+
const result = await runCredentialHealthcheck({
|
|
34
|
+
server,
|
|
35
|
+
prefix: 'teams',
|
|
36
|
+
hostLabel: base.host,
|
|
37
|
+
probePath: `${base.pathname}/users/ME/conversations`,
|
|
38
|
+
// Resolves the token the way every tool does — same cache, same capture.
|
|
39
|
+
resolveCredential: async () => {
|
|
40
|
+
await chatsvc.ensureToken();
|
|
41
|
+
return { source: chatsvc.tokenSource };
|
|
42
|
+
},
|
|
43
|
+
probeFn: async () => {
|
|
44
|
+
conversations = (await chatsvc.listConversations()).length;
|
|
45
|
+
return `${conversations} conversation(s) listed`;
|
|
46
|
+
},
|
|
47
|
+
classifyThrown: (err) => /could not capture a Teams token/i.test(err instanceof Error ? err.message : String(err))
|
|
48
|
+
? { kind: 'token_capture', hint: TOKEN_CAPTURE_HINT }
|
|
49
|
+
: undefined,
|
|
50
|
+
});
|
|
51
|
+
// Read after the resolve, which is what loads (or captures) the token.
|
|
52
|
+
const expiresAt = chatsvc.tokenExpiresAt();
|
|
53
|
+
const chatService = {
|
|
54
|
+
api_base: chatsvc.apiBase,
|
|
55
|
+
token_source: chatsvc.tokenSource,
|
|
56
|
+
token_expires_at: expiresAt === null ? null : new Date(expiresAt).toISOString(),
|
|
57
|
+
token_minutes_remaining: expiresAt === null ? null : Math.round((expiresAt - Date.now()) / 60_000),
|
|
58
|
+
conversations,
|
|
59
|
+
};
|
|
60
|
+
const first = result.content[0];
|
|
61
|
+
let body;
|
|
62
|
+
try {
|
|
63
|
+
body = first === undefined ? undefined : JSON.parse(first.text);
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
body = undefined;
|
|
67
|
+
}
|
|
68
|
+
if (body === null || typeof body !== 'object' || Array.isArray(body)) {
|
|
69
|
+
// Not the JSON envelope this expects: keep its text as-is and report the
|
|
70
|
+
// chat service beside it rather than failing the healthcheck.
|
|
71
|
+
return {
|
|
72
|
+
content: [
|
|
73
|
+
...result.content,
|
|
74
|
+
{
|
|
75
|
+
type: 'text',
|
|
76
|
+
text: JSON.stringify({ chat_service: chatService, sharepoint: SHAREPOINT_NOTE, substrate: SUBSTRATE_NOTE }, null, 2),
|
|
77
|
+
},
|
|
78
|
+
],
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
content: [
|
|
83
|
+
{
|
|
84
|
+
type: 'text',
|
|
85
|
+
text: JSON.stringify({ ...body, chat_service: chatService, sharepoint: SHAREPOINT_NOTE, substrate: SUBSTRATE_NOTE }, null, 2),
|
|
86
|
+
},
|
|
87
|
+
],
|
|
88
|
+
};
|
|
19
89
|
});
|
|
20
90
|
}
|
|
21
|
-
const
|
|
22
|
-
'
|
|
23
|
-
'
|
|
24
|
-
class ChatViewNotOpenError extends Error {
|
|
25
|
-
constructor() {
|
|
26
|
-
super('bridge OK but no chat list rendered — is the Chat view open?');
|
|
27
|
-
this.name = 'ChatViewNotOpenError';
|
|
28
|
-
}
|
|
29
|
-
}
|
|
91
|
+
const TOKEN_CAPTURE_HINT = 'No Teams access token could be captured. Open a signed-in teams.cloud.microsoft tab and click ' +
|
|
92
|
+
'into any chat (that is what makes Teams call its chat service, where the token is read from), ' +
|
|
93
|
+
'then retry.';
|
package/dist/tools/limit.js
CHANGED
|
@@ -1,25 +1,29 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Client-side trimming for every list/read tool.
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* START of a
|
|
2
|
+
* Client-side trimming for every list/read tool. A chat-service read or conversation
|
|
3
|
+
* listing returns hundreds of rows at once; dumping all of them into one
|
|
4
|
+
* result fills the context window with other people's messages the question
|
|
5
|
+
* did not need. Each tool takes an optional `limit` (default
|
|
6
|
+
* {@link DEFAULT_LIMIT}) and keeps the rows that lead its ordering — the
|
|
7
|
+
* NEWEST for anything time-ordered (the END of an oldest-first thread, the
|
|
8
|
+
* START of a newest-first feed), the first for an alphabetical listing.
|
|
9
9
|
*/
|
|
10
10
|
import { z } from 'zod';
|
|
11
11
|
export const DEFAULT_LIMIT = 50;
|
|
12
|
-
/**
|
|
13
|
-
|
|
12
|
+
/**
|
|
13
|
+
* The optional `limit` argument, capped at what the source can return. `kept`
|
|
14
|
+
* says which rows survive, for a listing that is not newest-first.
|
|
15
|
+
*/
|
|
16
|
+
export function limitArg(max, what, kept = 'newest first kept') {
|
|
14
17
|
return z
|
|
15
18
|
.number()
|
|
16
19
|
.int()
|
|
17
20
|
.min(1)
|
|
18
21
|
.max(max)
|
|
19
22
|
.optional()
|
|
20
|
-
.describe(`Maximum ${what} to return,
|
|
23
|
+
.describe(`Maximum ${what} to return, ${kept} (default ${DEFAULT_LIMIT}, max ${max}).`);
|
|
21
24
|
}
|
|
22
|
-
|
|
25
|
+
/** `which` names the kept rows in the hint ("newest", or "first" for a non-time ordering). */
|
|
26
|
+
export function trimRows(rows, limit, newestAt, max, which = 'newest') {
|
|
23
27
|
const n = limit ?? DEFAULT_LIMIT;
|
|
24
28
|
if (rows.length <= n)
|
|
25
29
|
return { rows };
|
|
@@ -29,7 +33,7 @@ export function trimRows(rows, limit, newestAt, max) {
|
|
|
29
33
|
truncated: {
|
|
30
34
|
total: rows.length,
|
|
31
35
|
returned: kept.length,
|
|
32
|
-
hint: `Only the
|
|
36
|
+
hint: `Only the ${which} ${kept.length} of ${rows.length} were returned; pass a larger limit (max ${max}) to read more.`,
|
|
33
37
|
},
|
|
34
38
|
};
|
|
35
39
|
}
|
|
@@ -50,3 +54,30 @@ export function filterSince(rows, since) {
|
|
|
50
54
|
return Number.isNaN(t) || t >= cutoff;
|
|
51
55
|
});
|
|
52
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* The `stopAt` behind `teams_read_conversation` and `teams_get_unread`. It
|
|
59
|
+
* sees each message once, newest first, so it can count: the first wanted
|
|
60
|
+
* message past `limit` is the boundary, and its existence is what says the
|
|
61
|
+
* result was truncated. `horizon` (when given) ends the read at the first
|
|
62
|
+
* message the user had already read — checked first, so a boundary there is
|
|
63
|
+
* never a truncation.
|
|
64
|
+
*/
|
|
65
|
+
export function makeLimitedStopAt(horizon, wanted, limit) {
|
|
66
|
+
let kept = 0;
|
|
67
|
+
let truncated = false;
|
|
68
|
+
return {
|
|
69
|
+
stopAt: (m) => {
|
|
70
|
+
if (horizon !== undefined && Number(m.id) <= horizon)
|
|
71
|
+
return true;
|
|
72
|
+
if (!wanted(m))
|
|
73
|
+
return false;
|
|
74
|
+
if (kept >= limit)
|
|
75
|
+
return (truncated = true);
|
|
76
|
+
kept++;
|
|
77
|
+
return false;
|
|
78
|
+
},
|
|
79
|
+
get truncated() {
|
|
80
|
+
return truncated;
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The conversation listing shared by `teams_list_chats` and
|
|
3
|
+
* `teams_list_teams_and_channels`: one `listConversations` call, normalised
|
|
4
|
+
* against the signed-in user, then filtered by kind, unread state and query.
|
|
5
|
+
* With `unread_only`, the listing's unread flag only nominates candidates; each
|
|
6
|
+
* is confirmed by reading past its horizon (`confirm.ts`).
|
|
7
|
+
*/
|
|
8
|
+
import { z } from 'zod';
|
|
9
|
+
import { confirmedSummary, confirmUnreadCandidates, olderUnreadArg, olderUnreadConversations, olderUnreadReport, sinceCutoff, sinceDaysArg, } from './confirm.js';
|
|
10
|
+
import { wrapApiError } from './errors.js';
|
|
11
|
+
import { searchRecentMessages } from './chat-search.js';
|
|
12
|
+
import { enrichTitles } from './titles.js';
|
|
13
|
+
import { conversationSummary, matchConversations, SELF_CHAT, SELF_CHAT_ALIASES, } from '../model.js';
|
|
14
|
+
/**
|
|
15
|
+
* Whether a conversation's last activity falls in `[since, until]` (either
|
|
16
|
+
* end open when undefined). With either end given, a conversation with no
|
|
17
|
+
* readable last activity is out: nothing places it in the window.
|
|
18
|
+
*/
|
|
19
|
+
export function activeWithin(s, since, until) {
|
|
20
|
+
if (since === undefined && until === undefined)
|
|
21
|
+
return true;
|
|
22
|
+
const t = s.lastActivity === undefined ? Number.NaN : Date.parse(s.lastActivity);
|
|
23
|
+
if (Number.isNaN(t))
|
|
24
|
+
return false;
|
|
25
|
+
return (since === undefined || t >= since) && (until === undefined || t <= until);
|
|
26
|
+
}
|
|
27
|
+
/** The list tools' `since_days`: it narrows `unread_only` only. */
|
|
28
|
+
export const listSinceDaysArg = sinceDaysArg('With unread_only: ');
|
|
29
|
+
/** The list tools' `older_unread`: it needs `unread_only`. */
|
|
30
|
+
export const listOlderUnreadArg = olderUnreadArg('With unread_only: ');
|
|
31
|
+
export const unreadOnlyArg = z
|
|
32
|
+
.boolean()
|
|
33
|
+
.optional()
|
|
34
|
+
.describe('Only return conversations with a real message (not a call recording or other system event) ' +
|
|
35
|
+
'the user has not read yet, each with its unread_count (default false). Exact: every candidate ' +
|
|
36
|
+
'is confirmed by reading its messages past the read marker. Never marks anything read (teams_mark_read does).');
|
|
37
|
+
/** Description text shared by the list tools on what their unread flag means. */
|
|
38
|
+
export const UNREAD_HINT_DESCRIPTION = 'Without unread_only, unread is only a hint from the listing (unread_confirmed: false): it can ' +
|
|
39
|
+
'flag a conversation whose only news is a call recording or other system event. For an exact ' +
|
|
40
|
+
'answer use unread_only (confirmed rows carry unread_confirmed: true and unread_count) or ' +
|
|
41
|
+
'teams_get_unread.';
|
|
42
|
+
/** Real unread messages counted per candidate before unread_count is reported as a lower bound. */
|
|
43
|
+
const CONFIRM_LIMIT = 50;
|
|
44
|
+
/** Raw messages read per candidate — one page; the horizon is usually much nearer. */
|
|
45
|
+
const CONFIRM_MAX_RAW = 50;
|
|
46
|
+
export const includeHiddenArg = z
|
|
47
|
+
.boolean()
|
|
48
|
+
.optional()
|
|
49
|
+
.describe('Also count channels the user has hidden in Teams as unread (default false: Teams shows no ' +
|
|
50
|
+
'unread badge for a hidden channel, so neither does this).');
|
|
51
|
+
/**
|
|
52
|
+
* Whether a conversation is an unread candidate worth confirming: the listing
|
|
53
|
+
* flags it, and it is not a channel hidden in Teams (unless the caller asked
|
|
54
|
+
* for hidden ones — Teams shows a hidden channel no badge).
|
|
55
|
+
*/
|
|
56
|
+
export function isUnreadCandidateFor(s, includeHidden) {
|
|
57
|
+
return s.unread && (includeHidden === true || s.hidden !== true);
|
|
58
|
+
}
|
|
59
|
+
export function queryArg(what) {
|
|
60
|
+
return z
|
|
61
|
+
.string()
|
|
62
|
+
.min(1)
|
|
63
|
+
.optional()
|
|
64
|
+
.describe(`Case-insensitive substring of the ${what}, or an exact conversation id.`);
|
|
65
|
+
}
|
|
66
|
+
/** Description text on the match_reason a query adds to each row. */
|
|
67
|
+
export const MATCH_REASON_DESCRIPTION = 'With a query, each row carries match_reason — the first of "id" (exact id), "title", "team", ' +
|
|
68
|
+
'"participant" (an untitled chat\'s participant) or "message" (what was said, not what the ' +
|
|
69
|
+
'conversation is called) that applies.';
|
|
70
|
+
/** Description text on how an untitled group chat or 1:1 is titled. */
|
|
71
|
+
export const GROUP_TITLE_DESCRIPTION = 'A group chat with no topic is titled "Group chat: " and up to three of its recent senders other ' +
|
|
72
|
+
'than the user, most recent first ("; " between names, "+N" for more), and carries every such ' +
|
|
73
|
+
'recent sender as participants; it is "(untitled group chat)" when no one else wrote recently. ' +
|
|
74
|
+
'A 1:1 is titled by the other person, who is its one participant; it is "(1:1 chat)" when they ' +
|
|
75
|
+
'wrote nothing recently.';
|
|
76
|
+
/**
|
|
77
|
+
* Favorites, then pinned conversations, ahead of the rest — the plain list
|
|
78
|
+
* tools' first sort key, as in the Teams sidebar. 0 between two of a kind, so
|
|
79
|
+
* a stable sort keeps each tool's own order within them.
|
|
80
|
+
*/
|
|
81
|
+
export function favoritesFirst(a, b) {
|
|
82
|
+
const rank = (s) => (s.favorite ? 0 : s.pinned ? 1 : 2);
|
|
83
|
+
return rank(a) - rank(b);
|
|
84
|
+
}
|
|
85
|
+
/** Description text on the favorite / pinned flags and order. */
|
|
86
|
+
export const FAVORITES_DESCRIPTION = 'Conversations the user marked a favorite or pinned in Teams carry favorite: true / pinned: true ' +
|
|
87
|
+
'and, without unread_only, are listed first (favorites, then pinned); unread_only keeps its usual order.';
|
|
88
|
+
/**
|
|
89
|
+
* Every conversation of the given kinds, as summaries. Unsorted: each tool
|
|
90
|
+
* orders its own result. A team's name comes from its own thread, so the
|
|
91
|
+
* summaries are built against the FULL listing before any filtering. With
|
|
92
|
+
* `unread_only`, only candidates a read confirms are kept.
|
|
93
|
+
*/
|
|
94
|
+
export async function listSummaries(chatsvc, filter) {
|
|
95
|
+
const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
|
|
96
|
+
let rows = raw
|
|
97
|
+
.map((c) => conversationSummary(c, me, raw))
|
|
98
|
+
.filter((s) => filter.kinds.includes(s.kind) && activeWithin(s, filter.activeSince, filter.activeUntil));
|
|
99
|
+
if (filter.unread_only)
|
|
100
|
+
rows = rows.filter((s) => isUnreadCandidateFor(s, filter.include_hidden));
|
|
101
|
+
let searched = {};
|
|
102
|
+
if (filter.query !== undefined) {
|
|
103
|
+
// A query can name a group chat or 1:1 by a participant, so every untitled one is titled first.
|
|
104
|
+
const titled = await enrichTitles(chatsvc, raw, me, rows);
|
|
105
|
+
const matched = matchConversations(titled, filter.query, { messages: true });
|
|
106
|
+
if (filter.searchMessages && !namesOne(matched, filter.query)) {
|
|
107
|
+
const found = await searchUnmatched(chatsvc, me, titled, matched, filter.query);
|
|
108
|
+
rows = found.rows;
|
|
109
|
+
if (found.failed > 0)
|
|
110
|
+
searched = { messages_not_searched: found.failed };
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
rows = matched;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (!filter.unread_only) {
|
|
117
|
+
return { rows, ...searched, retitle: async (kept) => ({ rows: await enrichTitles(chatsvc, raw, me, kept) }) };
|
|
118
|
+
}
|
|
119
|
+
const outcome = await confirmUnreadCandidates(chatsvc, raw, me, rows, {
|
|
120
|
+
limit: CONFIRM_LIMIT,
|
|
121
|
+
maxRaw: CONFIRM_MAX_RAW,
|
|
122
|
+
since: sinceCutoff(filter.since_days),
|
|
123
|
+
});
|
|
124
|
+
const errors = (titled) => outcome.failed.length > 0
|
|
125
|
+
? outcome.failed.map((f, i) => ({
|
|
126
|
+
conversation: { id: f.summary.id, title: titled[i].title },
|
|
127
|
+
error: wrapApiError(f.error, 'confirm this conversation is unread').message,
|
|
128
|
+
}))
|
|
129
|
+
: undefined;
|
|
130
|
+
const failedSummaries = outcome.failed.map((f) => f.summary);
|
|
131
|
+
const retitle = async (kept) => {
|
|
132
|
+
const [rows, failed] = await Promise.all([
|
|
133
|
+
enrichTitles(chatsvc, raw, me, kept),
|
|
134
|
+
enrichTitles(chatsvc, raw, me, failedSummaries),
|
|
135
|
+
]);
|
|
136
|
+
const errs = errors(failed);
|
|
137
|
+
return { rows, ...(errs ? { errors: errs } : {}) };
|
|
138
|
+
};
|
|
139
|
+
const errs = errors(failedSummaries);
|
|
140
|
+
// Listed only on request; titled now, since nothing later trims them.
|
|
141
|
+
const listedOlder = filter.older_unread ? outcome.older : [];
|
|
142
|
+
const olderTitled = await enrichTitles(chatsvc, raw, me, listedOlder.map((o) => o.summary));
|
|
143
|
+
return {
|
|
144
|
+
retitle,
|
|
145
|
+
rows: outcome.confirmed.map(({ summary, read }) => ({
|
|
146
|
+
...confirmedSummary(summary, true),
|
|
147
|
+
unread_count: read.messages.length,
|
|
148
|
+
...(read.truncated ? { unread_count_exact: false } : {}),
|
|
149
|
+
})),
|
|
150
|
+
skipped_unreachable: outcome.skippedUnreachable,
|
|
151
|
+
...olderUnreadReport(outcome.older.length, filter.since_days),
|
|
152
|
+
...olderUnreadConversations(listedOlder, olderTitled),
|
|
153
|
+
...(errs ? { errors: errs } : {}),
|
|
154
|
+
...searched,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
/** Whether the match is an exact id or a self-chat alias — a named chat, not a search. */
|
|
158
|
+
function namesOne(matched, query) {
|
|
159
|
+
if (matched.length !== 1)
|
|
160
|
+
return false;
|
|
161
|
+
const [m] = matched;
|
|
162
|
+
return m.match_reason === 'id' || (m.id === SELF_CHAT && SELF_CHAT_ALIASES.has(query.trim().toLowerCase()));
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* `matched` plus every other row in `all` whose recent messages contain the
|
|
166
|
+
* query (`match_reason: "message"`, with `matched_message`), in `all`'s order.
|
|
167
|
+
*/
|
|
168
|
+
async function searchUnmatched(chatsvc, me, all, matched, query) {
|
|
169
|
+
const byId = new Map(matched.map((m) => [m.id, m]));
|
|
170
|
+
const rest = all.filter((s) => !byId.has(s.id));
|
|
171
|
+
const { hits, failed } = await searchRecentMessages(chatsvc, me, rest.map((s) => s.id), query);
|
|
172
|
+
const rows = all.flatMap((s) => {
|
|
173
|
+
const named = byId.get(s.id);
|
|
174
|
+
if (named !== undefined)
|
|
175
|
+
return [named];
|
|
176
|
+
const hit = hits.get(s.id);
|
|
177
|
+
return hit !== undefined ? [{ ...s, match_reason: 'message', matched_message: hit }] : [];
|
|
178
|
+
});
|
|
179
|
+
return { rows, failed };
|
|
180
|
+
}
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { CONFIRM_FLOW_SENTENCE, CONFIRM_INJECTION_RULE, confirmTokenParam, confirmWrite, mapWithConcurrency, McpToolError, toolAnnotations, WriteOutcomeUnknownError, } from '@chrischall/mcp-utils';
|
|
3
|
+
import { outcomeUnknownStatus } from '../chatsvc.js';
|
|
4
|
+
import { clipText } from '../compose.js';
|
|
5
|
+
import { htmlToText, isUnread, readHorizon, SELF_CHAT, senderMri } from '../model.js';
|
|
6
|
+
import { confirmedSummary } from './confirm.js';
|
|
7
|
+
import { resolveListed } from './conversation.js';
|
|
8
|
+
import { wrapApiError } from './errors.js';
|
|
9
|
+
import { untrustedField, untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
|
|
10
|
+
const TOOL = 'teams_mark_read';
|
|
11
|
+
/** Messages read to find the newest one — one page; a page is not strictly ordered, so all of it is looked at. */
|
|
12
|
+
const NEWEST_PAGE = 50;
|
|
13
|
+
/** Previewed text of the message the marker moves to. */
|
|
14
|
+
const PREVIEW_CHARS = 200;
|
|
15
|
+
/** Markers moved at once by a read tool's `mark_read`. */
|
|
16
|
+
const MARK_CONCURRENCY = 4;
|
|
17
|
+
/** The `mark_read` argument the read tools share. */
|
|
18
|
+
export const markReadArg = z
|
|
19
|
+
.boolean()
|
|
20
|
+
.optional()
|
|
21
|
+
.describe('After the read, also mark it read in Teams: move the read marker of each conversation returned up to ' +
|
|
22
|
+
'the newest message returned (default false — the read leaves the unread badges alone). Never moves a ' +
|
|
23
|
+
'marker backwards, and never past an unread message the caller did not receive: a conversation whose ' +
|
|
24
|
+
'read was cut short is left as it was (marked_read: { skipped, hint }). Not allowed with format ' +
|
|
25
|
+
'"summary", which returns no message text. A write, so it asks the user to confirm first, as ' +
|
|
26
|
+
'teams_mark_read does.');
|
|
27
|
+
/**
|
|
28
|
+
* Refuse `mark_read` with `format: "summary"`: the caller would get no message
|
|
29
|
+
* text, so marking would clear badges on messages nobody read.
|
|
30
|
+
*/
|
|
31
|
+
export function assertMarkReadFormat(markRead, format) {
|
|
32
|
+
if (markRead && format === 'summary') {
|
|
33
|
+
throw new McpToolError('mark_read cannot be combined with format "summary": a summary returns no messages, so nothing would have been read.', {
|
|
34
|
+
hint: 'Read with format "full" or "compact" to mark what is returned, or use teams_mark_read to mark a conversation read deliberately.',
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** Description text for a read tool that takes `mark_read`. */
|
|
39
|
+
export const MARK_READ_DESCRIPTION = 'By default this does NOT mark anything read — the user\'s Teams unread badges are unaffected; pass ' +
|
|
40
|
+
'mark_read: true (or use teams_mark_read) to clear them. mark_read never marks a message the caller did ' +
|
|
41
|
+
'not receive: it is refused with format "summary" (compact is fine), and a conversation whose read was ' +
|
|
42
|
+
'cut short, leaving unread messages older than those returned, keeps its marker and reports ' +
|
|
43
|
+
'marked_read: { skipped: "truncated" (or "since"), hint }. ';
|
|
44
|
+
/** The request path a marker move PUTs to — the same string the client builds. */
|
|
45
|
+
export function horizonPath(conversationId) {
|
|
46
|
+
return `/users/ME/conversations/${encodeURIComponent(conversationId)}/properties?name=consumptionhorizon`;
|
|
47
|
+
}
|
|
48
|
+
/** The id of the newest of `messages` (a message's id is its arrival ms), or `undefined` for none. */
|
|
49
|
+
export function newestMessageId(messages) {
|
|
50
|
+
let best;
|
|
51
|
+
for (const m of messages) {
|
|
52
|
+
const n = Number(m.id);
|
|
53
|
+
if (Number.isFinite(n) && (best === undefined || n > Number(best)))
|
|
54
|
+
best = m.id;
|
|
55
|
+
}
|
|
56
|
+
return best;
|
|
57
|
+
}
|
|
58
|
+
/** The current marker as a message id (its arrival ms), or `null` for a conversation never opened. */
|
|
59
|
+
export function horizonMessageId(conv) {
|
|
60
|
+
const h = readHorizon(conv);
|
|
61
|
+
return h > 0 ? String(h) : null;
|
|
62
|
+
}
|
|
63
|
+
/** Whether moving the marker to `target` moves it forwards. */
|
|
64
|
+
export function advancesHorizon(conv, target) {
|
|
65
|
+
if (target === undefined)
|
|
66
|
+
return false;
|
|
67
|
+
const n = Number(target);
|
|
68
|
+
return Number.isFinite(n) && n > readHorizon(conv);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* The confirmation for a read tool's `mark_read`: one approval covering every
|
|
72
|
+
* move, each conversation's title fenced as a read tool's result is.
|
|
73
|
+
* Resolves `undefined` when the moves may proceed (see `confirmWrite`).
|
|
74
|
+
*/
|
|
75
|
+
export async function confirmMarks(ctx, opts) {
|
|
76
|
+
const { plans } = opts;
|
|
77
|
+
const many = plans.length > 1;
|
|
78
|
+
return confirmWrite(ctx, {
|
|
79
|
+
tool: opts.tool,
|
|
80
|
+
action: 'chat.mark_read',
|
|
81
|
+
message: 'Review and confirm marking these Teams messages read:',
|
|
82
|
+
summary: many
|
|
83
|
+
? `Mark ${plans.length} conversations read up to their newest returned message`
|
|
84
|
+
: `Mark a ${plans[0].summary.kind} ${JSON.stringify(plans[0].summary.title)} read up to message ${plans[0].target}`,
|
|
85
|
+
account: opts.me,
|
|
86
|
+
...(many
|
|
87
|
+
? { payload: plans.map((p) => ({ conversation: p.summary.id, up_to_message_id: p.target })) }
|
|
88
|
+
: { target: `${plans[0].summary.id}/${plans[0].target}`, request: { method: 'PUT', path: horizonPath(plans[0].summary.id) } }),
|
|
89
|
+
preview: {
|
|
90
|
+
conversations: untrustedField(plans.map((p) => ({
|
|
91
|
+
id: p.summary.id,
|
|
92
|
+
title: p.summary.title,
|
|
93
|
+
kind: p.summary.kind,
|
|
94
|
+
previous_horizon_message_id: p.previous,
|
|
95
|
+
up_to_message_id: p.target,
|
|
96
|
+
}))),
|
|
97
|
+
...(opts.note !== undefined ? { note: opts.note } : {}),
|
|
98
|
+
},
|
|
99
|
+
confirmToken: opts.confirmToken,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
/** Why a write went unconfirmed, for a warning. */
|
|
103
|
+
function unconfirmedWhy(e) {
|
|
104
|
+
const status = outcomeUnknownStatus(e);
|
|
105
|
+
return e.timedOut ? 'it did not answer in time' : status !== undefined ? `it answered HTTP ${status}` : 'the connection dropped';
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Make every move, a few at a time. One failing never costs the others: an
|
|
109
|
+
* unconfirmed or refused move is `marked_read: false` with a warning.
|
|
110
|
+
*/
|
|
111
|
+
export async function applyMarks(chatsvc, plans) {
|
|
112
|
+
const results = await mapWithConcurrency(plans, MARK_CONCURRENCY, async (p) => {
|
|
113
|
+
try {
|
|
114
|
+
await chatsvc.setConsumptionHorizon(p.summary.id, p.target);
|
|
115
|
+
return { marked_read: true };
|
|
116
|
+
}
|
|
117
|
+
catch (e) {
|
|
118
|
+
if (e instanceof WriteOutcomeUnknownError) {
|
|
119
|
+
return {
|
|
120
|
+
marked_read: false,
|
|
121
|
+
mark_read_warning: `Teams did not confirm moving the read marker (${unconfirmedWhy(e)}); it may have moved — ` +
|
|
122
|
+
'retrying is harmless.',
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
return { marked_read: false, mark_read_warning: wrapApiError(e, 'mark this conversation read').message };
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
return new Map(plans.map((p, i) => [p.summary.id, results[i]]));
|
|
129
|
+
}
|
|
130
|
+
export function registerMarkReadTools(server, { chatsvc }) {
|
|
131
|
+
server.registerTool(TOOL, {
|
|
132
|
+
title: 'Mark a Teams conversation read',
|
|
133
|
+
description: 'Mark a chat or channel read in Teams, clearing its unread badge: moves the signed-in user\'s read ' +
|
|
134
|
+
'marker up to up_to_message_id (from teams_read_conversation), or by default up to the newest message ' +
|
|
135
|
+
'in the conversation. conversation is an id or name as for teams_read_conversation; ' +
|
|
136
|
+
`"${SELF_CHAT}" (or "notes" / "self") is the user's own notes self-chat — use it to try this tool. ` +
|
|
137
|
+
'The marker never moves backwards: when it is already at or past the target, nothing is written and ' +
|
|
138
|
+
'status is "already_read". Returns the conversation, previous_horizon_message_id (null if it was never ' +
|
|
139
|
+
'opened) and new_horizon_message_id; status "unknown" means Teams did not confirm the move — retrying is ' +
|
|
140
|
+
'harmless. teams_read_conversation and teams_get_unread can do the same after a read with mark_read. ' +
|
|
141
|
+
CONFIRM_FLOW_SENTENCE +
|
|
142
|
+
' The preview shows the conversation, the message the marker moves to and where it was. ' +
|
|
143
|
+
CONFIRM_INJECTION_RULE +
|
|
144
|
+
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
145
|
+
annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
|
|
146
|
+
inputSchema: {
|
|
147
|
+
conversation: z
|
|
148
|
+
.string()
|
|
149
|
+
.min(1)
|
|
150
|
+
.describe(`The conversation id (or "${SELF_CHAT}" — also by the name "notes" or "self" — for the self-chat), ` +
|
|
151
|
+
"or a case-insensitive substring of the chat title, channel name, team name or an untitled chat's participant names."),
|
|
152
|
+
up_to_message_id: z
|
|
153
|
+
.string()
|
|
154
|
+
.min(1)
|
|
155
|
+
.optional()
|
|
156
|
+
.describe('Mark read up to and including this message, as teams_read_conversation lists it (default: the ' +
|
|
157
|
+
'newest message in the conversation). Messages after it stay unread.'),
|
|
158
|
+
confirmToken: confirmTokenParam,
|
|
159
|
+
},
|
|
160
|
+
}, async ({ conversation, up_to_message_id, confirmToken }, ctx) => {
|
|
161
|
+
try {
|
|
162
|
+
const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
|
|
163
|
+
const summary = await resolveListed(chatsvc, raw, me, conversation, 'mark read');
|
|
164
|
+
// The self-chat resolves even when the listing does not carry it.
|
|
165
|
+
const conv = raw.find((c) => c.id === summary.id) ?? { id: summary.id };
|
|
166
|
+
const previous = horizonMessageId(conv);
|
|
167
|
+
const page = await chatsvc.getMessages(summary.id, { max: NEWEST_PAGE, pageSize: NEWEST_PAGE });
|
|
168
|
+
let target;
|
|
169
|
+
if (up_to_message_id !== undefined) {
|
|
170
|
+
target = await chatsvc.getMessage(summary.id, up_to_message_id);
|
|
171
|
+
if (target === undefined) {
|
|
172
|
+
throw new McpToolError(`There is no message ${up_to_message_id} in this conversation to mark read up to.`, {
|
|
173
|
+
hint: 'Take message ids from teams_read_conversation, or leave up_to_message_id out to mark it all read.',
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
else {
|
|
178
|
+
const newest = newestMessageId(page);
|
|
179
|
+
target = page.find((m) => m.id === newest);
|
|
180
|
+
}
|
|
181
|
+
if (!advancesHorizon(conv, target?.id)) {
|
|
182
|
+
return untrustedResult({
|
|
183
|
+
status: 'already_read',
|
|
184
|
+
conversation: summary,
|
|
185
|
+
previous_horizon_message_id: previous,
|
|
186
|
+
new_horizon_message_id: previous,
|
|
187
|
+
hint: target === undefined
|
|
188
|
+
? 'The conversation has no messages, so there is nothing to mark read.'
|
|
189
|
+
: `The read marker is already at or past message ${target.id}; it never moves backwards, so nothing was changed.`,
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
const to = target.id;
|
|
193
|
+
const gate = await confirmWrite(ctx, {
|
|
194
|
+
tool: TOOL,
|
|
195
|
+
action: 'chat.mark_read',
|
|
196
|
+
message: 'Review and confirm marking this Teams conversation read:',
|
|
197
|
+
// The title is someone else's text: JSON-quoted so it cannot break out of its quotes.
|
|
198
|
+
summary: `Mark ${summary.kind} ${JSON.stringify(summary.title)} read up to message ${to}`,
|
|
199
|
+
// The signed-in user, so an approval minted under one account never marks another's chats.
|
|
200
|
+
account: me,
|
|
201
|
+
target: `${summary.id}/${to}`,
|
|
202
|
+
// The client time in the body is minted when the marker moves, so it is not bound.
|
|
203
|
+
request: { method: 'PUT', path: horizonPath(summary.id) },
|
|
204
|
+
preview: {
|
|
205
|
+
conversation: untrustedField({ id: summary.id, title: summary.title, kind: summary.kind }),
|
|
206
|
+
up_to_message: untrustedField({
|
|
207
|
+
id: to,
|
|
208
|
+
sender: target.imdisplayname?.trim() || senderMri(target.from) || 'unknown',
|
|
209
|
+
preview: clipText(htmlToText(target.content ?? ''), PREVIEW_CHARS),
|
|
210
|
+
}),
|
|
211
|
+
previous_horizon_message_id: previous,
|
|
212
|
+
},
|
|
213
|
+
confirmToken,
|
|
214
|
+
});
|
|
215
|
+
if (gate)
|
|
216
|
+
return gate;
|
|
217
|
+
// What the page shows past the new marker: anything from someone else is still unread.
|
|
218
|
+
const stillUnread = page.some((m) => isUnread(m, Number(to), me));
|
|
219
|
+
const after = confirmedSummary(summary, stillUnread);
|
|
220
|
+
try {
|
|
221
|
+
await chatsvc.setConsumptionHorizon(summary.id, to);
|
|
222
|
+
}
|
|
223
|
+
catch (e) {
|
|
224
|
+
if (!(e instanceof WriteOutcomeUnknownError))
|
|
225
|
+
throw e;
|
|
226
|
+
return untrustedResult({
|
|
227
|
+
status: 'unknown',
|
|
228
|
+
conversation: summary,
|
|
229
|
+
previous_horizon_message_id: previous,
|
|
230
|
+
new_horizon_message_id: to,
|
|
231
|
+
warning: `Teams did not confirm moving the read marker (${unconfirmedWhy(e)}); it may have moved. ` +
|
|
232
|
+
'Retrying is harmless — moving it to the same message again is one move.',
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
return untrustedResult({
|
|
236
|
+
status: 'marked_read',
|
|
237
|
+
conversation: after,
|
|
238
|
+
previous_horizon_message_id: previous,
|
|
239
|
+
new_horizon_message_id: to,
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
catch (err) {
|
|
243
|
+
throw wrapApiError(err, 'mark the conversation read');
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
}
|