@chrischall/microsoft-teams-mcp 0.14.0 → 0.15.1
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 +248 -37
- package/dist/attachments.js +238 -0
- package/dist/auth-fetchproxy.js +7 -6
- package/dist/browser-open.js +159 -0
- package/dist/bundle.js +6849 -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 +26 -0
- package/package.json +4 -1
- package/server.json +37 -2
- package/skills/teams-fpx/SKILL.md +2 -2
- package/skills/teams-fpx/references/teams-env.sh +1 -1
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a token capture tells the person waiting on it — while it waits, and
|
|
3
|
+
* when it fails. Bridge-free, so tools and clients can import it without
|
|
4
|
+
* loading the optional `@fetchproxy/server` peer.
|
|
5
|
+
*
|
|
6
|
+
* THE TIMING RULE every message here is built around (diagnosed live
|
|
7
|
+
* 2026-12-02): a capture resolves on the NEXT matching request the Teams page
|
|
8
|
+
* makes WHILE the capture is waiting (`capture_request_header` is a one-shot
|
|
9
|
+
* `webRequest` listener; it has no "recently seen" mode). Clicking into a chat
|
|
10
|
+
* before the tool call starts never counts. The old guidance — "click into any
|
|
11
|
+
* chat, then retry" — had the order backwards, so an agent that followed it
|
|
12
|
+
* (it cannot act during its own tool call) timed out on every retry. Every
|
|
13
|
+
* hint now says the action has to happen within the window AFTER the call
|
|
14
|
+
* starts, and names the window's length.
|
|
15
|
+
*
|
|
16
|
+
* While a capture waits, {@link captureWithFeedback} sends MCP progress
|
|
17
|
+
* notifications ("click into any chat now (25s left)") to a caller that asked
|
|
18
|
+
* for progress, so a client that shows them gives the human the chance to act
|
|
19
|
+
* in time, and fires an optional nudge (a local install opens a Teams tab,
|
|
20
|
+
* whose page load makes the request — `teamsTabNudger` in `browser-open.ts`).
|
|
21
|
+
*
|
|
22
|
+
* A failure is classified into a stable code (the step that failed) and
|
|
23
|
+
* remembered per token, for `teams_token_status`.
|
|
24
|
+
*/
|
|
25
|
+
import { McpToolError, reportProgress } from '@chrischall/mcp-utils';
|
|
26
|
+
/** The stable error code a caller can match on: `token_<step>`. */
|
|
27
|
+
export function captureErrorCode(code) {
|
|
28
|
+
return `token_${code}`;
|
|
29
|
+
}
|
|
30
|
+
/** What each token is called, and what makes the page send the request it is read from. */
|
|
31
|
+
const TOKENS = {
|
|
32
|
+
chat_service: {
|
|
33
|
+
name: 'Teams access token',
|
|
34
|
+
request: 'chat-service',
|
|
35
|
+
now: 'click into any chat now',
|
|
36
|
+
action: 'click into any chat in your signed-in Teams tab (teams.cloud.microsoft)',
|
|
37
|
+
},
|
|
38
|
+
substrate: {
|
|
39
|
+
name: 'Substrate search token',
|
|
40
|
+
request: 'search',
|
|
41
|
+
now: 'run any search in its search box now',
|
|
42
|
+
action: 'type anything into the search box at the top of your signed-in Teams tab and press Enter',
|
|
43
|
+
},
|
|
44
|
+
sharepoint: {
|
|
45
|
+
name: 'SharePoint token',
|
|
46
|
+
request: 'SharePoint',
|
|
47
|
+
now: 'open the file or reload the tab now',
|
|
48
|
+
action: 'open the file in your signed-in browser (or reload your Teams tab)',
|
|
49
|
+
},
|
|
50
|
+
recap: {
|
|
51
|
+
name: 'meeting-recap token',
|
|
52
|
+
request: 'meeting-recap',
|
|
53
|
+
now: "open a meeting chat's Recap tab now",
|
|
54
|
+
action: 'open any meeting chat in your signed-in Teams tab and click its Recap tab',
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
/** The action that makes the page send `token`'s request (for progress text and status output). */
|
|
58
|
+
export function tokenAction(token) {
|
|
59
|
+
return TOKENS[token].action;
|
|
60
|
+
}
|
|
61
|
+
const seconds = (ms) => Math.max(1, Math.round(ms / 1000));
|
|
62
|
+
/**
|
|
63
|
+
* The one correctly-ordered instruction: retry, and act within the window
|
|
64
|
+
* after the call starts. Every capture's guidance and every hint uses it.
|
|
65
|
+
*/
|
|
66
|
+
export function whileWaitingGuidance(token, windowMs) {
|
|
67
|
+
return (`Retry, and within ${seconds(windowMs)} seconds of starting it ${TOKENS[token].action} — the token is read ` +
|
|
68
|
+
'off the NEXT request the page makes while the call is waiting, so anything done before the call starts ' +
|
|
69
|
+
'does not count.');
|
|
70
|
+
}
|
|
71
|
+
/** A failed capture, with the step that failed and how long it waited. The message is the capture's own. */
|
|
72
|
+
export class TokenCaptureError extends Error {
|
|
73
|
+
token;
|
|
74
|
+
code;
|
|
75
|
+
waitedMs;
|
|
76
|
+
windowMs;
|
|
77
|
+
/** When the token this capture was replacing expired (epoch ms), if one was held. */
|
|
78
|
+
previousExpiresAt;
|
|
79
|
+
constructor(message, opts) {
|
|
80
|
+
super(message, opts.cause !== undefined ? { cause: opts.cause } : undefined);
|
|
81
|
+
this.name = 'TokenCaptureError';
|
|
82
|
+
this.token = opts.token;
|
|
83
|
+
this.code = opts.code;
|
|
84
|
+
this.waitedMs = opts.waitedMs;
|
|
85
|
+
this.windowMs = opts.windowMs;
|
|
86
|
+
if (opts.previousExpiresAt !== undefined)
|
|
87
|
+
this.previousExpiresAt = opts.previousExpiresAt;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** The step a capture failure came from, read off its type and text (see {@link CaptureCode}). */
|
|
91
|
+
export function classifyCaptureFailure(err) {
|
|
92
|
+
if (err instanceof TokenCaptureError)
|
|
93
|
+
return err.code;
|
|
94
|
+
if (err instanceof McpToolError && err.kind === 'credential_rejected')
|
|
95
|
+
return 'token_rejected';
|
|
96
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
97
|
+
if (/pair code|pairing required|pair-required|not granted|not in declared|awaiting[ -]approval|not yet allowed/i.test(message)) {
|
|
98
|
+
return 'bridge_not_approved';
|
|
99
|
+
}
|
|
100
|
+
if (/no extension|extension offline|bridge[_ ]down|session[_ ]not[_ ]ready|ECONNREFUSED|not connected/i.test(message)) {
|
|
101
|
+
return 'bridge_unreachable';
|
|
102
|
+
}
|
|
103
|
+
if (/\bno tab\b/i.test(message))
|
|
104
|
+
return 'no_tab';
|
|
105
|
+
if (/timed? ?out|timeout|nothing matched|window closed/i.test(message))
|
|
106
|
+
return 'no_request_seen';
|
|
107
|
+
return 'capture_failed';
|
|
108
|
+
}
|
|
109
|
+
const outcomes = new Map();
|
|
110
|
+
export function lastCaptureOutcome(token) {
|
|
111
|
+
return outcomes.get(token);
|
|
112
|
+
}
|
|
113
|
+
/** Forget every recorded outcome (tests). */
|
|
114
|
+
export function resetCaptureOutcomes() {
|
|
115
|
+
outcomes.clear();
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Run a capture with feedback: progress at once and every `intervalMs` until it
|
|
119
|
+
* settles ("click into any chat now (25s left)"), the nudge fired once, the
|
|
120
|
+
* outcome recorded. A plain failure is rethrown as a {@link TokenCaptureError}
|
|
121
|
+
* with the SAME message (callers still match "could not capture …") plus the
|
|
122
|
+
* step, the time waited and the previous expiry; an `McpToolError` (already
|
|
123
|
+
* actionable: a disabled bridge, a refused scope) passes through as is.
|
|
124
|
+
*/
|
|
125
|
+
export async function captureWithFeedback(opts) {
|
|
126
|
+
const { token, windowMs } = opts;
|
|
127
|
+
const progress = opts.progress ?? reportProgress;
|
|
128
|
+
const intervalMs = opts.intervalMs ?? 5_000;
|
|
129
|
+
const started = Date.now();
|
|
130
|
+
const total = seconds(windowMs);
|
|
131
|
+
const tell = () => {
|
|
132
|
+
const elapsed = Math.min(total, Math.floor((Date.now() - started) / 1000));
|
|
133
|
+
const left = Math.max(0, total - elapsed);
|
|
134
|
+
const text = `Waiting for the Teams tab: ${TOKENS[token].now} (${left}s left).`;
|
|
135
|
+
void progress(elapsed, total, text).catch(() => { });
|
|
136
|
+
};
|
|
137
|
+
tell();
|
|
138
|
+
const timer = setInterval(tell, intervalMs);
|
|
139
|
+
timer.unref?.();
|
|
140
|
+
if (opts.nudge !== undefined) {
|
|
141
|
+
try {
|
|
142
|
+
void Promise.resolve(opts.nudge()).catch(() => { });
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
// A nudge is a courtesy; the capture is what matters.
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
try {
|
|
149
|
+
const value = await opts.capture();
|
|
150
|
+
outcomes.set(token, { at: Date.now(), ok: true, waitedMs: Date.now() - started, windowMs });
|
|
151
|
+
return value;
|
|
152
|
+
}
|
|
153
|
+
catch (err) {
|
|
154
|
+
const waitedMs = Date.now() - started;
|
|
155
|
+
const code = classifyCaptureFailure(err);
|
|
156
|
+
outcomes.set(token, { at: Date.now(), ok: false, waitedMs, windowMs, code });
|
|
157
|
+
if (err instanceof McpToolError || err instanceof TokenCaptureError)
|
|
158
|
+
throw err;
|
|
159
|
+
throw new TokenCaptureError(err instanceof Error ? err.message : String(err), {
|
|
160
|
+
token,
|
|
161
|
+
code,
|
|
162
|
+
waitedMs,
|
|
163
|
+
windowMs,
|
|
164
|
+
...(opts.previousExpiresAt !== undefined && opts.previousExpiresAt > 0 ? { previousExpiresAt: opts.previousExpiresAt } : {}),
|
|
165
|
+
cause: err,
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
finally {
|
|
169
|
+
clearInterval(timer);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/** The bridge's own words from a `captureBearerHeader` message, without the guidance that follows them. */
|
|
173
|
+
function bridgeDetail(message) {
|
|
174
|
+
const m = /from the browser \((.*)\)\.(?:\s|$)/s.exec(message);
|
|
175
|
+
return (m?.[1] ?? message).trim();
|
|
176
|
+
}
|
|
177
|
+
/** The default window, for a plain error that carries none (`capture-window.ts`'s default). */
|
|
178
|
+
const DEFAULT_WINDOW_MS = 30_000;
|
|
179
|
+
/** Which token a plain capture error is about, from its text; `chat_service` when it does not say. */
|
|
180
|
+
function tokenOf(err) {
|
|
181
|
+
if (err instanceof TokenCaptureError)
|
|
182
|
+
return err.token;
|
|
183
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
184
|
+
if (/substrate/i.test(message))
|
|
185
|
+
return 'substrate';
|
|
186
|
+
if (/sharepoint/i.test(message))
|
|
187
|
+
return 'sharepoint';
|
|
188
|
+
if (/recap/i.test(message))
|
|
189
|
+
return 'recap';
|
|
190
|
+
return 'chat_service';
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* A capture failure as the actionable error a tool returns: which step failed,
|
|
194
|
+
* how long it waited, the stable error code (`token_<step>`), and as the hint
|
|
195
|
+
* the single next thing to do. `action` completes "Could not get a Teams
|
|
196
|
+
* access token to …".
|
|
197
|
+
*/
|
|
198
|
+
export function captureFailure(err, action, tokenHint) {
|
|
199
|
+
const token = err instanceof TokenCaptureError ? err.token : (tokenHint ?? tokenOf(err));
|
|
200
|
+
const t = TOKENS[token];
|
|
201
|
+
const code = classifyCaptureFailure(err);
|
|
202
|
+
const windowMs = err instanceof TokenCaptureError ? err.windowMs : DEFAULT_WINDOW_MS;
|
|
203
|
+
const waited = err instanceof TokenCaptureError ? `waited ${seconds(err.waitedMs)} s` : `waited up to ${seconds(windowMs)} s`;
|
|
204
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
205
|
+
const detail = bridgeDetail(message);
|
|
206
|
+
const expired = err instanceof TokenCaptureError && err.previousExpiresAt !== undefined
|
|
207
|
+
? ` The previous token expired at ${new Date(err.previousExpiresAt).toISOString()}.`
|
|
208
|
+
: '';
|
|
209
|
+
const wait = whileWaitingGuidance(token, windowMs);
|
|
210
|
+
const prime = token === 'chat_service' || token === 'substrate'
|
|
211
|
+
? ` Or run teams_token_status with wait: true${token === 'substrate' ? ' and token: "substrate"' : ''} (it waits up to 120 s), and act once it starts.`
|
|
212
|
+
: '';
|
|
213
|
+
const steps = {
|
|
214
|
+
bridge_not_approved: {
|
|
215
|
+
what: 'the ContextMint Bridge has not approved this server (or this capture) yet',
|
|
216
|
+
hint: 'Approve microsoft-teams-mcp in the ContextMint Bridge extension popup, then retry.',
|
|
217
|
+
},
|
|
218
|
+
bridge_unreachable: {
|
|
219
|
+
what: 'no browser with the ContextMint Bridge extension is connected',
|
|
220
|
+
hint: 'Open the browser that has the ContextMint Bridge extension (signed in to Teams) and check the extension is connected, then retry.',
|
|
221
|
+
},
|
|
222
|
+
no_tab: {
|
|
223
|
+
what: 'the bridge found no signed-in Teams tab',
|
|
224
|
+
hint: `Open teams.cloud.microsoft in the browser with the ContextMint Bridge and sign in. Then: ${wait}`,
|
|
225
|
+
},
|
|
226
|
+
no_request_seen: {
|
|
227
|
+
what: `${waited} and the Teams tab made no ${t.request} request in that time (the bridge cannot tell an idle tab from a missing one)`,
|
|
228
|
+
hint: wait + prime,
|
|
229
|
+
},
|
|
230
|
+
token_rejected: {
|
|
231
|
+
what: `a freshly captured ${t.name} was still refused`,
|
|
232
|
+
hint: `Reload the Teams tab and sign in again if it asks. Then: ${wait}`,
|
|
233
|
+
},
|
|
234
|
+
capture_failed: {
|
|
235
|
+
what: `the capture failed (${detail})`,
|
|
236
|
+
hint: wait,
|
|
237
|
+
},
|
|
238
|
+
};
|
|
239
|
+
const step = steps[code];
|
|
240
|
+
const detailNote = code === 'capture_failed' ? '' : ` Bridge said: ${detail}.`;
|
|
241
|
+
return new McpToolError(`Could not get a ${t.name} to ${action}: ${step.what}.${expired}${detailNote} (error code: ${captureErrorCode(code)})`, {
|
|
242
|
+
hint: step.hint,
|
|
243
|
+
...(code === 'token_rejected' ? { kind: 'credential_rejected' } : {}),
|
|
244
|
+
cause: err,
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* A token counts as held only with more than this left: inside it, the next
|
|
249
|
+
* call re-captures anyway (mcp-utils' `TOKEN_REFRESH_SKEW_MS`, 5 minutes).
|
|
250
|
+
*/
|
|
251
|
+
const HELD_MARGIN_MS = 5 * 60 * 1000;
|
|
252
|
+
/**
|
|
253
|
+
* Build a {@link TokenStatus} from what the client knows without capturing: the
|
|
254
|
+
* in-memory expiry, the disk cache's, or a directly supplied token's.
|
|
255
|
+
*/
|
|
256
|
+
export function tokenStatusOf(token, opts) {
|
|
257
|
+
const now = opts.now ?? Date.now();
|
|
258
|
+
const candidates = [];
|
|
259
|
+
if (opts.memoryExpiresAt !== null)
|
|
260
|
+
candidates.push({ at: opts.memoryExpiresAt, from: opts.direct ? 'TEAMS_ACCESS_TOKEN' : 'memory' });
|
|
261
|
+
if (opts.storedExpiresAt !== null)
|
|
262
|
+
candidates.push({ at: opts.storedExpiresAt, from: 'disk cache' });
|
|
263
|
+
const best = candidates.sort((a, b) => b.at - a.at)[0];
|
|
264
|
+
const held = best !== undefined && best.at - now > HELD_MARGIN_MS;
|
|
265
|
+
const last = outcomes.get(token);
|
|
266
|
+
return {
|
|
267
|
+
source: opts.source,
|
|
268
|
+
held,
|
|
269
|
+
from: held ? best.from : null,
|
|
270
|
+
expires_at: held ? new Date(best.at).toISOString() : null,
|
|
271
|
+
minutes_remaining: held ? Math.round((best.at - now) / 60_000) : null,
|
|
272
|
+
expired_at: !held && best !== undefined ? new Date(best.at).toISOString() : null,
|
|
273
|
+
last_capture: last === undefined
|
|
274
|
+
? null
|
|
275
|
+
: {
|
|
276
|
+
at: new Date(last.at).toISOString(),
|
|
277
|
+
ok: last.ok,
|
|
278
|
+
waited_seconds: Math.round(last.waitedMs / 1000),
|
|
279
|
+
window_seconds: Math.round(last.windowMs / 1000),
|
|
280
|
+
...(last.code !== undefined ? { code: captureErrorCode(last.code) } : {}),
|
|
281
|
+
},
|
|
282
|
+
};
|
|
283
|
+
}
|
package/dist/chatsvc.js
CHANGED
|
@@ -24,9 +24,13 @@
|
|
|
24
24
|
import { decodeJwtClaim, fetchBounded, errorKindOf, McpToolError, parseBoolEnv, readEnvVar, RequestTimeoutError, WriteOutcomeUnknownError, } from '@chrischall/mcp-utils';
|
|
25
25
|
import { createCapturedTokenManager } from '@chrischall/mcp-utils/session';
|
|
26
26
|
import { createTokenCache, reportCacheWriteFailure } from './token-cache.js';
|
|
27
|
+
import { teamsTabNudger } from './browser-open.js';
|
|
27
28
|
import { SELF_CHAT } from './model.js';
|
|
28
29
|
import { isAmsObjectId, transcriptUrl } from './transcript.js';
|
|
29
30
|
import { describeTransportFailure } from './network-error.js';
|
|
31
|
+
import { parsePresenceResponse, presenceUrl } from './presence.js';
|
|
32
|
+
import { captureWithFeedback, tokenStatusOf, whileWaitingGuidance } from './capture-feedback.js';
|
|
33
|
+
import { captureWindowMs } from './capture-window.js';
|
|
30
34
|
/**
|
|
31
35
|
* Load the bridge bootstrap lazily.
|
|
32
36
|
*
|
|
@@ -36,9 +40,9 @@ import { describeTransportFailure } from './network-error.js';
|
|
|
36
40
|
* `ERR_MODULE_NOT_FOUND` before the server could answer `initialize`. Deferring
|
|
37
41
|
* it means a user who supplies `TEAMS_ACCESS_TOKEN` never needs it installed.
|
|
38
42
|
*/
|
|
39
|
-
async function captureTokenLazily() {
|
|
43
|
+
async function captureTokenLazily(windowMs) {
|
|
40
44
|
const mod = await import('./auth-fetchproxy.js');
|
|
41
|
-
return mod.captureTokenViaFetchproxy();
|
|
45
|
+
return mod.captureTokenViaFetchproxy(undefined, windowMs);
|
|
42
46
|
}
|
|
43
47
|
/** The chat-service region this tenant was verified on. */
|
|
44
48
|
export const DEFAULT_REGION = 'amer';
|
|
@@ -55,6 +59,8 @@ export function chatServiceBase(env = process.env) {
|
|
|
55
59
|
}
|
|
56
60
|
/** Per-request deadline, covering the body read. */
|
|
57
61
|
const REQUEST_TIMEOUT_MS = 60_000;
|
|
62
|
+
/** A presence answer is a few hundred bytes per person; anything near this is not one. */
|
|
63
|
+
const PRESENCE_MAX_BYTES = 1024 * 1024;
|
|
58
64
|
/** Paging caps — a runaway `backwardLink` chain must not hold a tool call open. */
|
|
59
65
|
const MAX_CONVERSATION_PAGES = 10;
|
|
60
66
|
const MAX_MESSAGE_PAGES = 20;
|
|
@@ -124,12 +130,28 @@ export class ChatServiceClient {
|
|
|
124
130
|
#configError = null;
|
|
125
131
|
#env;
|
|
126
132
|
#capture;
|
|
133
|
+
/** A longer capture window for a deliberate prime (`ensureToken({ windowMs })`), while it runs. */
|
|
134
|
+
#windowOverride;
|
|
127
135
|
#fetchImpl;
|
|
128
136
|
#direct;
|
|
129
137
|
#tokens = null;
|
|
130
138
|
constructor(opts = {}) {
|
|
131
139
|
this.#env = opts.env ?? process.env;
|
|
132
|
-
|
|
140
|
+
const capture = opts.captureToken ?? captureTokenLazily;
|
|
141
|
+
const nudge = opts.nudge ?? (opts.captureToken === undefined ? (teamsTabNudger({ env: this.#env }) ?? undefined) : undefined);
|
|
142
|
+
// Every capture reports progress while it waits, fires the nudge, and fails
|
|
143
|
+
// with its step and how long it waited (`capture-feedback.ts`).
|
|
144
|
+
this.#capture = () => {
|
|
145
|
+
const windowMs = this.#windowOverride ?? captureWindowMs(this.#env);
|
|
146
|
+
const previous = this.#knownExpiry();
|
|
147
|
+
return captureWithFeedback({
|
|
148
|
+
token: 'chat_service',
|
|
149
|
+
windowMs,
|
|
150
|
+
capture: () => capture(windowMs),
|
|
151
|
+
...(nudge !== undefined ? { nudge } : {}),
|
|
152
|
+
...(previous !== null ? { previousExpiresAt: previous } : {}),
|
|
153
|
+
});
|
|
154
|
+
};
|
|
133
155
|
// A receiver-safe wrapper, never the bare global: older undici throws
|
|
134
156
|
// `Illegal invocation` when `fetch` is called with a non-global receiver.
|
|
135
157
|
this.#fetchImpl = opts.fetchImpl ?? ((input, init) => fetch(input, init));
|
|
@@ -165,10 +187,62 @@ export class ChatServiceClient {
|
|
|
165
187
|
* Hold a token — the cached one, or a fresh capture — without calling the
|
|
166
188
|
* API. The healthcheck resolves the credential with this before probing, so
|
|
167
189
|
* a capture failure is reported as one rather than as a failed request.
|
|
190
|
+
* `windowMs` lengthens the capture window for a deliberate prime
|
|
191
|
+
* (`teams_token_status` with wait), for this call only.
|
|
168
192
|
*/
|
|
169
|
-
async ensureToken() {
|
|
193
|
+
async ensureToken(opts = {}) {
|
|
170
194
|
this.#requireConfigured();
|
|
171
|
-
|
|
195
|
+
this.#windowOverride = opts.windowMs;
|
|
196
|
+
try {
|
|
197
|
+
await this.#tokenManager().getAccessToken();
|
|
198
|
+
}
|
|
199
|
+
finally {
|
|
200
|
+
this.#windowOverride = undefined;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Whether a token is held and until when, WITHOUT capturing: this process's
|
|
205
|
+
* token, else the disk cache an earlier run left, else a TEAMS_ACCESS_TOKEN's
|
|
206
|
+
* own expiry; and the last capture this process ran. Never the token itself.
|
|
207
|
+
*/
|
|
208
|
+
tokenStatus() {
|
|
209
|
+
if (this.#direct !== undefined) {
|
|
210
|
+
let exp = null;
|
|
211
|
+
try {
|
|
212
|
+
const claim = decodeJwtClaim(this.#direct, 'exp');
|
|
213
|
+
if (typeof claim === 'number' && Number.isFinite(claim))
|
|
214
|
+
exp = claim * 1000;
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
exp = null;
|
|
218
|
+
}
|
|
219
|
+
return tokenStatusOf('chat_service', { source: this.tokenSource, memoryExpiresAt: exp, storedExpiresAt: null, direct: true });
|
|
220
|
+
}
|
|
221
|
+
return tokenStatusOf('chat_service', {
|
|
222
|
+
source: this.tokenSource,
|
|
223
|
+
memoryExpiresAt: this.tokenExpiresAt(),
|
|
224
|
+
storedExpiresAt: this.#storedExpiry(),
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
/** The disk cache's expiry (epoch ms), or `null` when there is no cache or nothing in it. Never throws. */
|
|
228
|
+
#storedExpiry() {
|
|
229
|
+
if (this.#direct !== undefined)
|
|
230
|
+
return null;
|
|
231
|
+
try {
|
|
232
|
+
const at = createTokenCache(this.#env)?.load()?.expiresAt;
|
|
233
|
+
return typeof at === 'number' && Number.isFinite(at) && at > 0 ? at : null;
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
/** The latest expiry known for a token this client held or cached, for a capture error. */
|
|
240
|
+
#knownExpiry() {
|
|
241
|
+
const memory = this.tokenExpiresAt();
|
|
242
|
+
const stored = this.#storedExpiry();
|
|
243
|
+
if (memory === null)
|
|
244
|
+
return stored;
|
|
245
|
+
return stored === null ? memory : Math.max(memory, stored);
|
|
172
246
|
}
|
|
173
247
|
/**
|
|
174
248
|
* The signed-in user's MRI, `8:orgid:<oid>`, from the token's `oid` claim.
|
|
@@ -480,6 +554,57 @@ export class ChatServiceClient {
|
|
|
480
554
|
const { status } = await this.#send(url, 'text', undefined, { method, body, hint: THREAD_OUTCOME_HINT });
|
|
481
555
|
this.#checkWriteStatus(method, status, THREAD_OUTCOME_HINT);
|
|
482
556
|
}
|
|
557
|
+
/**
|
|
558
|
+
* The presence of `mris` (`presence.ts`): availability, last seen, time
|
|
559
|
+
* zone. Sent with the chat-service token to the presence service behind the
|
|
560
|
+
* same New Teams host, so the bearer goes nowhere it was not captured from.
|
|
561
|
+
*
|
|
562
|
+
* Deliberately NOT through `withAuth`: a 401 here says the presence service
|
|
563
|
+
* does not take this token, not that the token is stale, so it must never
|
|
564
|
+
* trigger a re-capture (which would hold the call for a capture window and
|
|
565
|
+
* churn a chat token that works). It is reported, and the caller carries on.
|
|
566
|
+
*/
|
|
567
|
+
async getPresence(mris) {
|
|
568
|
+
this.#requireConfigured();
|
|
569
|
+
if (mris.length === 0)
|
|
570
|
+
return [];
|
|
571
|
+
const url = presenceUrl(this.#env);
|
|
572
|
+
const token = await this.#tokenManager().getAccessToken();
|
|
573
|
+
let r;
|
|
574
|
+
try {
|
|
575
|
+
r = await fetchBounded(url, {
|
|
576
|
+
method: 'POST',
|
|
577
|
+
headers: {
|
|
578
|
+
authorization: `Bearer ${token}`,
|
|
579
|
+
behavioroverride: 'redirectAs404',
|
|
580
|
+
accept: 'application/json',
|
|
581
|
+
'content-type': 'application/json',
|
|
582
|
+
},
|
|
583
|
+
body: JSON.stringify(mris.map((mri) => ({ mri }))),
|
|
584
|
+
redirect: 'error',
|
|
585
|
+
}, { read: 'text', maxBytes: PRESENCE_MAX_BYTES, service: 'Teams presence', timeoutMs: REQUEST_TIMEOUT_MS, fetchImpl: this.#fetchImpl });
|
|
586
|
+
}
|
|
587
|
+
catch (e) {
|
|
588
|
+
throw describeTransportFailure(e, url, 'Teams presence') ?? e;
|
|
589
|
+
}
|
|
590
|
+
const status = r.res.status;
|
|
591
|
+
if (status < 200 || status >= 300) {
|
|
592
|
+
const refused = status === 401 || status === 403;
|
|
593
|
+
throw new McpToolError(`Teams presence returned HTTP ${status}.`, {
|
|
594
|
+
status,
|
|
595
|
+
kind: refused ? 'credential_rejected' : 'http',
|
|
596
|
+
hint: refused
|
|
597
|
+
? 'The presence service did not accept the chat-service token; last seen and local time are unavailable.'
|
|
598
|
+
: 'Presence is optional; retry later for last seen and local time.',
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
try {
|
|
602
|
+
return parsePresenceResponse(JSON.parse(r.body), Date.now());
|
|
603
|
+
}
|
|
604
|
+
catch {
|
|
605
|
+
throw new McpToolError('Teams presence returned a response that is not JSON.', { status, kind: 'http' });
|
|
606
|
+
}
|
|
607
|
+
}
|
|
483
608
|
/**
|
|
484
609
|
* Download an inline image (`<img src>` in a message body).
|
|
485
610
|
*
|
|
@@ -680,8 +805,8 @@ export class ChatServiceClient {
|
|
|
680
805
|
throw new McpToolError('Teams rejected the access token (401) even after a fresh capture.', {
|
|
681
806
|
status,
|
|
682
807
|
kind: 'credential_rejected',
|
|
683
|
-
hint: '
|
|
684
|
-
'
|
|
808
|
+
hint: 'Reload your teams.cloud.microsoft tab (sign in again if it asks). Then: ' +
|
|
809
|
+
whileWaitingGuidance('chat_service', captureWindowMs(this.#env)),
|
|
685
810
|
});
|
|
686
811
|
}
|
|
687
812
|
if (status === 429) {
|
package/dist/compose.js
CHANGED
|
@@ -202,6 +202,14 @@ function placeMentions(text, mentions) {
|
|
|
202
202
|
}
|
|
203
203
|
return placed.sort((a, b) => a.start - b.start);
|
|
204
204
|
}
|
|
205
|
+
/**
|
|
206
|
+
* Where each mention will sit in `text` — `[start, end)` — exactly as
|
|
207
|
+
* {@link renderMessageHtml} places them (so a preview can tell which "@name"s
|
|
208
|
+
* no mention covers). Throws as rendering does when one is not in the text.
|
|
209
|
+
*/
|
|
210
|
+
export function mentionRanges(text, mentions) {
|
|
211
|
+
return placeMentions(text, mentions).map((p) => [p.start, p.end]);
|
|
212
|
+
}
|
|
205
213
|
const mentionSpan = (n, shown) => `<span itemscope itemtype="http://schema.skype.com/Mention" itemid="${n}">${escapeHtml(shown)}</span>`;
|
|
206
214
|
/*
|
|
207
215
|
* Private-use placeholders for a mention (MENTION_OPEN n MENTION_CLOSE),
|
|
@@ -330,7 +338,7 @@ export function buildSendBody(i) {
|
|
|
330
338
|
links: '[]',
|
|
331
339
|
mentions: i.mentions ?? '[]',
|
|
332
340
|
onbehalfof: null,
|
|
333
|
-
files: '[]',
|
|
341
|
+
files: i.files ?? '[]',
|
|
334
342
|
policyViolation: null,
|
|
335
343
|
formatVariant: 'TEAMS',
|
|
336
344
|
...(i.qtdMsgs !== undefined ? { qtdMsgs: i.qtdMsgs } : {}),
|