@chrischall/microsoft-teams-mcp 0.13.0 → 0.14.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 +12 -2
- package/dist/auth-fetchproxy.js +35 -1
- package/dist/bridge-scope.js +45 -8
- package/dist/bundle.js +22429 -27258
- package/dist/sharepoint-auth.js +175 -29
- package/dist/sharepoint.js +182 -8
- package/dist/tools/send.js +70 -10
- package/dist/version.js +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/sharepoint-auth.js
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Bootstrap-only fetchproxy auth for SharePoint shared-file download.
|
|
3
3
|
*
|
|
4
|
+
* This module holds TWO ways to get a shared file's bytes. The PRIMARY one is
|
|
5
|
+
* `downloadSharePointFileViaBrowser`: the bridge's `download` verb
|
|
6
|
+
* (`chrome.downloads`, the browser's own cookies and TLS) fetches the file with
|
|
7
|
+
* no token at all, so an idle Teams tab's cached token can never starve it. The
|
|
8
|
+
* token-capture path below is the FALLBACK (and the only path on a hosted
|
|
9
|
+
* install, where the bridge has no browser to download through): the rest of
|
|
10
|
+
* this comment documents it.
|
|
11
|
+
*
|
|
4
12
|
* A shared file in a Teams chat lives in SharePoint, not the Teams AMS object
|
|
5
13
|
* store that holds inline images, so downloading its contents needs a
|
|
6
14
|
* SharePoint token — NOT the chat-service token `auth-fetchproxy.ts` captures.
|
|
@@ -45,12 +53,72 @@
|
|
|
45
53
|
* code that needs a token, as `auth-fetchproxy.ts` is, so a server run with
|
|
46
54
|
* `TEAMS_DISABLE_FETCHPROXY` never has to load the bridge to boot.
|
|
47
55
|
*/
|
|
56
|
+
import { randomUUID } from 'node:crypto';
|
|
48
57
|
import { captureBearerHeader } from '@chrischall/mcp-utils/fetchproxy';
|
|
49
58
|
import { McpToolError } from '@chrischall/mcp-utils';
|
|
50
59
|
import { captureWindowMs } from './capture-window.js';
|
|
51
|
-
import { bridgeScopedTransport, getWsPort } from './auth-fetchproxy.js';
|
|
60
|
+
import { bridgeScopedTransport, bridgeDownloadTransport, DOWNLOAD_VERB_TIMEOUT_MS, getWsPort } from './auth-fetchproxy.js';
|
|
52
61
|
import { BRIDGE_TRUST_DOMAINS, isSharePointHost, rememberSharePointHost, sharePointCaptureDecl } from './bridge-scope.js';
|
|
53
62
|
import { PACKAGE_NAME, VERSION } from './version.js';
|
|
63
|
+
/** The SharePoint/Office 365 resource the captured token's `aud` must name. */
|
|
64
|
+
const SHAREPOINT_RESOURCE_GUID = '00000003-0000-0ff1-ce00-000000000000';
|
|
65
|
+
/**
|
|
66
|
+
* Download a shared SharePoint file through the browser's own `chrome.downloads`
|
|
67
|
+
* — real cookies, real TLS fingerprint — and return the local path it saved to.
|
|
68
|
+
*
|
|
69
|
+
* This is the PRIMARY path for a shared file: it needs no token capture, so the
|
|
70
|
+
* cached-token-starves-the-capture failure (an idle Teams tab makes no fresh
|
|
71
|
+
* SharePoint request, so there is nothing to snapshot) cannot happen. The file
|
|
72
|
+
* host is gated by the transport's `domains` (`sharepoint.com`), so any tenant
|
|
73
|
+
* host works without a per-host capture grant. `?download=1` is added so
|
|
74
|
+
* SharePoint returns the file bytes rather than the web viewer's HTML.
|
|
75
|
+
*
|
|
76
|
+
* Only usable where this server shares a disk with the browser (a LOCAL
|
|
77
|
+
* install): the returned path is on the browser's machine. The caller reads it
|
|
78
|
+
* and, on any failure — this being a hosted install, Safari (no
|
|
79
|
+
* `chrome.downloads`), or a denied capability — falls back to the bearer path.
|
|
80
|
+
*
|
|
81
|
+
* Import this module LAZILY, as the capture path is, so a boot with
|
|
82
|
+
* `TEAMS_DISABLE_FETCHPROXY` never loads the optional bridge peer.
|
|
83
|
+
*/
|
|
84
|
+
export async function downloadSharePointFileViaBrowser(objectUrl, env = process.env) {
|
|
85
|
+
let target;
|
|
86
|
+
try {
|
|
87
|
+
target = new URL(objectUrl);
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
throw new McpToolError('Refusing to download a file whose link is not a URL.', {
|
|
91
|
+
hint: 'Pass a file url exactly as a message listing returned it.',
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
const host = target.hostname;
|
|
95
|
+
if (target.protocol !== 'https:' || !isSharePointHost(host)) {
|
|
96
|
+
throw new McpToolError(`Refusing to download a file from ${target.protocol}//${host}.`, {
|
|
97
|
+
hint: 'Only https files on a *.sharepoint.com tenant host are downloaded.',
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
const transport = bridgeDownloadTransport(env);
|
|
101
|
+
await transport.start();
|
|
102
|
+
try {
|
|
103
|
+
const res = await transport.server.download({
|
|
104
|
+
url: withDownloadQuery(target),
|
|
105
|
+
// A fresh unguessable name under one subdir, so the read-then-delete below
|
|
106
|
+
// never collides and never touches a file this server did not create.
|
|
107
|
+
filename: `microsoft-teams-mcp-tmp/${randomUUID()}`,
|
|
108
|
+
timeoutMs: DOWNLOAD_VERB_TIMEOUT_MS,
|
|
109
|
+
});
|
|
110
|
+
return { path: res.path, bytes: res.bytes, ...(res.mime !== undefined ? { mime: res.mime } : {}) };
|
|
111
|
+
}
|
|
112
|
+
finally {
|
|
113
|
+
await transport.close().catch(() => { });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/** Add `download=1` so SharePoint serves the file bytes, not the web viewer HTML. */
|
|
117
|
+
function withDownloadQuery(target) {
|
|
118
|
+
const u = new URL(target.toString());
|
|
119
|
+
u.searchParams.set('download', '1');
|
|
120
|
+
return u.toString();
|
|
121
|
+
}
|
|
54
122
|
/**
|
|
55
123
|
* The domains the SharePoint capture trusts: the one bridge scope
|
|
56
124
|
* (`bridge-scope.ts`), whose `sharepoint.com` covers every tenant SP host, while
|
|
@@ -105,45 +173,123 @@ export async function captureSharePointTokenViaFetchproxy(hosts, env = process.e
|
|
|
105
173
|
'*.sharepoint.com host');
|
|
106
174
|
}
|
|
107
175
|
const label = list.join(' or ');
|
|
108
|
-
//
|
|
109
|
-
//
|
|
110
|
-
|
|
111
|
-
|
|
176
|
+
// One capture attempt. A bridge scope refusal (the host is not yet granted)
|
|
177
|
+
// is turned into a typed, actionable McpToolError here — it will NOT get
|
|
178
|
+
// better on a retry, so the retry wrapper leaves McpToolErrors alone and only
|
|
179
|
+
// re-runs a plain capture failure (an idle-tab timeout).
|
|
180
|
+
const attempt = async () => {
|
|
181
|
+
let refused = false;
|
|
182
|
+
const scoped = bridgeScopedTransport(env, list);
|
|
183
|
+
try {
|
|
184
|
+
return await captureBearerHeader({
|
|
185
|
+
// Any call the browser makes to one of these hosts. Concrete hosts, never
|
|
186
|
+
// a wildcard — see the module note.
|
|
187
|
+
captures: list.map(sharePointCaptureDecl),
|
|
188
|
+
// The one bridge scope (`bridge-scope.ts`), with these hosts' captures
|
|
189
|
+
// added to the remembered ones so the hello asks for exactly what it is
|
|
190
|
+
// about to read.
|
|
191
|
+
domains: SHAREPOINT_TRUST_DOMAINS,
|
|
192
|
+
// Read per capture, not at import: see `capture-window.ts`.
|
|
193
|
+
windowMs: captureWindowMs(env),
|
|
194
|
+
port: getWsPort(),
|
|
195
|
+
serverName: PACKAGE_NAME,
|
|
196
|
+
version: VERSION,
|
|
197
|
+
what: `a SharePoint token for ${label}`,
|
|
198
|
+
guidance: `Open the file once in your signed-in browser (or reload your Teams tab) and retry while it ` +
|
|
199
|
+
`loads — that is what makes the page call ${label} with the SharePoint token we capture. ` +
|
|
200
|
+
`On a local install the file is normally downloaded straight through the browser with no token at all.`,
|
|
201
|
+
createTransport: (opts) => noteScopeRefusal(scoped(opts), () => (refused = true)),
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
catch (err) {
|
|
205
|
+
if (!refused)
|
|
206
|
+
throw err;
|
|
207
|
+
throw new McpToolError(`The ContextMint Bridge has not yet allowed a SharePoint token capture from ${label}.`, {
|
|
208
|
+
hint: `Open the ContextMint Bridge extension popup and approve the pending scope update for ${PACKAGE_NAME}, ` +
|
|
209
|
+
`which adds ${label} (no need to remove or re-pair it). Then retry, and reload your Teams tab while it waits.`,
|
|
210
|
+
cause: err,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
// Retry once on a timed-out capture window: the page may simply not have made
|
|
215
|
+
// a SharePoint request inside the first window, and a second often catches
|
|
216
|
+
// one. A scope refusal (a typed McpToolError) is already actionable, and a
|
|
217
|
+
// token-validation failure (too short, or no header at all) would only return
|
|
218
|
+
// the same on a retry — neither is retried.
|
|
112
219
|
let token;
|
|
113
220
|
try {
|
|
114
|
-
token = await
|
|
115
|
-
// Any call the browser makes to one of these hosts. Concrete hosts, never
|
|
116
|
-
// a wildcard — see the module note.
|
|
117
|
-
captures: list.map(sharePointCaptureDecl),
|
|
118
|
-
// The one bridge scope (`bridge-scope.ts`), with these hosts' captures
|
|
119
|
-
// added to the remembered ones so the hello asks for exactly what it is
|
|
120
|
-
// about to read.
|
|
121
|
-
domains: SHAREPOINT_TRUST_DOMAINS,
|
|
122
|
-
// Read per capture, not at import: see `capture-window.ts`.
|
|
123
|
-
windowMs: captureWindowMs(env),
|
|
124
|
-
port: getWsPort(),
|
|
125
|
-
serverName: PACKAGE_NAME,
|
|
126
|
-
version: VERSION,
|
|
127
|
-
what: `a SharePoint token for ${label}`,
|
|
128
|
-
guidance: `Reload your signed-in Teams tab and retry while it loads — that makes the ` +
|
|
129
|
-
`page call ${label} with the SharePoint token we capture.`,
|
|
130
|
-
createTransport: (opts) => noteScopeRefusal(scoped(opts), () => (refused = true)),
|
|
131
|
-
});
|
|
221
|
+
token = await attempt();
|
|
132
222
|
}
|
|
133
223
|
catch (err) {
|
|
134
|
-
if (!
|
|
224
|
+
if (!isRetryableCaptureError(err))
|
|
135
225
|
throw err;
|
|
136
|
-
|
|
137
|
-
hint: `Open the ContextMint Bridge extension popup and approve the pending scope update for ${PACKAGE_NAME}, ` +
|
|
138
|
-
`which adds ${label} (no need to remove or re-pair it). Then retry, and reload your Teams tab while it waits.`,
|
|
139
|
-
cause: err,
|
|
140
|
-
});
|
|
226
|
+
token = await attempt();
|
|
141
227
|
}
|
|
228
|
+
verifySharePointAudience(token, label);
|
|
142
229
|
// Granted and captured: every later hello declares these hosts too.
|
|
143
230
|
for (const h of list)
|
|
144
231
|
rememberSharePointHost(h, env);
|
|
145
232
|
return token;
|
|
146
233
|
}
|
|
234
|
+
/**
|
|
235
|
+
* Whether one `aud` value names SharePoint: the resource GUID (bare, or in its
|
|
236
|
+
* v1 form `GUID/host@tenant`), or a url whose host is a concrete
|
|
237
|
+
* `*.sharepoint.com` tenant host. Any other Office service — notably
|
|
238
|
+
* `substrate.office.com`, whose token this server also captures — is not.
|
|
239
|
+
*/
|
|
240
|
+
function isSharePointAudience(aud) {
|
|
241
|
+
if (aud === SHAREPOINT_RESOURCE_GUID || aud.startsWith(`${SHAREPOINT_RESOURCE_GUID}/`))
|
|
242
|
+
return true;
|
|
243
|
+
try {
|
|
244
|
+
return isSharePointHost(new URL(aud).hostname);
|
|
245
|
+
}
|
|
246
|
+
catch {
|
|
247
|
+
return false;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Reject a captured token whose audience is not SharePoint's, before it is
|
|
252
|
+
* cached and replayed into repeated 401s. The capture snapshots whatever
|
|
253
|
+
* `Authorization` header the browser sent to the host; this guards against
|
|
254
|
+
* snapshotting a wrong-audience token (a different Office service's) by
|
|
255
|
+
* mistake. Lenient only about what it cannot read: a token whose payload will
|
|
256
|
+
* not decode, or whose `aud` is absent, is accepted — a decodable `aud` that
|
|
257
|
+
* {@link isSharePointAudience} does not accept is refused.
|
|
258
|
+
*/
|
|
259
|
+
function verifySharePointAudience(token, label) {
|
|
260
|
+
const parts = token.split('.');
|
|
261
|
+
if (parts.length < 2)
|
|
262
|
+
return;
|
|
263
|
+
let aud;
|
|
264
|
+
try {
|
|
265
|
+
aud = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')).aud;
|
|
266
|
+
}
|
|
267
|
+
catch {
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
const auds = (Array.isArray(aud) ? aud : [aud]).filter((a) => typeof a === 'string' && a !== '');
|
|
271
|
+
if (auds.length === 0)
|
|
272
|
+
return;
|
|
273
|
+
const ok = auds.some(isSharePointAudience);
|
|
274
|
+
if (!ok) {
|
|
275
|
+
throw new McpToolError(`Captured a token for ${label} whose audience is not SharePoint's.`, {
|
|
276
|
+
kind: 'credential_rejected',
|
|
277
|
+
hint: `The browser's last request to ${label} carried a token for a different service. Open the file in ` +
|
|
278
|
+
`SharePoint (or reload Teams) so the page makes a SharePoint request, then retry.`,
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Whether a failed capture attempt is worth one retry: only a bridge/window
|
|
284
|
+
* timeout is. A scope refusal is a typed {@link McpToolError} (actionable as
|
|
285
|
+
* is), and a token-validation failure — the header was too short, or none was
|
|
286
|
+
* captured — would return the same on a retry, so neither qualifies.
|
|
287
|
+
*/
|
|
288
|
+
function isRetryableCaptureError(err) {
|
|
289
|
+
if (err instanceof McpToolError)
|
|
290
|
+
return false;
|
|
291
|
+
return err instanceof Error && !/too short|returned no header/i.test(err.message);
|
|
292
|
+
}
|
|
147
293
|
/** Call `onRefused` when the bridge refuses a capture for being outside the granted scope. */
|
|
148
294
|
function noteScopeRefusal(transport, onRefused) {
|
|
149
295
|
const server = transport.server;
|
package/dist/sharepoint.js
CHANGED
|
@@ -25,11 +25,13 @@
|
|
|
25
25
|
* As with `chatsvc.ts`, once a token is held every request is a plain Node
|
|
26
26
|
* `fetch` — the bridge is only ever touched to capture the token.
|
|
27
27
|
*/
|
|
28
|
+
import { readFile, rm } from 'node:fs/promises';
|
|
28
29
|
import { fetchBounded, McpToolError, parseBoolEnv } from '@chrischall/mcp-utils';
|
|
29
30
|
import { describeTransportFailure } from './network-error.js';
|
|
30
31
|
import { createCapturedTokenManager } from '@chrischall/mcp-utils/session';
|
|
31
32
|
import { createSharePointTokenCache } from './sharepoint-token-cache.js';
|
|
32
33
|
import { knownSharePointHosts } from './bridge-scope.js';
|
|
34
|
+
import { PACKAGE_NAME } from './version.js';
|
|
33
35
|
/**
|
|
34
36
|
* Capture a SharePoint token for `host` lazily.
|
|
35
37
|
*
|
|
@@ -43,8 +45,56 @@ async function captureSharePointTokenLazily(hosts) {
|
|
|
43
45
|
const mod = await import('./sharepoint-auth.js');
|
|
44
46
|
return mod.captureSharePointTokenViaFetchproxy(hosts);
|
|
45
47
|
}
|
|
48
|
+
/**
|
|
49
|
+
* Download a shared file through the browser's own `chrome.downloads`, lazily
|
|
50
|
+
* (see {@link captureSharePointTokenLazily} for why the bridge peer is only ever
|
|
51
|
+
* imported on demand). Returns the saved local path + metadata.
|
|
52
|
+
*/
|
|
53
|
+
async function downloadViaBrowserLazily(objectUrl, env) {
|
|
54
|
+
const mod = await import('./sharepoint-auth.js');
|
|
55
|
+
return mod.downloadSharePointFileViaBrowser(objectUrl, env);
|
|
56
|
+
}
|
|
46
57
|
/** Per-request deadline, covering the body read. */
|
|
47
58
|
const REQUEST_TIMEOUT_MS = 60_000;
|
|
59
|
+
/** Sentinel: the browser `download` capability is declared but not yet granted in the bridge. */
|
|
60
|
+
const GRANT_NEEDED = Symbol('download-grant-needed');
|
|
61
|
+
/**
|
|
62
|
+
* Whether a browser-download failure is specifically the `download` capability
|
|
63
|
+
* not being granted yet (the one-time approval), as opposed to the capability
|
|
64
|
+
* being unavailable (Safari) or the saved file being off-machine (hosted). The
|
|
65
|
+
* bridge reports it as `capability "download" not granted` / `capability_denied`.
|
|
66
|
+
*/
|
|
67
|
+
function isDownloadGrantMissing(err) {
|
|
68
|
+
const m = err instanceof Error ? err.message : '';
|
|
69
|
+
return /\bdownload\b/i.test(m) && /not granted|denied/i.test(m);
|
|
70
|
+
}
|
|
71
|
+
/** The host of a url for a message, or the url itself when it will not parse. */
|
|
72
|
+
function hostOf(url) {
|
|
73
|
+
try {
|
|
74
|
+
return new URL(url).host;
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return url;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function pageInPlaceOfFile(data, mime, objectUrl) {
|
|
81
|
+
const head = data.subarray(0, 64 * 1024).toString('latin1');
|
|
82
|
+
const isHtml = /^text\/html\b/i.test(mime ?? '') || /^\s*<(!doctype\s+html|html|head|body|script)\b/i.test(head);
|
|
83
|
+
if (!isHtml)
|
|
84
|
+
return null;
|
|
85
|
+
if (/\/_forms\/default\.aspx/i.test(head))
|
|
86
|
+
return 'sign-in';
|
|
87
|
+
if (/g_requestAccessContext|\bAccessDenied\b/i.test(head))
|
|
88
|
+
return 'access-denied';
|
|
89
|
+
let wantsPage = false;
|
|
90
|
+
try {
|
|
91
|
+
wantsPage = /\.(x?html?|aspx?)$/i.test(new URL(objectUrl).pathname);
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
// An unparseable url was vetted by the browser path already; treat as a file.
|
|
95
|
+
}
|
|
96
|
+
return wantsPage ? null : 'other-page';
|
|
97
|
+
}
|
|
48
98
|
/** Run one fetch, turning "never got a response" into an error naming the host and cause. */
|
|
49
99
|
async function reachable(url, run) {
|
|
50
100
|
try {
|
|
@@ -58,6 +108,7 @@ export class SharePointClient {
|
|
|
58
108
|
#env;
|
|
59
109
|
#capture;
|
|
60
110
|
#knownHosts;
|
|
111
|
+
#browserDownload;
|
|
61
112
|
#fetchImpl;
|
|
62
113
|
#cache;
|
|
63
114
|
/**
|
|
@@ -73,6 +124,7 @@ export class SharePointClient {
|
|
|
73
124
|
this.#env = opts.env ?? process.env;
|
|
74
125
|
this.#capture = opts.captureToken ?? captureSharePointTokenLazily;
|
|
75
126
|
this.#knownHosts = opts.knownHosts ?? (() => knownSharePointHosts(this.#env));
|
|
127
|
+
this.#browserDownload = opts.browserDownload ?? ((objectUrl) => downloadViaBrowserLazily(objectUrl, this.#env));
|
|
76
128
|
// A receiver-safe wrapper, never the bare global: older undici throws
|
|
77
129
|
// `Illegal invocation` when `fetch` is called with a non-global receiver.
|
|
78
130
|
this.#fetchImpl = opts.fetchImpl ?? ((input, init) => fetch(input, init));
|
|
@@ -97,13 +149,139 @@ export class SharePointClient {
|
|
|
97
149
|
* Download the contents of a shared file by its `objectUrl` (the `url` a file
|
|
98
150
|
* attachment carries). Returns the bytes, the mime type and the byte count.
|
|
99
151
|
*
|
|
152
|
+
* Two paths, browser-first:
|
|
153
|
+
* 1. {@link #downloadViaBrowser} — `chrome.downloads` with the browser's own
|
|
154
|
+
* cookies. No token capture, so it works even when an idle Teams tab's
|
|
155
|
+
* cached token would starve the bearer capture, and on any tenant host
|
|
156
|
+
* without a per-host grant. Local installs only (it reads the saved file
|
|
157
|
+
* off the same disk).
|
|
158
|
+
* 2. {@link #downloadViaBearer} — the SharePoint v2.1 shares API with a
|
|
159
|
+
* captured bearer token. The fallback: hosted installs, Safari (no
|
|
160
|
+
* `chrome.downloads`), or a denied/failed browser download.
|
|
161
|
+
*
|
|
100
162
|
* The URL comes out of message content — i.e. it is attacker-influenced — so
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
-
* bearer to whoever wrote the message.
|
|
163
|
+
* each path vets it (https only, a concrete `*.sharepoint.com` tenant host)
|
|
164
|
+
* BEFORE it is used. Anything else would hand the browser's cookies or the
|
|
165
|
+
* SharePoint bearer to whoever wrote the message.
|
|
104
166
|
*/
|
|
105
167
|
async downloadFile(objectUrl, maxBytes) {
|
|
106
168
|
this.#requireConfigured();
|
|
169
|
+
// An oversize file thrown here propagates (the attachment tool degrades to
|
|
170
|
+
// metadata + link) rather than falling through to the bearer path, which
|
|
171
|
+
// would otherwise capture a token only to re-derive the same limit.
|
|
172
|
+
const viaBrowser = await this.#downloadViaBrowser(objectUrl, maxBytes);
|
|
173
|
+
if (viaBrowser !== null && viaBrowser !== GRANT_NEEDED)
|
|
174
|
+
return viaBrowser;
|
|
175
|
+
// The browser path was unavailable. If it was specifically a MISSING grant
|
|
176
|
+
// (a local install where the user has not yet approved the `download`
|
|
177
|
+
// capability), the bearer path will probably hit its flaky capture — so if
|
|
178
|
+
// it fails too, tell the user the one thing that fixes everything: approve
|
|
179
|
+
// the grant. Otherwise (hosted, Safari) the bearer path is simply the way.
|
|
180
|
+
try {
|
|
181
|
+
return await this.#downloadViaBearer(objectUrl, maxBytes);
|
|
182
|
+
}
|
|
183
|
+
catch (err) {
|
|
184
|
+
throw viaBrowser === GRANT_NEEDED ? this.#withGrantHint(err) : err;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* The browser-download path. Returns the bytes, {@link GRANT_NEEDED} when the
|
|
189
|
+
* `download` capability has not been approved in the bridge yet, or `null`
|
|
190
|
+
* when it is unavailable for any other reason (hosted install, Safari, a bad
|
|
191
|
+
* URL) — either sentinel sends the caller to the bearer path. Throws only for
|
|
192
|
+
* an oversize file: a terminal, actionable outcome.
|
|
193
|
+
*/
|
|
194
|
+
async #downloadViaBrowser(objectUrl, maxBytes) {
|
|
195
|
+
let meta;
|
|
196
|
+
try {
|
|
197
|
+
meta = await this.#browserDownload(objectUrl);
|
|
198
|
+
}
|
|
199
|
+
catch (err) {
|
|
200
|
+
// Unavailable, denied, or a bad URL — the bearer path vets and reports.
|
|
201
|
+
// A missing `download` grant is singled out so the caller can say so.
|
|
202
|
+
return isDownloadGrantMissing(err) ? GRANT_NEEDED : null;
|
|
203
|
+
}
|
|
204
|
+
if (meta === null)
|
|
205
|
+
return null;
|
|
206
|
+
// The browser reports the size before we read: refuse an oversize file
|
|
207
|
+
// without reading it, same as the bearer path's `size` check.
|
|
208
|
+
if (typeof meta.bytes === 'number' && meta.bytes > maxBytes) {
|
|
209
|
+
await this.#removeTemp(meta.path);
|
|
210
|
+
throw this.#tooLargeError(meta.bytes, maxBytes);
|
|
211
|
+
}
|
|
212
|
+
let data;
|
|
213
|
+
try {
|
|
214
|
+
data = await readFile(meta.path);
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
// The saved file is not on this machine (a hosted install) or vanished:
|
|
218
|
+
// fall back to the bearer path.
|
|
219
|
+
await this.#removeTemp(meta.path);
|
|
220
|
+
return null;
|
|
221
|
+
}
|
|
222
|
+
await this.#removeTemp(meta.path);
|
|
223
|
+
// A page saved in place of the file is not the file.
|
|
224
|
+
const page = pageInPlaceOfFile(data, meta.mime, objectUrl);
|
|
225
|
+
// Access denied: the browser asked as the user's own account and was
|
|
226
|
+
// refused. The bearer token is that same account, so trying it would only
|
|
227
|
+
// burn a capture timeout (~60s) to reach the same 403. Fail now, as a 403,
|
|
228
|
+
// which the attachment tool turns into "ask whoever shared it for access".
|
|
229
|
+
if (page === 'access-denied') {
|
|
230
|
+
throw new McpToolError(`Your account cannot open this file on ${hostOf(objectUrl)}.`, {
|
|
231
|
+
kind: 'http',
|
|
232
|
+
status: 403,
|
|
233
|
+
hint: 'Open its link to request access from whoever shared it, then retry.',
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
// A sign-in page (no browser session on that host) or any other page: let
|
|
237
|
+
// the bearer path (one token serves every host) try, and degrade to
|
|
238
|
+
// metadata + link cleanly if it cannot.
|
|
239
|
+
if (page !== null)
|
|
240
|
+
return null;
|
|
241
|
+
// `bytes: 0` means the browser could not report the size, so the cap was not
|
|
242
|
+
// checked above — enforce it now on the real length.
|
|
243
|
+
if (data.length > maxBytes)
|
|
244
|
+
throw this.#tooLargeError(data.length, maxBytes);
|
|
245
|
+
const mimeType = typeof meta.mime === 'string' && meta.mime !== '' ? meta.mime.split(';')[0].trim() : 'application/octet-stream';
|
|
246
|
+
return { mimeType, data, size: data.length };
|
|
247
|
+
}
|
|
248
|
+
/** Delete a browser-downloaded temp file, best-effort (it was ours to clean up). */
|
|
249
|
+
async #removeTemp(path) {
|
|
250
|
+
await rm(path, { force: true }).catch(() => { });
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Append, to a failed bearer-path error, the one fix for a local install whose
|
|
254
|
+
* only problem is the un-approved `download` grant: approve it and the file
|
|
255
|
+
* downloads straight through the browser with no token capture at all.
|
|
256
|
+
*/
|
|
257
|
+
#withGrantHint(err) {
|
|
258
|
+
const extra = `If this is a local install, the simplest fix is to approve the ContextMint Bridge grant that adds ` +
|
|
259
|
+
`file download for ${PACKAGE_NAME} (open the extension popup) — then the file is fetched straight through ` +
|
|
260
|
+
`the browser with no token capture needed.`;
|
|
261
|
+
if (err instanceof McpToolError) {
|
|
262
|
+
return new McpToolError(err.message, {
|
|
263
|
+
...(err.kind !== undefined ? { kind: err.kind } : {}),
|
|
264
|
+
...(err.status !== undefined ? { status: err.status } : {}),
|
|
265
|
+
hint: err.hint !== undefined && err.hint !== '' ? `${err.hint} ${extra}` : extra,
|
|
266
|
+
cause: err,
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
return err;
|
|
270
|
+
}
|
|
271
|
+
/** The oversize-file error, shared by both download paths. */
|
|
272
|
+
#tooLargeError(size, maxBytes) {
|
|
273
|
+
const mb = (n) => `${Math.round(n / (1024 * 1024))} MB`;
|
|
274
|
+
return new McpToolError(`The file is ${mb(size)}, larger than the ${mb(maxBytes)} download limit.`, {
|
|
275
|
+
kind: 'http',
|
|
276
|
+
hint: `This file is ${mb(size)}; open it with its link rather than downloading it here.`,
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* The bearer-token path: the SharePoint v2.1 shares API with a token captured
|
|
281
|
+
* from the browser. The fallback when {@link #downloadViaBrowser} is
|
|
282
|
+
* unavailable.
|
|
283
|
+
*/
|
|
284
|
+
async #downloadViaBearer(objectUrl, maxBytes) {
|
|
107
285
|
let target;
|
|
108
286
|
try {
|
|
109
287
|
target = new URL(objectUrl);
|
|
@@ -138,11 +316,7 @@ export class SharePointClient {
|
|
|
138
316
|
// surfaces this hint) instead of fetching to the byte limit and tripping a
|
|
139
317
|
// less actionable read error.
|
|
140
318
|
if (typeof meta.size === 'number' && meta.size > maxBytes) {
|
|
141
|
-
|
|
142
|
-
throw new McpToolError(`The file is ${mb(meta.size)}, larger than the ${mb(maxBytes)} download limit.`, {
|
|
143
|
-
kind: 'http',
|
|
144
|
-
hint: `This file is ${mb(meta.size)}; open it with its link rather than downloading it here.`,
|
|
145
|
-
});
|
|
319
|
+
throw this.#tooLargeError(meta.size, maxBytes);
|
|
146
320
|
}
|
|
147
321
|
const downloadUrl = meta['@content.downloadUrl'];
|
|
148
322
|
if (typeof downloadUrl !== 'string' || downloadUrl === '') {
|
package/dist/tools/send.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { CONFIRM_FLOW_SENTENCE, CONFIRM_INJECTION_RULE, confirmTokenParam, confirmWrite, McpToolError, toolAnnotations, unknownOutcomeReason, writeOrUnknown, } from '@chrischall/mcp-utils';
|
|
3
3
|
import { buildSendBody, clipText, MESSAGE_FORMATS, mentionsProperty, newClientMessageId, qtdMsgsProperty, quoteHtml, renderMessageHtml, } from '../compose.js';
|
|
4
|
-
import { htmlToText, normaliseMessage, SELF_CHAT, senderMri } from '../model.js';
|
|
4
|
+
import { htmlToText, localIsoTime, normaliseMessage, SELF_CHAT, senderMri } from '../model.js';
|
|
5
5
|
import { resolveListed } from './conversation.js';
|
|
6
6
|
import { wrapApiError } from './errors.js';
|
|
7
7
|
import { MRI, recentSenders } from './people.js';
|
|
8
8
|
import { THIRD_PARTY_NAMES_NOTE, untrustedField, untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX, } from './untrusted.js';
|
|
9
9
|
import { workMeta } from './hints.js';
|
|
10
|
+
import { resolveTimeZone } from './timezone.js';
|
|
10
11
|
const TOOL = 'teams_send_message';
|
|
11
12
|
/**
|
|
12
13
|
* The user's own notes chat — the one `48:*` system conversation that takes
|
|
@@ -20,6 +21,8 @@ const READBACK_MESSAGES = 50;
|
|
|
20
21
|
const MAX_CANDIDATES = 10;
|
|
21
22
|
/** Previewed text of a quoted message. */
|
|
22
23
|
const PREVIEW_CHARS = 200;
|
|
24
|
+
/** Quoted text carried in the preview's one-line `quoting`. */
|
|
25
|
+
const QUOTING_LINE_CHARS = 80;
|
|
23
26
|
/** How `text` is read: shared by `teams_send_message` and `teams_edit_message`. */
|
|
24
27
|
export const formatParam = z
|
|
25
28
|
.enum(MESSAGE_FORMATS)
|
|
@@ -102,7 +105,45 @@ async function quoted(chatsvc, conversationId, id) {
|
|
|
102
105
|
});
|
|
103
106
|
}
|
|
104
107
|
const mri = senderMri(m.from) ?? '';
|
|
105
|
-
|
|
108
|
+
const time = m.originalarrivaltime ?? m.composetime;
|
|
109
|
+
return {
|
|
110
|
+
id: m.id,
|
|
111
|
+
senderMri: mri,
|
|
112
|
+
senderName: m.imdisplayname?.trim() || mri,
|
|
113
|
+
text: htmlToText(m.content ?? ''),
|
|
114
|
+
...(time ? { time } : {}),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* When a quoted message was sent, to the minute: in TEAMS_TIME_ZONE when one is
|
|
119
|
+
* set ("2026-11-12 12:31 America/New_York"), else UTC. A bad TEAMS_TIME_ZONE
|
|
120
|
+
* falls back to UTC here — it must not stop a preview.
|
|
121
|
+
*/
|
|
122
|
+
function quotedWhen(iso) {
|
|
123
|
+
if (iso === undefined || Number.isNaN(Date.parse(iso)))
|
|
124
|
+
return undefined;
|
|
125
|
+
let zone;
|
|
126
|
+
try {
|
|
127
|
+
zone = resolveTimeZone(undefined);
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
zone = undefined;
|
|
131
|
+
}
|
|
132
|
+
const local = zone !== undefined ? localIsoTime(iso, zone) : undefined;
|
|
133
|
+
if (zone !== undefined && local !== undefined)
|
|
134
|
+
return `${local.slice(0, 16).replace('T', ' ')} ${zone}`;
|
|
135
|
+
return `${new Date(iso).toISOString().slice(0, 16).replace('T', ' ')} UTC`;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* The preview's plain-words `quoting` line: `none`, or the quoted sender, when
|
|
139
|
+
* and the start of what they wrote. Sender and text are other people's, so each
|
|
140
|
+
* is JSON-quoted (on one line, its own quotes escaped) as the title is in the summary.
|
|
141
|
+
*/
|
|
142
|
+
function quotingLine(q) {
|
|
143
|
+
if (q === undefined)
|
|
144
|
+
return 'none';
|
|
145
|
+
const when = quotedWhen(q.time);
|
|
146
|
+
return `${JSON.stringify(q.senderName)}${when ? `, ${when}` : ''}: ${JSON.stringify(clipText(q.text, QUOTING_LINE_CHARS, '…'))}`;
|
|
106
147
|
}
|
|
107
148
|
/**
|
|
108
149
|
* The channel root post a threaded reply goes under, read to prove it is one:
|
|
@@ -147,9 +188,13 @@ export function registerSendTools(server, { chatsvc }) {
|
|
|
147
188
|
':eyes:, :white_check_mark:, …) and unicode-style keys (:1f680_rocket:). format "markdown" ' +
|
|
148
189
|
'reads text as Markdown instead: **bold**, *italic*, ~~strike~~, `inline code`, ``` code blocks ```, ' +
|
|
149
190
|
'bulleted (- item) and numbered (1. item) lists, [link text](https://…), blank-line paragraphs and ' +
|
|
150
|
-
'line breaks; raw HTML, headings, quotes and images are escaped and shown as written.
|
|
151
|
-
'channel posts into that root post\'s thread
|
|
152
|
-
'quote
|
|
191
|
+
'line breaks; raw HTML, headings, quotes and images are escaped and shown as written. By default ' +
|
|
192
|
+
'nothing is quoted. reply_to in a channel posts into that root post\'s thread (a thread reply, no ' +
|
|
193
|
+
'quote); in a chat, reply_to and quote are the same thing: both quote-reply that message, so the ' +
|
|
194
|
+
'post opens with a quote of it. quote quote-replies a message in any conversation. Pass reply_to ' +
|
|
195
|
+
'or quote only when the user asked for a reply or a quote; when the request is ambiguous (they ' +
|
|
196
|
+
'mention a message\'s timestamp, or say "reply" in a chat), ask them whether they want it quoted ' +
|
|
197
|
+
'rather than guessing. mentions @-mention people: name_in_text must appear ' +
|
|
153
198
|
'in text, and person is an MRI or a display name matched among recent senders (ambiguous names ' +
|
|
154
199
|
`are refused with the candidates). conversation "${SELF_CHAT}" (or "notes" / "self") is the user's own notes self-chat — ` +
|
|
155
200
|
'use it to try this tool without anyone else seeing; other 48: system conversations are refused. ' +
|
|
@@ -157,7 +202,8 @@ export function registerSendTools(server, { chatsvc }) {
|
|
|
157
202
|
'reading the conversation back (verified); status "unknown" means Teams did not confirm it — check ' +
|
|
158
203
|
'the conversation before retrying. ' +
|
|
159
204
|
CONFIRM_FLOW_SENTENCE +
|
|
160
|
-
' The preview shows the conversation and exactly what would be posted
|
|
205
|
+
' The preview shows the conversation and exactly what would be posted, says in plain words what ' +
|
|
206
|
+
'is quoted (quoting: the sender, time and text, or "none"), and warns when reply_to is set. ' +
|
|
161
207
|
CONFIRM_INJECTION_RULE +
|
|
162
208
|
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
163
209
|
annotations: toolAnnotations({ readOnly: false, destructive: true, idempotent: false, openWorld: true }),
|
|
@@ -177,8 +223,9 @@ export function registerSendTools(server, { chatsvc }) {
|
|
|
177
223
|
.string()
|
|
178
224
|
.min(1)
|
|
179
225
|
.optional()
|
|
180
|
-
.describe('A message id. Channel: the root post to reply under (threaded). Chat: the message to
|
|
181
|
-
|
|
226
|
+
.describe('A message id. Channel: the root post to reply under (threaded, no quote). Chat: the message to ' +
|
|
227
|
+
'quote-reply — the same as quote. Only when the user asked for a reply or quote.'),
|
|
228
|
+
quote: z.string().min(1).optional().describe('A message id to quote-reply, in any conversation. Only when the user asked for a quote.'),
|
|
182
229
|
mentions: z.array(mentionArg).max(20).optional().describe('People to @-mention in text.'),
|
|
183
230
|
confirmToken: confirmTokenParam,
|
|
184
231
|
},
|
|
@@ -205,6 +252,15 @@ export function registerSendTools(server, { chatsvc }) {
|
|
|
205
252
|
const people = await resolveMentions(chatsvc, target.id, mentions ?? []);
|
|
206
253
|
const rendered = renderMessageHtml(text, people.map((p) => p.target), format);
|
|
207
254
|
const content = (q ? quoteHtml(q) : '') + rendered.html;
|
|
255
|
+
const quoting = quotingLine(q);
|
|
256
|
+
// reply_to is easy to pass by reflex; it changes what is posted, so the preview says so.
|
|
257
|
+
const replyWarning = reply_to === undefined
|
|
258
|
+
? undefined
|
|
259
|
+
: inChannel
|
|
260
|
+
? `reply_to is set: this posts into the thread under root post ${reply_to}, not as a new post ` +
|
|
261
|
+
'in the channel. Drop reply_to unless the user asked to reply in that thread.'
|
|
262
|
+
: `reply_to is set: in a chat it quote-replies message ${reply_to}, so the post opens with a ` +
|
|
263
|
+
'quote of it (see quoting). Drop reply_to unless the user asked for a quote.';
|
|
208
264
|
const properties = {
|
|
209
265
|
...(rendered.mentions.length > 0 ? { mentions: mentionsProperty(rendered.mentions) } : {}),
|
|
210
266
|
...(q ? { qtdMsgs: qtdMsgsProperty(q) } : {}),
|
|
@@ -220,7 +276,9 @@ export function registerSendTools(server, { chatsvc }) {
|
|
|
220
276
|
action: 'chat.send_message',
|
|
221
277
|
message: 'Review and confirm this Teams message before it is posted:',
|
|
222
278
|
// The title is someone else's text: JSON-quoted so it cannot break out of its quotes.
|
|
223
|
-
summary: `Post a message to ${target.kind} ${JSON.stringify(target.title)}
|
|
279
|
+
summary: `Post a message to ${target.kind} ${JSON.stringify(target.title)}` +
|
|
280
|
+
(q ? `, quoting ${JSON.stringify(q.senderName)}` : ', no quote') +
|
|
281
|
+
(inChannel && reply_to !== undefined ? `, in the thread under ${reply_to}` : ''),
|
|
224
282
|
// The signed-in user, so an approval minted under one account never posts as another.
|
|
225
283
|
account: me,
|
|
226
284
|
target: postTo,
|
|
@@ -230,6 +288,8 @@ export function registerSendTools(server, { chatsvc }) {
|
|
|
230
288
|
// result is; `text` is the caller's own.
|
|
231
289
|
preview: {
|
|
232
290
|
conversation: untrustedField(target),
|
|
291
|
+
quoting,
|
|
292
|
+
...(replyWarning ? { warning: replyWarning } : {}),
|
|
233
293
|
text,
|
|
234
294
|
format,
|
|
235
295
|
...(inChannel && reply_to !== undefined ? { thread_root: reply_to } : {}),
|
|
@@ -243,7 +303,7 @@ export function registerSendTools(server, { chatsvc }) {
|
|
|
243
303
|
}
|
|
244
304
|
: {}),
|
|
245
305
|
...(q
|
|
246
|
-
? {
|
|
306
|
+
? { quoted_message: untrustedField({ id: q.id, sender: q.senderName, preview: clipText(q.text, PREVIEW_CHARS) }) }
|
|
247
307
|
: {}),
|
|
248
308
|
note: 'clientmessageid and the timestamps are filled in when the message is posted.',
|
|
249
309
|
},
|
package/dist/version.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chrischall/microsoft-teams-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
4
4
|
"mcpName": "io.github.chrischall/microsoft-teams-mcp",
|
|
5
5
|
"description": "Microsoft Teams MCP server for Claude — developed and maintained by AI (Claude Code)",
|
|
6
6
|
"author": "Claude Code (AI) <https://www.anthropic.com/claude>",
|