@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
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { createFileStatePersistence, resolveStateFile, } from '@chrischall/mcp-utils/session';
|
|
2
|
+
import { parseBoolEnv } from '@chrischall/mcp-utils';
|
|
3
|
+
import { reportCacheWriteFailure } from './token-cache.js';
|
|
4
|
+
/**
|
|
5
|
+
* Where the captured Substrate search token is cached between runs.
|
|
6
|
+
*
|
|
7
|
+
* Its own file, beside `token.json` (chat service) and `sharepoint-tokens.json`:
|
|
8
|
+
* a different audience with its own lifetime, and one token overall (Substrate
|
|
9
|
+
* has a single host), so a plain `BearerTokens`, not a per-host map.
|
|
10
|
+
*/
|
|
11
|
+
export function substrateTokenCachePath(env = process.env) {
|
|
12
|
+
return resolveStateFile({
|
|
13
|
+
env,
|
|
14
|
+
envVar: 'TEAMS_SUBSTRATE_TOKEN_FILE',
|
|
15
|
+
subdir: '.microsoft-teams-mcp',
|
|
16
|
+
fileName: 'substrate-token.json',
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
/** Same `BearerTokens` guard as the other caches; copied, as it is module-private there. */
|
|
20
|
+
function isToken(raw) {
|
|
21
|
+
if (raw === null || typeof raw !== 'object')
|
|
22
|
+
return false;
|
|
23
|
+
const t = raw;
|
|
24
|
+
return (typeof t.accessToken === 'string' &&
|
|
25
|
+
t.accessToken !== '' &&
|
|
26
|
+
typeof t.expiresAt === 'number' &&
|
|
27
|
+
(t.refreshToken === undefined || typeof t.refreshToken === 'string'));
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The Substrate token cache, or `null` when it is off or there is nothing to
|
|
31
|
+
* cache. Gated like the SharePoint cache: `TEAMS_TOKEN_CACHE` (default on), and
|
|
32
|
+
* off under `TEAMS_DISABLE_FETCHPROXY` — the bridge is the only source of a
|
|
33
|
+
* Substrate token. A failed write is reported, never thrown.
|
|
34
|
+
*/
|
|
35
|
+
export function createSubstrateTokenCache(env = process.env) {
|
|
36
|
+
if (!parseBoolEnv('TEAMS_TOKEN_CACHE', { env, default: true }))
|
|
37
|
+
return null;
|
|
38
|
+
if (parseBoolEnv('TEAMS_DISABLE_FETCHPROXY', { env }))
|
|
39
|
+
return null;
|
|
40
|
+
const file = createFileStatePersistence({
|
|
41
|
+
filePath: substrateTokenCachePath(env),
|
|
42
|
+
boundTo: 'fetchproxy',
|
|
43
|
+
validate: (raw) => (isToken(raw) ? raw : null),
|
|
44
|
+
});
|
|
45
|
+
return {
|
|
46
|
+
load: () => file.load(),
|
|
47
|
+
save(tokens) {
|
|
48
|
+
try {
|
|
49
|
+
file.save(tokens);
|
|
50
|
+
}
|
|
51
|
+
catch (err) {
|
|
52
|
+
reportCacheWriteFailure(err);
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
clear() {
|
|
56
|
+
try {
|
|
57
|
+
file.clear();
|
|
58
|
+
}
|
|
59
|
+
catch (err) {
|
|
60
|
+
reportCacheWriteFailure(err);
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
}
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Microsoft Substrate search client — the backend Teams' own search box
|
|
3
|
+
* uses, and the primary path of `teams_search_messages` (the client-side
|
|
4
|
+
* chat-service scan in `tools/search.ts` is the fallback).
|
|
5
|
+
*
|
|
6
|
+
* POST https://substrate.office.com/searchservice/api/v2/query
|
|
7
|
+
* [Authorization: Bearer <token>, Content-Type: application/json]
|
|
8
|
+
* { entityRequests: [{ entityType: "Message", contentSources: ["Teams"],
|
|
9
|
+
* query: { queryString, displayQueryString }, from, size,
|
|
10
|
+
* sort: [{ Field: "Time", SortDirection: "Desc" }] }],
|
|
11
|
+
* cvid, logicalId, scenario: { Name: "powerbar", … } }
|
|
12
|
+
* → { EntitySets: [{ ResultSets: [{ Total, MoreResultsAvailable,
|
|
13
|
+
* Results: [{ HitHighlightedSummary, Source: {
|
|
14
|
+
* ClientThreadId, ClientConversationId, InternetMessageId,
|
|
15
|
+
* DateTimeSent, Sender: { EmailAddress: { Name, Address } },
|
|
16
|
+
* Preview, Subject, ChannelName, TeamName, … } }] }] }] }
|
|
17
|
+
*
|
|
18
|
+
* Verified live 2026-10-12 (token captured off the Teams tab, replayed from
|
|
19
|
+
* Node; read-only queries such as "deploy"; a redacted response is
|
|
20
|
+
* `tests/fixtures/substrate-query-response.json`):
|
|
21
|
+
* - No header beyond the bearer and the JSON content type is needed. The
|
|
22
|
+
* token `substrate-auth.ts` captures off `/searchservice/*` worked (an
|
|
23
|
+
* app-GUID audience, ~1.4h lifetime); so did one captured off another
|
|
24
|
+
* substrate.office.com path (audience `https://outlook.office.com/`).
|
|
25
|
+
* - Body: `cvid`/`logicalId` and `scenario.Name` are REQUIRED (400 without);
|
|
26
|
+
* the sort must be `Field: "Time"` with capitalised keys (`DateTime`, or
|
|
27
|
+
* `field`/`sortDirection`, is a 400). `size` up to 200 works; `from`
|
|
28
|
+
* pages without overlap, newest first.
|
|
29
|
+
* - Response: the Teams conversation is `Source.ClientThreadId`;
|
|
30
|
+
* `ClientConversationId` is the same plus `;messageid=<root>` for a
|
|
31
|
+
* channel post or reply. `InternetMessageId` is the Teams message id
|
|
32
|
+
* (equal to the root id on a root post). `Sender` (= `From`) carries a
|
|
33
|
+
* display name and an SMTP address — NO MRI, and the address need not be
|
|
34
|
+
* the token's UPN, so `fromMe` cannot be decided from a hit. `Preview`
|
|
35
|
+
* (= `HitHighlightedSummary`, no highlight markup) is PLAIN TEXT capped
|
|
36
|
+
* at ~255 characters; there is no body. `Subject` is set on a channel
|
|
37
|
+
* root post with a subject. A query with no hits has no `Results` key.
|
|
38
|
+
* `Total` is an estimate (one phrase query said 86 and paged to 11).
|
|
39
|
+
* - Matching is Substrate's: words ANDed with stemming ("deploy" matches
|
|
40
|
+
* "deployed", "deployment"), `"phrases"`, `OR`; not window-bound (all
|
|
41
|
+
* history unless restricted).
|
|
42
|
+
* - Server-side restrictions in the query string, ANDed with a
|
|
43
|
+
* parenthesised user query: `ClientThreadId:"<conversation id>"` (also
|
|
44
|
+
* for `48:notes`) and `sent>=<ISO date-time, UNQUOTED>` (a quoted value
|
|
45
|
+
* was mis-read). `from:<word>` exists but matches name/address word
|
|
46
|
+
* PREFIXES, not the "display name contains" the tool promises, so `from`
|
|
47
|
+
* stays client-side.
|
|
48
|
+
* - A bad token is a 401.
|
|
49
|
+
*
|
|
50
|
+
* As with the other clients, the bridge is touched only to capture the token
|
|
51
|
+
* (`substrate-auth.ts`); every request is a plain Node `fetch`.
|
|
52
|
+
*/
|
|
53
|
+
import { decodeJwtExp, fetchBounded, McpToolError, parseBoolEnv } from '@chrischall/mcp-utils';
|
|
54
|
+
import { TokenManager } from '@chrischall/mcp-utils/session';
|
|
55
|
+
import { createSubstrateTokenCache } from './substrate-token-cache.js';
|
|
56
|
+
export const SUBSTRATE_QUERY_URL = 'https://substrate.office.com/searchservice/api/v2/query';
|
|
57
|
+
/**
|
|
58
|
+
* How long after a failed capture (or a 401 on a freshly captured token) an
|
|
59
|
+
* unforced search skips straight to failing
|
|
60
|
+
* (so mode "auto" falls back to the scan at once) instead of holding the call
|
|
61
|
+
* for another capture window. Mode "substrate" forces a fresh attempt.
|
|
62
|
+
*/
|
|
63
|
+
export const CAPTURE_RETRY_COOLDOWN_MS = 10 * 60 * 1000;
|
|
64
|
+
/** Fallback lifetime for a token whose `exp` we cannot read (as in `sharepoint.ts`). */
|
|
65
|
+
const UNKNOWN_TOKEN_TTL_MS = 10 * 60 * 1000;
|
|
66
|
+
/** Stands in for a refresh token this flow does not have (see `sharepoint.ts`). */
|
|
67
|
+
const RECAPTURE_SENTINEL = 'fetchproxy:recapture';
|
|
68
|
+
/** Per-request deadline, covering the body read. */
|
|
69
|
+
const REQUEST_TIMEOUT_MS = 30_000;
|
|
70
|
+
/** A search response is a page of summaries; anything near this is not one. */
|
|
71
|
+
const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
72
|
+
function toBearerTokens(accessToken) {
|
|
73
|
+
let expiresAt;
|
|
74
|
+
try {
|
|
75
|
+
expiresAt = decodeJwtExp(accessToken) * 1000;
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
expiresAt = Date.now() + UNKNOWN_TOKEN_TTL_MS;
|
|
79
|
+
}
|
|
80
|
+
return { accessToken, refreshToken: RECAPTURE_SENTINEL, expiresAt };
|
|
81
|
+
}
|
|
82
|
+
/** Capture lazily, so boot never loads the bridge (see `sharepoint.ts`). */
|
|
83
|
+
async function captureSubstrateTokenLazily() {
|
|
84
|
+
const mod = await import('./substrate-auth.js');
|
|
85
|
+
return mod.captureSubstrateTokenViaFetchproxy();
|
|
86
|
+
}
|
|
87
|
+
/** `sent>=` takes an unquoted ISO date-time (a quoted one was mis-read live); whole seconds, rounded down. */
|
|
88
|
+
function sentBound(ms) {
|
|
89
|
+
return new Date(Math.floor(ms / 1000) * 1000).toISOString().replace(/\.000Z$/, 'Z');
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The query string: the user's query, ANDed with the verified KQL-style
|
|
93
|
+
* property restrictions. With a restriction, the user's query is
|
|
94
|
+
* parenthesised so an `OR` in it cannot escape the filter (verified live).
|
|
95
|
+
*/
|
|
96
|
+
export function buildQueryString(req) {
|
|
97
|
+
const filters = [];
|
|
98
|
+
if (req.conversationId !== undefined) {
|
|
99
|
+
if (/["\s]/.test(req.conversationId)) {
|
|
100
|
+
throw new McpToolError('That conversation id cannot be expressed as a Substrate filter.', { kind: 'unknown' });
|
|
101
|
+
}
|
|
102
|
+
filters.push(`ClientThreadId:"${req.conversationId}"`);
|
|
103
|
+
}
|
|
104
|
+
if (req.sentAfter !== undefined && Number.isFinite(req.sentAfter))
|
|
105
|
+
filters.push(`sent>=${sentBound(req.sentAfter)}`);
|
|
106
|
+
return filters.length === 0 ? req.query : [`(${req.query})`, ...filters].join(' ');
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The query body, as verified live 2026-10-12. Required (400 without them):
|
|
110
|
+
* `cvid` + `logicalId`, and a `scenario` with a `Name`. `sort` must be
|
|
111
|
+
* `{ Field: "Time", SortDirection: "Desc" }` — `DateTime`, or lower-case keys,
|
|
112
|
+
* are a 400.
|
|
113
|
+
*/
|
|
114
|
+
export function buildQueryBody(req) {
|
|
115
|
+
const cvid = crypto.randomUUID();
|
|
116
|
+
return {
|
|
117
|
+
entityRequests: [
|
|
118
|
+
{
|
|
119
|
+
entityType: 'Message',
|
|
120
|
+
contentSources: ['Teams'],
|
|
121
|
+
query: { queryString: buildQueryString(req), displayQueryString: req.query },
|
|
122
|
+
from: req.from,
|
|
123
|
+
size: req.size,
|
|
124
|
+
sort: [{ Field: 'Time', SortDirection: 'Desc' }],
|
|
125
|
+
},
|
|
126
|
+
],
|
|
127
|
+
cvid,
|
|
128
|
+
logicalId: cvid,
|
|
129
|
+
scenario: {
|
|
130
|
+
Name: 'powerbar',
|
|
131
|
+
Dimensions: [
|
|
132
|
+
{ DimensionName: 'QueryType', DimensionValue: 'Messages' },
|
|
133
|
+
{ DimensionName: 'FormFactor', DimensionValue: 'general.web.reactSearch' },
|
|
134
|
+
],
|
|
135
|
+
},
|
|
136
|
+
QueryAlterationOptions: { EnableSuggestion: false, EnableAlteration: false },
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
function obj(v) {
|
|
140
|
+
return v !== null && typeof v === 'object' && !Array.isArray(v) ? v : undefined;
|
|
141
|
+
}
|
|
142
|
+
function str(v) {
|
|
143
|
+
return typeof v === 'string' && v.trim() !== '' ? v : undefined;
|
|
144
|
+
}
|
|
145
|
+
function isoOf(v) {
|
|
146
|
+
const s = str(v);
|
|
147
|
+
if (s === undefined)
|
|
148
|
+
return undefined;
|
|
149
|
+
const ms = Date.parse(s);
|
|
150
|
+
return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined;
|
|
151
|
+
}
|
|
152
|
+
function mapResult(raw) {
|
|
153
|
+
const r = obj(raw);
|
|
154
|
+
const source = obj(r?.Source);
|
|
155
|
+
if (r === undefined || source === undefined)
|
|
156
|
+
return undefined;
|
|
157
|
+
// `19:x@thread.tacv2;messageid=<root>` for a channel post or reply; the bare id for a chat.
|
|
158
|
+
const clientConv = str(source.ClientConversationId) ?? str(source.ClientThreadId);
|
|
159
|
+
if (clientConv === undefined)
|
|
160
|
+
return undefined;
|
|
161
|
+
const [conversationId, ...params] = clientConv.split(';');
|
|
162
|
+
if (str(conversationId) === undefined)
|
|
163
|
+
return undefined;
|
|
164
|
+
const root = params.map((p) => /^messageid=(.+)$/i.exec(p.trim())?.[1]).find((v) => v !== undefined);
|
|
165
|
+
const messageId = str(source.InternetMessageId);
|
|
166
|
+
// `Sender` and `From` were identical on every hit seen live.
|
|
167
|
+
const from = obj(obj(source.Sender)?.EmailAddress) ?? obj(obj(source.From)?.EmailAddress);
|
|
168
|
+
const text = str(source.Preview) ?? str(r.HitHighlightedSummary) ?? '';
|
|
169
|
+
const time = isoOf(source.DateTimeSent) ?? isoOf(source.DateTimeReceived) ?? isoOf(source.DateTimeCreated);
|
|
170
|
+
const sender = str(from?.Name);
|
|
171
|
+
const senderEmail = str(from?.Address);
|
|
172
|
+
const subject = str(source.Subject);
|
|
173
|
+
return {
|
|
174
|
+
conversationId,
|
|
175
|
+
...(messageId !== undefined ? { messageId } : {}),
|
|
176
|
+
...(time !== undefined ? { time } : {}),
|
|
177
|
+
...(sender !== undefined ? { sender } : {}),
|
|
178
|
+
...(senderEmail !== undefined ? { senderEmail } : {}),
|
|
179
|
+
text,
|
|
180
|
+
...(subject !== undefined ? { subject } : {}),
|
|
181
|
+
...(root !== undefined && root !== messageId ? { replyTo: root } : {}),
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
/** Parse a v2 query response into a page of message hits. Never throws on shape. */
|
|
185
|
+
export function parseQueryResponse(body) {
|
|
186
|
+
const sets = obj(body)?.EntitySets;
|
|
187
|
+
const firstSet = Array.isArray(sets) ? obj(sets[0]) : undefined;
|
|
188
|
+
const resultSets = firstSet?.ResultSets;
|
|
189
|
+
const rs = Array.isArray(resultSets) ? obj(resultSets[0]) : undefined;
|
|
190
|
+
if (rs === undefined)
|
|
191
|
+
return { results: [], moreAvailable: false, unmapped: 0 };
|
|
192
|
+
// A query with no hits has no `Results` key at all (seen live).
|
|
193
|
+
const raw = Array.isArray(rs.Results) ? rs.Results : [];
|
|
194
|
+
const results = [];
|
|
195
|
+
let unmapped = 0;
|
|
196
|
+
for (const r of raw) {
|
|
197
|
+
const m = mapResult(r);
|
|
198
|
+
if (m === undefined)
|
|
199
|
+
unmapped++;
|
|
200
|
+
else
|
|
201
|
+
results.push(m);
|
|
202
|
+
}
|
|
203
|
+
return {
|
|
204
|
+
results,
|
|
205
|
+
...(typeof rs.Total === 'number' ? { total: rs.Total } : {}),
|
|
206
|
+
moreAvailable: rs.MoreResultsAvailable === true,
|
|
207
|
+
unmapped,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
export class SubstrateClient {
|
|
211
|
+
#fetchImpl;
|
|
212
|
+
#configError = null;
|
|
213
|
+
#manager;
|
|
214
|
+
/**
|
|
215
|
+
* When the last capture failed, or a freshly captured token was still
|
|
216
|
+
* refused (401), and how; cleared by a successful capture.
|
|
217
|
+
*/
|
|
218
|
+
#captureFailure = null;
|
|
219
|
+
constructor(opts = {}) {
|
|
220
|
+
const env = opts.env ?? process.env;
|
|
221
|
+
const capture = opts.captureToken ?? captureSubstrateTokenLazily;
|
|
222
|
+
// A receiver-safe wrapper, never the bare global (see `sharepoint.ts`).
|
|
223
|
+
this.#fetchImpl = opts.fetchImpl ?? ((input, init) => fetch(input, init));
|
|
224
|
+
const recapture = async () => {
|
|
225
|
+
try {
|
|
226
|
+
const tokens = toBearerTokens(await capture());
|
|
227
|
+
this.#captureFailure = null;
|
|
228
|
+
return tokens;
|
|
229
|
+
}
|
|
230
|
+
catch (error) {
|
|
231
|
+
this.#captureFailure = { at: Date.now(), error };
|
|
232
|
+
throw error;
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
const persistence = createSubstrateTokenCache(env);
|
|
236
|
+
this.#manager = new TokenManager({
|
|
237
|
+
initial: recapture,
|
|
238
|
+
refresh: recapture,
|
|
239
|
+
...(persistence ? { persistence } : {}),
|
|
240
|
+
});
|
|
241
|
+
// Like SharePoint, there is no direct-token env var: the bridge is the only source.
|
|
242
|
+
if (parseBoolEnv('TEAMS_DISABLE_FETCHPROXY', { env })) {
|
|
243
|
+
this.#configError = new McpToolError('Substrate search is disabled (no token source).', {
|
|
244
|
+
kind: 'no_credential',
|
|
245
|
+
hint: 'Unset TEAMS_DISABLE_FETCHPROXY so a Substrate token can be captured from a signed-in Teams tab.',
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
/** Whether a token could be obtained at all (the bridge is not disabled). */
|
|
250
|
+
isConfigured() {
|
|
251
|
+
return this.#configError === null;
|
|
252
|
+
}
|
|
253
|
+
async searchMessages(req, opts = {}) {
|
|
254
|
+
if (this.#configError)
|
|
255
|
+
throw this.#configError;
|
|
256
|
+
const failed = this.#captureFailure;
|
|
257
|
+
if (!opts.force && failed !== null && Date.now() - failed.at < CAPTURE_RETRY_COOLDOWN_MS)
|
|
258
|
+
throw failed.error;
|
|
259
|
+
let text = '';
|
|
260
|
+
const res = await this.#manager.withAuth(async (token) => {
|
|
261
|
+
const r = await fetchBounded(SUBSTRATE_QUERY_URL, {
|
|
262
|
+
method: 'POST',
|
|
263
|
+
headers: {
|
|
264
|
+
authorization: `Bearer ${token}`,
|
|
265
|
+
'content-type': 'application/json',
|
|
266
|
+
accept: 'application/json',
|
|
267
|
+
},
|
|
268
|
+
body: JSON.stringify(buildQueryBody(req)),
|
|
269
|
+
redirect: 'error',
|
|
270
|
+
}, {
|
|
271
|
+
read: 'text',
|
|
272
|
+
maxBytes: MAX_RESPONSE_BYTES,
|
|
273
|
+
service: 'Substrate',
|
|
274
|
+
timeoutMs: REQUEST_TIMEOUT_MS,
|
|
275
|
+
fetchImpl: this.#fetchImpl,
|
|
276
|
+
});
|
|
277
|
+
text = r.body;
|
|
278
|
+
return r.res;
|
|
279
|
+
});
|
|
280
|
+
try {
|
|
281
|
+
checkStatus(res.status);
|
|
282
|
+
}
|
|
283
|
+
catch (error) {
|
|
284
|
+
// A 401 here is on a token `withAuth` just re-captured: the capture itself
|
|
285
|
+
// is not yielding a usable token. Cool down like a failed capture, so each
|
|
286
|
+
// unforced search does not hold the call for another capture window.
|
|
287
|
+
if (res.status === 401)
|
|
288
|
+
this.#captureFailure = { at: Date.now(), error };
|
|
289
|
+
throw error;
|
|
290
|
+
}
|
|
291
|
+
try {
|
|
292
|
+
return parseQueryResponse(JSON.parse(text));
|
|
293
|
+
}
|
|
294
|
+
catch {
|
|
295
|
+
// Never echo the body: it holds message content.
|
|
296
|
+
throw new McpToolError('Substrate returned a response that is not JSON.', { status: res.status, kind: 'http' });
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
/** Map a non-2xx to an `McpToolError` carrying its status. The body is never included. */
|
|
301
|
+
function checkStatus(status) {
|
|
302
|
+
if (status >= 200 && status < 300)
|
|
303
|
+
return;
|
|
304
|
+
if (status === 401) {
|
|
305
|
+
throw new McpToolError('Substrate rejected the search token (401) even after a fresh capture.', {
|
|
306
|
+
status,
|
|
307
|
+
kind: 'credential_rejected',
|
|
308
|
+
hint: 'Run a search in a signed-in Teams tab to mint a fresh Substrate token, then retry.',
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
if (status === 429) {
|
|
312
|
+
throw new McpToolError('Substrate is rate-limiting searches (429).', { status, kind: 'http', hint: 'Wait a minute before retrying.' });
|
|
313
|
+
}
|
|
314
|
+
throw new McpToolError(`Substrate search returned HTTP ${status}.`, {
|
|
315
|
+
status,
|
|
316
|
+
kind: 'http',
|
|
317
|
+
...(status >= 500 ? { hint: 'A Substrate-side failure; retry shortly.' } : {}),
|
|
318
|
+
});
|
|
319
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { createFileStatePersistence, resolveStateFile, } from '@chrischall/mcp-utils/session';
|
|
2
|
+
import { readEnvVar, parseBoolEnv } from '@chrischall/mcp-utils';
|
|
3
|
+
/**
|
|
4
|
+
* Where the captured chat-service access token is cached between runs.
|
|
5
|
+
*
|
|
6
|
+
* Deliberately its OWN directory, so nothing else that keeps Teams
|
|
7
|
+
* credentials (the `teams-fpx` access skill, say) can corrupt it by writing a
|
|
8
|
+
* different format to the same file.
|
|
9
|
+
*/
|
|
10
|
+
export function tokenCachePath(env = process.env) {
|
|
11
|
+
return resolveStateFile({
|
|
12
|
+
env,
|
|
13
|
+
envVar: 'TEAMS_TOKEN_FILE',
|
|
14
|
+
subdir: '.microsoft-teams-mcp',
|
|
15
|
+
fileName: 'token.json',
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
function isToken(raw) {
|
|
19
|
+
if (raw === null || typeof raw !== 'object')
|
|
20
|
+
return false;
|
|
21
|
+
const t = raw;
|
|
22
|
+
return (typeof t.accessToken === 'string' &&
|
|
23
|
+
t.accessToken !== '' &&
|
|
24
|
+
typeof t.expiresAt === 'number' &&
|
|
25
|
+
(t.refreshToken === undefined || typeof t.refreshToken === 'string'));
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* What a cached token is bound to, or `null` when there is nothing worth
|
|
29
|
+
* caching.
|
|
30
|
+
*
|
|
31
|
+
* A `TEAMS_ACCESS_TOKEN` IS the environment variable — there is no capture to
|
|
32
|
+
* skip, so caching it would only copy a credential onto disk. A captured token
|
|
33
|
+
* is worth caching most of all: it lets a cold start proceed with no browser
|
|
34
|
+
* present for the token's ~23h lifetime.
|
|
35
|
+
*/
|
|
36
|
+
function bindingFor(env) {
|
|
37
|
+
if (readEnvVar('TEAMS_ACCESS_TOKEN', { env }) !== undefined)
|
|
38
|
+
return null;
|
|
39
|
+
if (parseBoolEnv('TEAMS_DISABLE_FETCHPROXY', { env }))
|
|
40
|
+
return null;
|
|
41
|
+
return 'fetchproxy';
|
|
42
|
+
}
|
|
43
|
+
/** The token cache, or `null` when it is off or there is nothing to cache. */
|
|
44
|
+
export function createTokenCache(env = process.env) {
|
|
45
|
+
if (!parseBoolEnv('TEAMS_TOKEN_CACHE', { env, default: true }))
|
|
46
|
+
return null;
|
|
47
|
+
const boundTo = bindingFor(env);
|
|
48
|
+
if (boundTo === null)
|
|
49
|
+
return null;
|
|
50
|
+
return createFileStatePersistence({
|
|
51
|
+
filePath: tokenCachePath(env),
|
|
52
|
+
boundTo,
|
|
53
|
+
validate: (raw) => (isToken(raw) ? raw : null),
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Report a cache write that failed. Not fatal — the token is re-capturable —
|
|
58
|
+
* but worth saying, because a read-only data dir otherwise looks exactly like a
|
|
59
|
+
* server that simply never caches.
|
|
60
|
+
*
|
|
61
|
+
* stderr only; stdout is the JSON-RPC channel.
|
|
62
|
+
*/
|
|
63
|
+
export function reportCacheWriteFailure(err) {
|
|
64
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
65
|
+
console.error(`[microsoft-teams-mcp] could not cache the access token (${detail}); continuing ` +
|
|
66
|
+
'without the cache — every restart will re-capture from the browser.');
|
|
67
|
+
}
|
package/dist/tools/activity.js
CHANGED
|
@@ -1,31 +1,167 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
1
2
|
import { toolAnnotations } from '@chrischall/mcp-utils';
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
3
|
+
import { htmlToText } from '../model.js';
|
|
4
|
+
import { arrivalMs } from './conversation.js';
|
|
5
|
+
import { sinceCutoff, DEFAULT_SINCE_DAYS, MAX_SINCE_DAYS } from './confirm.js';
|
|
4
6
|
import { limitArg, trimRows } from './limit.js';
|
|
5
|
-
|
|
7
|
+
import { wrapApiError } from './errors.js';
|
|
8
|
+
import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
|
|
9
|
+
/** The chat-service conversation that holds the Activity feed. */
|
|
10
|
+
export const ACTIVITY_FEED_ID = '48:notifications';
|
|
11
|
+
const MAX_ROWS = 200;
|
|
12
|
+
/** Feed entries read before giving up — five pages; the real bound is `since_days`. */
|
|
13
|
+
const MAX_RAW_ENTRIES = 1000;
|
|
14
|
+
const MAX_PREVIEW_CHARS = 200;
|
|
15
|
+
export const ACTIVITY_KINDS = ['mention', 'reaction', 'reply', 'meeting', 'call', 'other'];
|
|
16
|
+
/** `activityType` → the bucket the `kinds` filter and each row's `kind` use. */
|
|
17
|
+
const KIND_OF_TYPE = {
|
|
18
|
+
mention: 'mention',
|
|
19
|
+
mentionInChat: 'mention',
|
|
20
|
+
reaction: 'reaction',
|
|
21
|
+
reactionInChat: 'reaction',
|
|
22
|
+
reply: 'reply',
|
|
23
|
+
replyToReply: 'reply',
|
|
24
|
+
// Every msGraph entry seen live was a private-meeting notice
|
|
25
|
+
// (privateMeetingCreated / Updated / Forwarded / …).
|
|
26
|
+
msGraph: 'meeting',
|
|
27
|
+
call: 'call',
|
|
28
|
+
};
|
|
29
|
+
export function activityKind(type) {
|
|
30
|
+
return Object.hasOwn(KIND_OF_TYPE, type) ? KIND_OF_TYPE[type] : 'other';
|
|
31
|
+
}
|
|
32
|
+
/** `properties.activity` as an object — it arrives as a JSON string or already parsed. */
|
|
33
|
+
function activityOf(m) {
|
|
34
|
+
const raw = m.properties?.activity;
|
|
35
|
+
let value = raw;
|
|
36
|
+
if (typeof raw === 'string') {
|
|
37
|
+
try {
|
|
38
|
+
value = JSON.parse(raw);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
|
|
45
|
+
}
|
|
46
|
+
/** A wire value as a non-empty string (ids can arrive as numbers), else undefined. */
|
|
47
|
+
function str(v) {
|
|
48
|
+
if (typeof v === 'string')
|
|
49
|
+
return v === '' ? undefined : v;
|
|
50
|
+
if (typeof v === 'number' && Number.isFinite(v))
|
|
51
|
+
return String(v);
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
function isoOrUndefined(v) {
|
|
55
|
+
const s = str(v);
|
|
56
|
+
if (s === undefined)
|
|
57
|
+
return undefined;
|
|
58
|
+
const ms = /^\d+$/.test(s) ? Number(s) : Date.parse(s);
|
|
59
|
+
return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined;
|
|
60
|
+
}
|
|
61
|
+
function clip(text) {
|
|
62
|
+
return text.length <= MAX_PREVIEW_CHARS ? text : `${text.slice(0, MAX_PREVIEW_CHARS - 1).trimEnd()}…`;
|
|
63
|
+
}
|
|
64
|
+
/** One feed entry as a row, or `undefined` for a deleted entry or one with no activity payload. */
|
|
65
|
+
export function activityRow(m) {
|
|
66
|
+
if (m.properties?.deletetime)
|
|
67
|
+
return undefined;
|
|
68
|
+
const a = activityOf(m);
|
|
69
|
+
if (a === undefined)
|
|
70
|
+
return undefined;
|
|
71
|
+
const type = str(a.activityType) ?? '';
|
|
72
|
+
const replyChain = str(a.sourceReplyChainId);
|
|
73
|
+
const isread = m.properties?.isread;
|
|
74
|
+
return {
|
|
75
|
+
id: m.id,
|
|
76
|
+
time: isoOrUndefined(a.activityTimestamp) ?? isoOrUndefined(m.originalarrivaltime),
|
|
77
|
+
kind: activityKind(type),
|
|
78
|
+
type,
|
|
79
|
+
subtype: str(a.activitySubtype) ?? '',
|
|
80
|
+
read: isread === true || isread === 'true',
|
|
81
|
+
from: str(a.sourceUserImDisplayName),
|
|
82
|
+
where: {
|
|
83
|
+
conversation_id: str(a.sourceThreadId),
|
|
84
|
+
title: str(a.sourceThreadTopic),
|
|
85
|
+
type: str(a.sourceThreadType),
|
|
86
|
+
},
|
|
87
|
+
message_id: str(a.sourceMessageId),
|
|
88
|
+
...(replyChain !== undefined ? { reply_chain_id: replyChain } : {}),
|
|
89
|
+
preview: clip(htmlToText(str(a.messagePreview) ?? '')),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
const newestFirst = (a, b) => (b.time ?? '').localeCompare(a.time ?? '');
|
|
93
|
+
export function registerActivityTools(server, { chatsvc }) {
|
|
6
94
|
server.registerTool('teams_get_activity', {
|
|
7
95
|
title: 'Read the Activity feed',
|
|
8
|
-
description: '
|
|
9
|
-
'
|
|
10
|
-
'
|
|
11
|
-
'
|
|
12
|
-
'
|
|
96
|
+
description: 'Read the Teams Activity feed (the bell icon) — mentions, reactions, replies, meeting ' +
|
|
97
|
+
'notices and missed calls across every chat and channel — newest first, through the ' +
|
|
98
|
+
'Teams chat-service API, so it works without the Activity view (or any particular view) ' +
|
|
99
|
+
'open in the browser. Each row has id, time (ISO 8601), kind (mention, reaction, reply, ' +
|
|
100
|
+
'meeting, call or other) with the raw type/subtype, read, from (who did it), where ' +
|
|
101
|
+
'(conversation_id, title, type), message_id, reply_chain_id (a channel thread\'s root, when there is one), ' +
|
|
102
|
+
'and a plain-text preview (at most 200 characters). Pass where.conversation_id to ' +
|
|
103
|
+
'teams_read_conversation to read the message in context. unread_only keeps rows the user ' +
|
|
104
|
+
'has not seen; kinds narrows to some buckets; since_days (default 14) sets how far back ' +
|
|
105
|
+
'to look. This does NOT mark anything read — the user\'s Activity badge is unaffected.' +
|
|
13
106
|
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
14
107
|
annotations: toolAnnotations({ readOnly: true, openWorld: true }),
|
|
15
|
-
inputSchema: {
|
|
16
|
-
|
|
108
|
+
inputSchema: {
|
|
109
|
+
unread_only: z
|
|
110
|
+
.boolean()
|
|
111
|
+
.optional()
|
|
112
|
+
.describe('Only return activity the user has not seen yet (default false). Never marks it read.'),
|
|
113
|
+
kinds: z
|
|
114
|
+
.array(z.enum(ACTIVITY_KINDS))
|
|
115
|
+
.min(1)
|
|
116
|
+
.optional()
|
|
117
|
+
.describe('Only these kinds of activity (default all): mention (incl. @team / @everyone), reaction, ' +
|
|
118
|
+
'reply, meeting (meeting invitations and updates), call (missed calls and meeting nudges), other.'),
|
|
119
|
+
since_days: z
|
|
120
|
+
.number()
|
|
121
|
+
.int()
|
|
122
|
+
.min(1)
|
|
123
|
+
.max(MAX_SINCE_DAYS)
|
|
124
|
+
.optional()
|
|
125
|
+
.describe(`Only activity from the last since_days days (default ${DEFAULT_SINCE_DAYS}, max ${MAX_SINCE_DAYS}).`),
|
|
126
|
+
limit: limitArg(MAX_ROWS, 'activity rows'),
|
|
127
|
+
},
|
|
128
|
+
}, async ({ unread_only, kinds, since_days, limit }) => {
|
|
17
129
|
try {
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
:
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
}
|
|
130
|
+
const cutoff = sinceCutoff(since_days);
|
|
131
|
+
let scanCapped = false;
|
|
132
|
+
const entries = await chatsvc.getMessages(ACTIVITY_FEED_ID, {
|
|
133
|
+
max: MAX_RAW_ENTRIES,
|
|
134
|
+
stopAt: (m) => {
|
|
135
|
+
const at = arrivalMs(m);
|
|
136
|
+
return Number.isFinite(at) && at < cutoff;
|
|
137
|
+
},
|
|
138
|
+
onCapped: () => {
|
|
139
|
+
scanCapped = true;
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
const wanted = kinds !== undefined ? new Set(kinds) : undefined;
|
|
143
|
+
const rows = entries
|
|
144
|
+
.map(activityRow)
|
|
145
|
+
.filter((r) => r !== undefined)
|
|
146
|
+
.filter((r) => r.time === undefined || Date.parse(r.time) >= cutoff)
|
|
147
|
+
.filter((r) => !unread_only || !r.read)
|
|
148
|
+
.filter((r) => wanted === undefined || wanted.has(r.kind))
|
|
149
|
+
.sort(newestFirst);
|
|
150
|
+
return untrustedResult({
|
|
151
|
+
...trimRows(rows, limit, 'start', MAX_ROWS),
|
|
152
|
+
...(scanCapped
|
|
153
|
+
? {
|
|
154
|
+
scan_capped: {
|
|
155
|
+
entries_read: MAX_RAW_ENTRIES,
|
|
156
|
+
hint: `Only the newest ${MAX_RAW_ENTRIES} feed entries were read, so older activity inside ` +
|
|
157
|
+
'since_days may be missing; pass a smaller since_days to look at a shorter window.',
|
|
158
|
+
},
|
|
159
|
+
}
|
|
160
|
+
: {}),
|
|
161
|
+
});
|
|
26
162
|
}
|
|
27
163
|
catch (err) {
|
|
28
|
-
throw
|
|
164
|
+
throw wrapApiError(err, 'read the Activity feed');
|
|
29
165
|
}
|
|
30
166
|
});
|
|
31
167
|
}
|