@chrischall/microsoft-teams-mcp 0.14.0 → 0.15.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 +241 -33
- package/dist/attachments.js +238 -0
- package/dist/auth-fetchproxy.js +7 -6
- package/dist/browser-open.js +138 -0
- package/dist/bundle.js +6840 -3949
- package/dist/capture-feedback.js +283 -0
- package/dist/chatsvc.js +132 -7
- package/dist/compose.js +9 -1
- package/dist/file-upload.js +335 -0
- package/dist/index.js +11 -1
- package/dist/model.js +1 -0
- package/dist/presence.js +120 -0
- package/dist/profile.js +182 -0
- package/dist/recap-auth.js +6 -4
- package/dist/recap.js +3 -1
- package/dist/sender-email.js +147 -0
- package/dist/sharepoint-auth.js +42 -21
- package/dist/sharepoint.js +150 -3
- package/dist/substrate-auth.js +8 -7
- package/dist/substrate.js +98 -4
- package/dist/tools/attach.js +167 -0
- package/dist/tools/attachment.js +3 -1
- package/dist/tools/conversation.js +14 -5
- package/dist/tools/edit.js +42 -14
- package/dist/tools/errors.js +10 -11
- package/dist/tools/export.js +30 -3
- package/dist/tools/format.js +29 -6
- package/dist/tools/group-chat.js +349 -33
- package/dist/tools/healthcheck.js +23 -9
- package/dist/tools/mention-check.js +225 -0
- package/dist/tools/people.js +149 -39
- package/dist/tools/profile.js +67 -0
- package/dist/tools/send.js +134 -37
- package/dist/tools/sender-email-arg.js +37 -0
- package/dist/tools/token-status.js +97 -0
- package/dist/tools/unread.js +3 -2
- package/dist/tools/upload-slots.js +51 -0
- package/dist/version.js +1 -1
- package/mint.yaml +19 -0
- package/package.json +4 -1
- package/server.json +30 -2
- package/skills/teams-fpx/references/teams-env.sh +1 -1
package/dist/sharepoint.js
CHANGED
|
@@ -32,6 +32,7 @@ import { createCapturedTokenManager } from '@chrischall/mcp-utils/session';
|
|
|
32
32
|
import { createSharePointTokenCache } from './sharepoint-token-cache.js';
|
|
33
33
|
import { knownSharePointHosts } from './bridge-scope.js';
|
|
34
34
|
import { PACKAGE_NAME } from './version.js';
|
|
35
|
+
import { browserOpener } from './browser-open.js';
|
|
35
36
|
/**
|
|
36
37
|
* Capture a SharePoint token for `host` lazily.
|
|
37
38
|
*
|
|
@@ -56,8 +57,12 @@ async function downloadViaBrowserLazily(objectUrl, env) {
|
|
|
56
57
|
}
|
|
57
58
|
/** Per-request deadline, covering the body read. */
|
|
58
59
|
const REQUEST_TIMEOUT_MS = 60_000;
|
|
60
|
+
/** Per-request deadline for an upload request (a whole small file rides in one). */
|
|
61
|
+
const UPLOAD_TIMEOUT_MS = 120_000;
|
|
59
62
|
/** Sentinel: the browser `download` capability is declared but not yet granted in the bridge. */
|
|
60
63
|
const GRANT_NEEDED = Symbol('download-grant-needed');
|
|
64
|
+
/** Sentinel: the browser download got SharePoint's sign-in page — no browser session on that host yet. */
|
|
65
|
+
const SIGN_IN = Symbol('sign-in-page');
|
|
61
66
|
/**
|
|
62
67
|
* Whether a browser-download failure is specifically the `download` capability
|
|
63
68
|
* not being granted yet (the one-time approval), as opposed to the capability
|
|
@@ -109,6 +114,17 @@ export class SharePointClient {
|
|
|
109
114
|
#capture;
|
|
110
115
|
#knownHosts;
|
|
111
116
|
#browserDownload;
|
|
117
|
+
#openInBrowser;
|
|
118
|
+
#signInPollMs;
|
|
119
|
+
#signInTimeoutMs;
|
|
120
|
+
#sleep;
|
|
121
|
+
/**
|
|
122
|
+
* Per SharePoint host, the one sign-in tab this process opened for it: it
|
|
123
|
+
* settles `true` once the browser has a session there, `false` if it never
|
|
124
|
+
* did. Kept for the life of the process, so a host gets at most one tab — a
|
|
125
|
+
* second would not bring a session the first did not.
|
|
126
|
+
*/
|
|
127
|
+
#signIns = new Map();
|
|
112
128
|
#fetchImpl;
|
|
113
129
|
#cache;
|
|
114
130
|
/**
|
|
@@ -125,6 +141,10 @@ export class SharePointClient {
|
|
|
125
141
|
this.#capture = opts.captureToken ?? captureSharePointTokenLazily;
|
|
126
142
|
this.#knownHosts = opts.knownHosts ?? (() => knownSharePointHosts(this.#env));
|
|
127
143
|
this.#browserDownload = opts.browserDownload ?? ((objectUrl) => downloadViaBrowserLazily(objectUrl, this.#env));
|
|
144
|
+
this.#openInBrowser = opts.openInBrowser !== undefined ? opts.openInBrowser : browserOpener({ env: this.#env });
|
|
145
|
+
this.#signInPollMs = opts.signInPollMs ?? 2_000;
|
|
146
|
+
this.#signInTimeoutMs = opts.signInTimeoutMs ?? 30_000;
|
|
147
|
+
this.#sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
128
148
|
// A receiver-safe wrapper, never the bare global: older undici throws
|
|
129
149
|
// `Illegal invocation` when `fetch` is called with a non-global receiver.
|
|
130
150
|
this.#fetchImpl = opts.fetchImpl ?? ((input, init) => fetch(input, init));
|
|
@@ -192,6 +212,71 @@ export class SharePointClient {
|
|
|
192
212
|
* an oversize file: a terminal, actionable outcome.
|
|
193
213
|
*/
|
|
194
214
|
async #downloadViaBrowser(objectUrl, maxBytes) {
|
|
215
|
+
const first = await this.#browserAttempt(objectUrl, maxBytes);
|
|
216
|
+
return first === SIGN_IN ? this.#afterSignInPage(objectUrl, maxBytes) : first;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* The browser download got SharePoint's sign-in page: the browser has no
|
|
220
|
+
* session on that host yet. Open the file's link in a browser tab — loading a
|
|
221
|
+
* page there runs the (normally silent) sign-on and sets the host's cookies —
|
|
222
|
+
* then retry the download until it gets past the sign-in page or the wait
|
|
223
|
+
* runs out. The tab is left open. Returns the file, or `null` to send the
|
|
224
|
+
* caller to the bearer path; an access-denied or oversize outcome on a retry
|
|
225
|
+
* throws, as on the first try.
|
|
226
|
+
*
|
|
227
|
+
* At most ONE tab per host per process (see {@link #signIns}): concurrent
|
|
228
|
+
* downloads on the host wait for that tab and then try once more, and later
|
|
229
|
+
* ones never open another.
|
|
230
|
+
*/
|
|
231
|
+
async #afterSignInPage(objectUrl, maxBytes) {
|
|
232
|
+
const host = hostOf(objectUrl);
|
|
233
|
+
const pending = this.#signIns.get(host);
|
|
234
|
+
if (pending !== undefined) {
|
|
235
|
+
if (!(await pending))
|
|
236
|
+
return null;
|
|
237
|
+
const again = await this.#browserAttempt(objectUrl, maxBytes);
|
|
238
|
+
return again === SIGN_IN || again === GRANT_NEEDED ? null : again;
|
|
239
|
+
}
|
|
240
|
+
if (this.#openInBrowser === null)
|
|
241
|
+
return null;
|
|
242
|
+
let settle = () => { };
|
|
243
|
+
this.#signIns.set(host, new Promise((resolve) => (settle = resolve)));
|
|
244
|
+
let signedIn = false;
|
|
245
|
+
try {
|
|
246
|
+
if (!(await this.#openInBrowser(objectUrl)))
|
|
247
|
+
return null;
|
|
248
|
+
const tries = Math.max(1, Math.ceil(this.#signInTimeoutMs / this.#signInPollMs));
|
|
249
|
+
for (let i = 0; i < tries; i++) {
|
|
250
|
+
await this.#sleep(this.#signInPollMs);
|
|
251
|
+
let r;
|
|
252
|
+
try {
|
|
253
|
+
r = await this.#browserAttempt(objectUrl, maxBytes);
|
|
254
|
+
}
|
|
255
|
+
catch (err) {
|
|
256
|
+
// Access denied or oversize: either way the browser got past sign-in.
|
|
257
|
+
signedIn = true;
|
|
258
|
+
throw err;
|
|
259
|
+
}
|
|
260
|
+
if (r === SIGN_IN)
|
|
261
|
+
continue;
|
|
262
|
+
signedIn = r !== null && r !== GRANT_NEEDED;
|
|
263
|
+
return r === GRANT_NEEDED ? null : r;
|
|
264
|
+
}
|
|
265
|
+
return null;
|
|
266
|
+
}
|
|
267
|
+
finally {
|
|
268
|
+
settle(signedIn);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* One browser-download attempt. Returns the bytes, {@link SIGN_IN} when
|
|
273
|
+
* SharePoint served its sign-in page instead, {@link GRANT_NEEDED} when the
|
|
274
|
+
* `download` capability has not been approved in the bridge yet, or `null`
|
|
275
|
+
* when it is unavailable for any other reason (hosted install, Safari, a bad
|
|
276
|
+
* URL, some other page in place of the file). Throws for an oversize file or
|
|
277
|
+
* an access-denied page: terminal, actionable outcomes.
|
|
278
|
+
*/
|
|
279
|
+
async #browserAttempt(objectUrl, maxBytes) {
|
|
195
280
|
let meta;
|
|
196
281
|
try {
|
|
197
282
|
meta = await this.#browserDownload(objectUrl);
|
|
@@ -233,9 +318,12 @@ export class SharePointClient {
|
|
|
233
318
|
hint: 'Open its link to request access from whoever shared it, then retry.',
|
|
234
319
|
});
|
|
235
320
|
}
|
|
236
|
-
// A sign-in page
|
|
237
|
-
//
|
|
238
|
-
|
|
321
|
+
// A sign-in page: no browser session on that host yet — the caller opens a
|
|
322
|
+
// tab there and retries (see #afterSignInPage).
|
|
323
|
+
if (page === 'sign-in')
|
|
324
|
+
return SIGN_IN;
|
|
325
|
+
// Any other page: let the bearer path (one token serves every host) try,
|
|
326
|
+
// and degrade to metadata + link cleanly if it cannot.
|
|
239
327
|
if (page !== null)
|
|
240
328
|
return null;
|
|
241
329
|
// `bytes: 0` means the browser could not report the size, so the cap was not
|
|
@@ -330,6 +418,65 @@ export class SharePointClient {
|
|
|
330
418
|
// in testing; the documented driveId/siteId/listItemUniqueId addressing stays
|
|
331
419
|
// out until a real 404 warrants it (plan Task 3, optional).
|
|
332
420
|
}
|
|
421
|
+
/**
|
|
422
|
+
* One authed SharePoint request, for the attachment upload (`file-upload.ts`):
|
|
423
|
+
* the URL must be https on a concrete `*.sharepoint.com` host (the bearer goes
|
|
424
|
+
* nowhere else), a redirect is an error rather than a hop that carries the
|
|
425
|
+
* bearer, and a 401 re-captures once and replays once (`withAuth`). Returns
|
|
426
|
+
* the status and the body text; the caller maps the status.
|
|
427
|
+
*/
|
|
428
|
+
async spRequest(url, init) {
|
|
429
|
+
this.#requireConfigured();
|
|
430
|
+
let target;
|
|
431
|
+
try {
|
|
432
|
+
target = new URL(url);
|
|
433
|
+
}
|
|
434
|
+
catch {
|
|
435
|
+
throw new McpToolError('Refusing a SharePoint request whose address is not a URL.', { kind: 'unknown' });
|
|
436
|
+
}
|
|
437
|
+
const { isSharePointHost, captureHostFor } = await import('./sharepoint-auth.js');
|
|
438
|
+
if (target.protocol !== 'https:' || !isSharePointHost(target.hostname)) {
|
|
439
|
+
throw new McpToolError(`Refusing to send the SharePoint token to ${target.protocol}//${target.hostname}.`, {
|
|
440
|
+
kind: 'unknown',
|
|
441
|
+
hint: 'Only https *.sharepoint.com tenant hosts are called.',
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
this.#fileCaptureHost = captureHostFor(target.hostname);
|
|
445
|
+
let body = '';
|
|
446
|
+
const res = await this.#tokens().withAuth(async (token) => {
|
|
447
|
+
const r = await reachable(url, () => fetchBounded(url, {
|
|
448
|
+
method: init.method,
|
|
449
|
+
headers: { accept: 'application/json', ...init.headers, authorization: `Bearer ${token}` },
|
|
450
|
+
...(init.body !== undefined ? { body: init.body } : {}),
|
|
451
|
+
redirect: 'error',
|
|
452
|
+
}, { read: 'text', service: 'SharePoint', timeoutMs: UPLOAD_TIMEOUT_MS, fetchImpl: this.#fetchImpl }));
|
|
453
|
+
body = r.body;
|
|
454
|
+
return r.res;
|
|
455
|
+
});
|
|
456
|
+
return { status: res.status, body };
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
* The delegated scopes (`scp`) of the SharePoint token, for an error that
|
|
460
|
+
* names what a refused write needed; `undefined` when the token is not a
|
|
461
|
+
* JWT carrying them. Captures a token if none is held.
|
|
462
|
+
*/
|
|
463
|
+
async grantedScopes() {
|
|
464
|
+
this.#requireConfigured();
|
|
465
|
+
if (this.#fileCaptureHost === '') {
|
|
466
|
+
const { captureHostFor } = await import('./sharepoint-auth.js');
|
|
467
|
+
const known = this.#knownHosts();
|
|
468
|
+
if (known.length > 0)
|
|
469
|
+
this.#fileCaptureHost = captureHostFor(known[0]);
|
|
470
|
+
}
|
|
471
|
+
const token = await this.#tokens().getAccessToken();
|
|
472
|
+
try {
|
|
473
|
+
const claims = JSON.parse(Buffer.from(token.split('.')[1] ?? '', 'base64url').toString('utf8'));
|
|
474
|
+
return typeof claims.scp === 'string' && claims.scp !== '' ? claims.scp : undefined;
|
|
475
|
+
}
|
|
476
|
+
catch {
|
|
477
|
+
return undefined;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
333
480
|
#requireConfigured() {
|
|
334
481
|
if (this.#configError)
|
|
335
482
|
throw this.#configError;
|
package/dist/substrate-auth.js
CHANGED
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
*/
|
|
31
31
|
import { captureBearerHeader } from '@chrischall/mcp-utils/fetchproxy';
|
|
32
32
|
import { captureWindowMs } from './capture-window.js';
|
|
33
|
+
import { whileWaitingGuidance } from './capture-feedback.js';
|
|
33
34
|
import { bridgeScopedTransport, getWsPort } from './auth-fetchproxy.js';
|
|
34
35
|
import { BRIDGE_TRUST_DOMAINS, SUBSTRATE_CAPTURE_DECL } from './bridge-scope.js';
|
|
35
36
|
import { PACKAGE_NAME, VERSION } from './version.js';
|
|
@@ -45,22 +46,22 @@ export const SUBSTRATE_TRUST_DOMAINS = [...BRIDGE_TRUST_DOMAINS];
|
|
|
45
46
|
* Capture a Substrate search token from the user's signed-in Teams tab.
|
|
46
47
|
* Returns the bare token (no `Bearer ` prefix).
|
|
47
48
|
*/
|
|
48
|
-
export async function captureSubstrateTokenViaFetchproxy(env = process.env) {
|
|
49
|
+
export async function captureSubstrateTokenViaFetchproxy(env = process.env, windowMs = captureWindowMs(env)) {
|
|
49
50
|
return captureBearerHeader({
|
|
50
51
|
// Same verb set and, through `bridgeScopedTransport`, the same declared
|
|
51
52
|
// scope as the other two captures; only the header read differs.
|
|
52
53
|
captures: [{ ...SUBSTRATE_CAPTURE_DECL }],
|
|
53
54
|
domains: SUBSTRATE_TRUST_DOMAINS,
|
|
54
|
-
// Read per capture, not at import: see `capture-window.ts
|
|
55
|
-
windowMs
|
|
55
|
+
// Read per capture, not at import: see `capture-window.ts`; a deliberate prime passes a longer one.
|
|
56
|
+
windowMs,
|
|
56
57
|
port: getWsPort(),
|
|
57
58
|
serverName: PACKAGE_NAME,
|
|
58
59
|
version: VERSION,
|
|
59
60
|
what: 'a Substrate search token',
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
'
|
|
63
|
-
'
|
|
61
|
+
// The search has to happen WHILE the capture waits: see `capture-feedback.ts`.
|
|
62
|
+
guidance: whileWaitingGuidance('substrate', windowMs) +
|
|
63
|
+
' A "not in declared set" error means the ContextMint Bridge pairing does not trust ' +
|
|
64
|
+
'substrate.office.com yet: approve microsoft-teams-mcp in the bridge popup once.',
|
|
64
65
|
createTransport: bridgeScopedTransport(env),
|
|
65
66
|
});
|
|
66
67
|
}
|
package/dist/substrate.js
CHANGED
|
@@ -66,11 +66,21 @@
|
|
|
66
66
|
* `PublicDistributionList` — only the first can be a chat member.
|
|
67
67
|
* - The v2 query endpoint with `EntityType: "People"` is a 400: not used.
|
|
68
68
|
*
|
|
69
|
+
* The same suggestions are `teams_get_profile`'s profile cards
|
|
70
|
+
* (`profile.ts`) and `sender_email`'s addresses (`sender-email.ts`). Besides
|
|
71
|
+
* the fields above, the live sample carried `OfficeLocation` and `ImAddress`
|
|
72
|
+
* (`sip:<address>`, the card's chat address); `CompanyName`, `City` (or a
|
|
73
|
+
* `PostalAddresses[].City`) and `Manager` are read when present but were NOT
|
|
74
|
+
* seen live — the Teams card takes those from the Loki/Delve profile service,
|
|
75
|
+
* which this server does not call (another host, another token).
|
|
76
|
+
*
|
|
69
77
|
* As with the other clients, the bridge is touched only to capture the token
|
|
70
78
|
* (`substrate-auth.ts`); every request is a plain Node `fetch`.
|
|
71
79
|
*/
|
|
72
80
|
import { fetchBounded, McpToolError, parseBoolEnv } from '@chrischall/mcp-utils';
|
|
73
81
|
import { describeTransportFailure } from './network-error.js';
|
|
82
|
+
import { captureWithFeedback, tokenStatusOf, whileWaitingGuidance } from './capture-feedback.js';
|
|
83
|
+
import { captureWindowMs } from './capture-window.js';
|
|
74
84
|
import { createCapturedTokenManager } from '@chrischall/mcp-utils/session';
|
|
75
85
|
import { createSubstrateTokenCache } from './substrate-token-cache.js';
|
|
76
86
|
export const SUBSTRATE_QUERY_URL = 'https://substrate.office.com/searchservice/api/v2/query';
|
|
@@ -91,9 +101,9 @@ const REQUEST_TIMEOUT_MS = 30_000;
|
|
|
91
101
|
/** A search response is a page of summaries; anything near this is not one. */
|
|
92
102
|
const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
93
103
|
/** Capture lazily, so boot never loads the bridge (see `sharepoint.ts`). */
|
|
94
|
-
async function captureSubstrateTokenLazily() {
|
|
104
|
+
async function captureSubstrateTokenLazily(windowMs) {
|
|
95
105
|
const mod = await import('./substrate-auth.js');
|
|
96
|
-
return mod.captureSubstrateTokenViaFetchproxy();
|
|
106
|
+
return mod.captureSubstrateTokenViaFetchproxy(undefined, windowMs);
|
|
97
107
|
}
|
|
98
108
|
/** `sent>=` takes an unquoted ISO date-time (a quoted one was mis-read live); whole seconds, rounded down. */
|
|
99
109
|
function sentBound(ms) {
|
|
@@ -256,6 +266,11 @@ function mapSuggestion(raw) {
|
|
|
256
266
|
const name = str(r.DisplayName)?.trim() ?? email ?? upn ?? mri;
|
|
257
267
|
const jobTitle = str(r.JobTitle);
|
|
258
268
|
const department = str(r.Department);
|
|
269
|
+
const company = str(r.CompanyName);
|
|
270
|
+
const officeLocation = str(r.OfficeLocation);
|
|
271
|
+
const city = str(r.City) ?? postalCity(r.PostalAddresses);
|
|
272
|
+
const chatAddress = str(r.ImAddress)?.trim().replace(/^sip:/i, '');
|
|
273
|
+
const manager = managerOf(r.Manager);
|
|
259
274
|
return {
|
|
260
275
|
mri,
|
|
261
276
|
name,
|
|
@@ -263,8 +278,35 @@ function mapSuggestion(raw) {
|
|
|
263
278
|
...(upn !== undefined ? { upn } : {}),
|
|
264
279
|
...(jobTitle !== undefined ? { jobTitle } : {}),
|
|
265
280
|
...(department !== undefined ? { department } : {}),
|
|
281
|
+
...(company !== undefined ? { company } : {}),
|
|
282
|
+
...(officeLocation !== undefined ? { officeLocation } : {}),
|
|
283
|
+
...(city !== undefined ? { city } : {}),
|
|
284
|
+
...(chatAddress ? { chatAddress } : {}),
|
|
285
|
+
...(manager !== undefined ? { manager } : {}),
|
|
266
286
|
};
|
|
267
287
|
}
|
|
288
|
+
/** The first city among a suggestion's postal addresses, if any. */
|
|
289
|
+
function postalCity(v) {
|
|
290
|
+
if (!Array.isArray(v))
|
|
291
|
+
return undefined;
|
|
292
|
+
return v.map((a) => str(obj(a)?.City)).find((c) => c !== undefined);
|
|
293
|
+
}
|
|
294
|
+
/** A manager given as a bare name, or as a person object (`DisplayName`/`Name`, `EmailAddresses`/`EmailAddress`). */
|
|
295
|
+
function managerOf(v) {
|
|
296
|
+
const name = str(v);
|
|
297
|
+
if (name !== undefined)
|
|
298
|
+
return { displayName: name.trim() };
|
|
299
|
+
const m = obj(v);
|
|
300
|
+
if (m === undefined)
|
|
301
|
+
return undefined;
|
|
302
|
+
const displayName = str(m.DisplayName) ?? str(m.Name);
|
|
303
|
+
const email = (Array.isArray(m.EmailAddresses) ? m.EmailAddresses.map(str).find((e) => e !== undefined) : undefined) ??
|
|
304
|
+
str(m.EmailAddress) ??
|
|
305
|
+
str(m.UserPrincipalName);
|
|
306
|
+
if (displayName === undefined && email === undefined)
|
|
307
|
+
return undefined;
|
|
308
|
+
return { ...(displayName !== undefined ? { displayName } : {}), ...(email !== undefined ? { email } : {}) };
|
|
309
|
+
}
|
|
268
310
|
/** Parse a suggestions response into the people who can be chat members, one per MRI. Never throws on shape. */
|
|
269
311
|
export function parseSuggestionsResponse(body) {
|
|
270
312
|
const groups = obj(body)?.Groups;
|
|
@@ -294,14 +336,28 @@ export class SubstrateClient {
|
|
|
294
336
|
* refused (401), and how; cleared by a successful capture.
|
|
295
337
|
*/
|
|
296
338
|
#captureFailure = null;
|
|
339
|
+
#env;
|
|
340
|
+
/** A longer capture window for a deliberate prime (`ensureToken({ windowMs })`), while it runs. */
|
|
341
|
+
#windowOverride;
|
|
297
342
|
constructor(opts = {}) {
|
|
298
343
|
const env = opts.env ?? process.env;
|
|
344
|
+
this.#env = env;
|
|
299
345
|
const capture = opts.captureToken ?? captureSubstrateTokenLazily;
|
|
300
346
|
// A receiver-safe wrapper, never the bare global (see `sharepoint.ts`).
|
|
301
347
|
this.#fetchImpl = opts.fetchImpl ?? ((input, init) => fetch(input, init));
|
|
348
|
+
// Progress while waiting, and a failure that names its step and how long it
|
|
349
|
+
// waited (`capture-feedback.ts`). No nudge: nothing but a search the person
|
|
350
|
+
// runs makes the page call the search service, and opening a tab does not.
|
|
302
351
|
const recapture = async () => {
|
|
303
352
|
try {
|
|
304
|
-
const
|
|
353
|
+
const windowMs = this.#windowOverride ?? captureWindowMs(env);
|
|
354
|
+
const previous = this.#storedExpiry() ?? this.#memoryExpiry();
|
|
355
|
+
const token = await captureWithFeedback({
|
|
356
|
+
token: 'substrate',
|
|
357
|
+
windowMs,
|
|
358
|
+
capture: () => capture(windowMs),
|
|
359
|
+
...(previous !== null ? { previousExpiresAt: previous } : {}),
|
|
360
|
+
});
|
|
305
361
|
this.#captureFailure = null;
|
|
306
362
|
return token;
|
|
307
363
|
}
|
|
@@ -326,6 +382,44 @@ export class SubstrateClient {
|
|
|
326
382
|
isConfigured() {
|
|
327
383
|
return this.#configError === null;
|
|
328
384
|
}
|
|
385
|
+
/**
|
|
386
|
+
* Hold a token — this process's, the disk cache's, or a fresh capture with
|
|
387
|
+
* `windowMs` (for this call only). Skips the failed-capture cooldown: it is
|
|
388
|
+
* the deliberate "prime the token" path.
|
|
389
|
+
*/
|
|
390
|
+
async ensureToken(opts = {}) {
|
|
391
|
+
if (this.#configError)
|
|
392
|
+
throw this.#configError;
|
|
393
|
+
this.#windowOverride = opts.windowMs;
|
|
394
|
+
try {
|
|
395
|
+
await this.#manager.getAccessToken();
|
|
396
|
+
}
|
|
397
|
+
finally {
|
|
398
|
+
this.#windowOverride = undefined;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
/** Whether a token is held and until when, WITHOUT capturing. Never the token itself. */
|
|
402
|
+
tokenStatus() {
|
|
403
|
+
return tokenStatusOf('substrate', {
|
|
404
|
+
source: 'browser capture',
|
|
405
|
+
memoryExpiresAt: this.#memoryExpiry(),
|
|
406
|
+
storedExpiresAt: this.#storedExpiry(),
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
#memoryExpiry() {
|
|
410
|
+
const at = this.#manager.getExpiresAt();
|
|
411
|
+
return Number.isFinite(at) && at > 0 ? at : null;
|
|
412
|
+
}
|
|
413
|
+
/** The disk cache's expiry, or `null`. Never throws. */
|
|
414
|
+
#storedExpiry() {
|
|
415
|
+
try {
|
|
416
|
+
const at = createSubstrateTokenCache(this.#env)?.load()?.expiresAt;
|
|
417
|
+
return typeof at === 'number' && Number.isFinite(at) && at > 0 ? at : null;
|
|
418
|
+
}
|
|
419
|
+
catch {
|
|
420
|
+
return null;
|
|
421
|
+
}
|
|
422
|
+
}
|
|
329
423
|
async searchMessages(req, opts = {}) {
|
|
330
424
|
return parseQueryResponse(await this.#post(SEARCH, buildQueryBody(req), opts.force === true));
|
|
331
425
|
}
|
|
@@ -408,7 +502,7 @@ function checkStatus(status, lookup) {
|
|
|
408
502
|
throw new McpToolError('Substrate rejected the search token (401) even after a fresh capture.', {
|
|
409
503
|
status,
|
|
410
504
|
kind: 'credential_rejected',
|
|
411
|
-
hint: '
|
|
505
|
+
hint: whileWaitingGuidance('substrate', captureWindowMs()),
|
|
412
506
|
});
|
|
413
507
|
}
|
|
414
508
|
if (status === 429) {
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Attachments for `teams_send_message` and `teams_edit_message`: plan them
|
|
3
|
+
* (resolve and vet every file, pick where they go and who gets access) on
|
|
4
|
+
* every call — the preview binds each file's SHA-256, so a file that changed
|
|
5
|
+
* between preview and confirm is refused by the gate — then, only on the
|
|
6
|
+
* confirmed call, upload and share them and hand back the file cards.
|
|
7
|
+
*
|
|
8
|
+
* Never sends without a file: an upload or share failure throws before the
|
|
9
|
+
* message is posted, naming any file already uploaded.
|
|
10
|
+
*/
|
|
11
|
+
import { McpToolError } from '@chrischall/mcp-utils';
|
|
12
|
+
import { blobStoreFromEnv, isHostedEnv } from '@chrischall/mcp-utils/export';
|
|
13
|
+
import { resolveAttachments, MAX_ATTACHMENT_BYTES } from '../attachments.js';
|
|
14
|
+
import { knownSharePointHosts } from '../bridge-scope.js';
|
|
15
|
+
import { channelDestination, filesProperty, oneDriveDestination, } from '../file-upload.js';
|
|
16
|
+
import { oneOnOnePeerMri } from '../model.js';
|
|
17
|
+
const ORGID = /^8:orgid:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
|
|
18
|
+
function humanSize(n) {
|
|
19
|
+
if (n < 1024)
|
|
20
|
+
return `${n} B`;
|
|
21
|
+
if (n < 1024 * 1024)
|
|
22
|
+
return `${(n / 1024).toFixed(1)} KiB`;
|
|
23
|
+
return `${(n / (1024 * 1024)).toFixed(1)} MiB`;
|
|
24
|
+
}
|
|
25
|
+
function destinationLabel(d, name) {
|
|
26
|
+
return d.kind === 'onedrive' ? `OneDrive (${d.host}) › ${d.folder}/${name}` : `${d.siteUrl} › Shared Documents/${d.folder}/${name}`;
|
|
27
|
+
}
|
|
28
|
+
/** The chat's members other than the user, split into grantable object ids and the rest. */
|
|
29
|
+
async function members(chatsvc, target, me) {
|
|
30
|
+
if (target.kind === 'self' || target.kind === 'channel')
|
|
31
|
+
return { ids: [], others: [] };
|
|
32
|
+
let mris;
|
|
33
|
+
const peer = target.kind === 'oneOnOne' ? oneOnOnePeerMri(target.id, me) : undefined;
|
|
34
|
+
if (peer !== undefined) {
|
|
35
|
+
mris = [peer];
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
const thread = await chatsvc.getThread(target.id);
|
|
39
|
+
mris = (thread.members ?? []).map((m) => m.id);
|
|
40
|
+
}
|
|
41
|
+
const ids = [];
|
|
42
|
+
const others = [];
|
|
43
|
+
for (const mri of mris) {
|
|
44
|
+
if (mri.toLowerCase() === me.toLowerCase())
|
|
45
|
+
continue;
|
|
46
|
+
const m = ORGID.exec(mri);
|
|
47
|
+
if (m)
|
|
48
|
+
ids.push(m[1].toLowerCase());
|
|
49
|
+
else
|
|
50
|
+
others.push(mri);
|
|
51
|
+
}
|
|
52
|
+
return { ids: [...new Set(ids)], others };
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Resolve and vet the files and decide where they go. Runs on the preview
|
|
56
|
+
* call and again on the confirmed one; uploads nothing.
|
|
57
|
+
*/
|
|
58
|
+
export async function planAttachments(chatsvc, opts, target, items, me) {
|
|
59
|
+
if (opts.files === undefined) {
|
|
60
|
+
throw new McpToolError('This server cannot attach files (no uploader is configured).', { kind: 'unknown' });
|
|
61
|
+
}
|
|
62
|
+
const env = opts.env ?? process.env;
|
|
63
|
+
const files = await resolveAttachments(items, {
|
|
64
|
+
env,
|
|
65
|
+
maxBytes: opts.maxAttachmentBytes ?? MAX_ATTACHMENT_BYTES,
|
|
66
|
+
hosted: isHostedEnv(env),
|
|
67
|
+
store: blobStoreFromEnv(env) ?? null,
|
|
68
|
+
});
|
|
69
|
+
let destination;
|
|
70
|
+
if (target.kind === 'channel') {
|
|
71
|
+
const all = await chatsvc.listConversations();
|
|
72
|
+
const raw = all.find((c) => c.id === target.id) ?? { id: target.id };
|
|
73
|
+
destination = channelDestination(raw, all, target.title);
|
|
74
|
+
}
|
|
75
|
+
else {
|
|
76
|
+
destination = oneDriveDestination(env, knownSharePointHosts(env));
|
|
77
|
+
}
|
|
78
|
+
const { ids, others } = await members(chatsvc, target, me);
|
|
79
|
+
const sharing = target.kind === 'channel'
|
|
80
|
+
? "the team's members (the channel's files folder)"
|
|
81
|
+
: target.kind === 'self'
|
|
82
|
+
? 'no one (your own notes chat)'
|
|
83
|
+
: `${ids.length} chat member${ids.length === 1 ? '' : 's'} (view access, no email)`;
|
|
84
|
+
return {
|
|
85
|
+
files,
|
|
86
|
+
destination,
|
|
87
|
+
shareWith: ids,
|
|
88
|
+
notSharedWith: others,
|
|
89
|
+
preview: {
|
|
90
|
+
attachments: files.map((f) => ({
|
|
91
|
+
name: f.fileName,
|
|
92
|
+
size_bytes: f.sizeBytes,
|
|
93
|
+
size: humanSize(f.sizeBytes),
|
|
94
|
+
type: f.mimeType,
|
|
95
|
+
sha256: f.sha256,
|
|
96
|
+
source: f.source,
|
|
97
|
+
destination: destinationLabel(destination, f.fileName),
|
|
98
|
+
})),
|
|
99
|
+
shared_with: sharing,
|
|
100
|
+
...(others.length > 0
|
|
101
|
+
? { not_shared_with: `${others.join(', ')} — not granted access to the files (not a directory account).` }
|
|
102
|
+
: {}),
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Upload every file and share it — the confirmed call only. Throws (with the
|
|
108
|
+
* files already uploaded named) on the first failure, so the caller never
|
|
109
|
+
* posts a message without its files.
|
|
110
|
+
*/
|
|
111
|
+
export async function deliverAttachments(opts, plan) {
|
|
112
|
+
const uploader = opts.files;
|
|
113
|
+
const done = [];
|
|
114
|
+
try {
|
|
115
|
+
for (const f of plan.files) {
|
|
116
|
+
const up = await uploader.upload(plan.destination, { fileName: f.fileName, mimeType: f.mimeType, bytes: f.bytes });
|
|
117
|
+
done.push(up);
|
|
118
|
+
await uploader.share(up, plan.shareWith);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
catch (err) {
|
|
122
|
+
const left = done.length > 0
|
|
123
|
+
? ` Already uploaded (not sent, still in ${plan.destination.kind === 'onedrive' ? 'your OneDrive' : 'the channel folder'}): ${done
|
|
124
|
+
.map((u) => `"${u.name}"`)
|
|
125
|
+
.join(', ')}.`
|
|
126
|
+
: '';
|
|
127
|
+
const e = err instanceof McpToolError ? err : new McpToolError(err.message ?? String(err), { kind: 'unknown' });
|
|
128
|
+
throw new McpToolError(`${e.message} The message was NOT sent.${left}`, {
|
|
129
|
+
...(e.kind !== undefined ? { kind: e.kind } : {}),
|
|
130
|
+
...(e.status !== undefined ? { status: e.status } : {}),
|
|
131
|
+
...(e.hint !== undefined ? { hint: e.hint } : {}),
|
|
132
|
+
cause: err,
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
return done;
|
|
136
|
+
}
|
|
137
|
+
/** The file cards for a message (merged after any it already had). */
|
|
138
|
+
export function mergedFilesProperty(existing, uploaded) {
|
|
139
|
+
let before = [];
|
|
140
|
+
if (typeof existing === 'string') {
|
|
141
|
+
try {
|
|
142
|
+
const p = JSON.parse(existing);
|
|
143
|
+
if (Array.isArray(p))
|
|
144
|
+
before = p;
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
before = [];
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
else if (Array.isArray(existing)) {
|
|
151
|
+
before = existing;
|
|
152
|
+
}
|
|
153
|
+
return JSON.stringify([...before, ...JSON.parse(filesProperty(uploaded))]);
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* After the message is posted: delete blob-store uploads (only when the write
|
|
157
|
+
* is known to have landed — `release`), and say per file what was attached
|
|
158
|
+
* (name, size, link).
|
|
159
|
+
*/
|
|
160
|
+
export async function attachmentResult(plan, uploaded, release = true) {
|
|
161
|
+
const releases = await Promise.all(plan.files.map((f) => (release && f.origin === 'blob' ? f.release().then((r) => ({ key: f.source, ...r })) : undefined)));
|
|
162
|
+
const blob = releases.filter((r) => r !== undefined);
|
|
163
|
+
return {
|
|
164
|
+
attachments: uploaded.map((u) => ({ name: u.name, size_bytes: u.size, ...(u.webUrl ? { url: u.webUrl } : {}) })),
|
|
165
|
+
...(blob.length > 0 ? { blob_uploads: blob } : {}),
|
|
166
|
+
};
|
|
167
|
+
}
|
package/dist/tools/attachment.js
CHANGED
|
@@ -59,7 +59,9 @@ export function registerAttachmentTools(server, { chatsvc, sharepoint }) {
|
|
|
59
59
|
'with the reason in conversion_error. ' +
|
|
60
60
|
'The first download may need your Teams tab reloaded to capture a short-lived SharePoint token, which ' +
|
|
61
61
|
'then serves every SharePoint host; a file your account cannot open, or one that could not be fetched, ' +
|
|
62
|
-
'comes back as metadata and its open link instead of failing.
|
|
62
|
+
'comes back as metadata and its open link instead of failing. On a local install, a file on a SharePoint ' +
|
|
63
|
+
'host the browser has not signed in to yet opens its link in a Chrome tab (once per host; the tab is left ' +
|
|
64
|
+
'open) and the download is retried. The caption names the conversation beside ' +
|
|
63
65
|
'its id: title (as teams_list_conversations names it — an untitled group chat by its participants, a 1:1 ' +
|
|
64
66
|
'by the other person) and participants. Does not mark anything read.' +
|
|
65
67
|
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
@@ -13,6 +13,8 @@ import { decodeFrom, FROM_DESCRIPTION, fromArg, fromReport, readFrom, takePage,
|
|
|
13
13
|
import { fetchOutsideRoots, MAX_ROOT_FETCHES, rootBudget } from './roots.js';
|
|
14
14
|
import { advancesHorizon, applyMarks, confirmMarks, horizonMessageId, MARK_READ_DESCRIPTION, markReadArg, assertMarkReadFormat, } from './markread.js';
|
|
15
15
|
import { workMeta } from './hints.js';
|
|
16
|
+
import { assertSenderEmail, SENDER_EMAIL_DESCRIPTION, senderEmailArg, senderEmailReport } from './sender-email-arg.js';
|
|
17
|
+
import { withSenderEmails } from '../sender-email.js';
|
|
16
18
|
const MAX_MESSAGES = 500;
|
|
17
19
|
/**
|
|
18
20
|
* Raw messages read before giving up (20 pages of 200). The real bound is the
|
|
@@ -315,18 +317,20 @@ async function readMany(chatsvc, raw, me, conversations, opts) {
|
|
|
315
317
|
errors.sort((a, b) => (order.get(a.conversation) ?? 0) - (order.get(b.conversation) ?? 0));
|
|
316
318
|
return { reads: results, errors };
|
|
317
319
|
}
|
|
318
|
-
export function registerConversationTools(server, { chatsvc }) {
|
|
320
|
+
export function registerConversationTools(server, { chatsvc, substrate }) {
|
|
319
321
|
server.registerTool('teams_list_messages', {
|
|
320
322
|
title: 'Read a Teams chat or channel',
|
|
321
323
|
description: 'Read the messages of any chat or channel the signed-in user is in, by id (from ' +
|
|
322
324
|
'teams_list_conversations / teams_list_channels) or by name, without opening it in ' +
|
|
323
325
|
'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, ' +
|
|
324
326
|
'text (never truncated; table cells separated by " | "; lists numbered or bulleted), subject, edited/deleted flags and attachments; ' +
|
|
327
|
+
'senderMri (the sender\'s MRI, 8:orgid:…, to pass to teams_get_profile), ' +
|
|
325
328
|
'a formatted message also carries content_html (its body as sanitised HTML: bold, lists, links, code, quotes, mentions), ' +
|
|
326
329
|
'mentions ([{mri, displayName}], who was @mentioned) and links ([{href, text}]), each absent when there is none; ' +
|
|
327
|
-
'
|
|
330
|
+
'every result has message_count (0 for an empty window, with messages []). A channel returns messages too — ' +
|
|
331
|
+
'flat, roots and replies in time order, each with thread_root_id — AND threads, ' +
|
|
328
332
|
'each root post with its replies. A root older than the window is fetched and marked outside_window: ' +
|
|
329
|
-
'true (it is context, not counted or cursored); up to ' +
|
|
333
|
+
'true (it is context, in threads only: not in messages, counted or cursored); up to ' +
|
|
330
334
|
`${MAX_ROOT_FETCHES} roots are fetched per call, and any beyond that or that cannot be fetched is ` +
|
|
331
335
|
'{ id, missing: true }. ' +
|
|
332
336
|
'unread_only returns just the messages the user has not read; since stops at a time; ' +
|
|
@@ -362,6 +366,7 @@ export function registerConversationTools(server, { chatsvc }) {
|
|
|
362
366
|
'with id, title, kind, team, lastActivity and match_reason), hint} and no messages — read again ' +
|
|
363
367
|
'with one candidate\'s id. ' +
|
|
364
368
|
TIME_ZONE_DESCRIPTION +
|
|
369
|
+
SENDER_EMAIL_DESCRIPTION +
|
|
365
370
|
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
366
371
|
// 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).
|
|
367
372
|
annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
|
|
@@ -383,11 +388,13 @@ export function registerConversationTools(server, { chatsvc }) {
|
|
|
383
388
|
tz: tzArg,
|
|
384
389
|
format: formatArg,
|
|
385
390
|
mark_read: markReadArg,
|
|
391
|
+
sender_email: senderEmailArg,
|
|
386
392
|
confirmToken: confirmTokenParam,
|
|
387
393
|
},
|
|
388
|
-
}, async ({ conversation, unread_only, since, after_message_id, from, limit, tz, format, mark_read, confirmToken }, ctx) => {
|
|
394
|
+
}, async ({ conversation, unread_only, since, after_message_id, from, limit, tz, format, mark_read, sender_email, confirmToken }, ctx) => {
|
|
389
395
|
try {
|
|
390
396
|
assertMarkReadFormat(mark_read, format);
|
|
397
|
+
assertSenderEmail(sender_email, format, substrate);
|
|
391
398
|
if (from !== undefined) {
|
|
392
399
|
const clash = since !== undefined ? 'since' : after_message_id !== undefined ? 'after_message_id' : mark_read ? 'mark_read' : undefined;
|
|
393
400
|
if (clash !== undefined) {
|
|
@@ -444,14 +451,16 @@ export function registerConversationTools(server, { chatsvc }) {
|
|
|
444
451
|
: { marked_read: false }))
|
|
445
452
|
: {}),
|
|
446
453
|
});
|
|
454
|
+
const senders = sender_email && substrate !== undefined ? senderEmailReport(await withSenderEmails(substrate, results)) : {};
|
|
447
455
|
if (Array.isArray(conversation)) {
|
|
448
456
|
return untrustedResult({
|
|
449
457
|
conversations: results,
|
|
450
458
|
...(many.errors.length > 0 ? { errors: many.errors } : {}),
|
|
459
|
+
...senders,
|
|
451
460
|
fetched_at,
|
|
452
461
|
});
|
|
453
462
|
}
|
|
454
|
-
return untrustedResult({ ...results[0], fetched_at });
|
|
463
|
+
return untrustedResult({ ...results[0], ...senders, fetched_at });
|
|
455
464
|
}
|
|
456
465
|
catch (err) {
|
|
457
466
|
// A read can safely hand back the candidates; the write tools keep refusing.
|