@chrischall/microsoft-teams-mcp 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +4 -4
- package/.claude-plugin/plugin.json +2 -2
- package/README.md +577 -93
- package/dist/auth-fetchproxy.js +138 -0
- package/dist/bundle.js +44324 -37483
- package/dist/capture-window.js +41 -0
- package/dist/chatsvc.js +580 -0
- package/dist/compose.js +241 -0
- package/dist/deps.js +1 -0
- package/dist/index.js +35 -6
- package/dist/model.js +603 -0
- package/dist/sharepoint-auth.js +162 -0
- package/dist/sharepoint-token-cache.js +105 -0
- package/dist/sharepoint.js +289 -0
- package/dist/substrate-auth.js +104 -0
- package/dist/substrate-token-cache.js +64 -0
- package/dist/substrate.js +319 -0
- package/dist/token-cache.js +67 -0
- package/dist/tools/activity.js +155 -19
- package/dist/tools/attachment.js +174 -0
- package/dist/tools/changes.js +241 -0
- package/dist/tools/channels.js +62 -44
- package/dist/tools/chat-search.js +65 -0
- package/dist/tools/chat.js +121 -41
- package/dist/tools/confirm.js +188 -0
- package/dist/tools/conversation.js +394 -30
- package/dist/tools/cursor.js +43 -0
- package/dist/tools/errors.js +18 -17
- package/dist/tools/format.js +135 -0
- package/dist/tools/healthcheck.js +91 -27
- package/dist/tools/limit.js +43 -12
- package/dist/tools/listing.js +180 -0
- package/dist/tools/markread.js +246 -0
- package/dist/tools/react.js +217 -0
- package/dist/tools/roots.js +73 -0
- package/dist/tools/search.js +426 -0
- package/dist/tools/send.js +309 -0
- package/dist/tools/timezone.js +38 -0
- package/dist/tools/titles.js +180 -0
- package/dist/tools/unread.js +263 -0
- package/dist/tools/untrusted.js +16 -1
- package/dist/version.js +1 -1
- package/mint.yaml +75 -20
- package/package.json +1 -2
- package/server.json +87 -3
- package/skills/teams-fpx/SKILL.md +111 -92
- package/skills/teams-fpx/references/chatsvc-recipes.md +151 -0
- package/skills/teams-fpx/references/teams-env.sh +146 -0
- package/dist/client.js +0 -290
- package/skills/teams-fpx/references/dom-list-recipes.md +0 -81
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How long a token capture may wait, and the bridge deadline that has to
|
|
3
|
+
* outlast it.
|
|
4
|
+
*
|
|
5
|
+
* Kept free of any bridge import, so it can be read and tested without
|
|
6
|
+
* loading `auth-fetchproxy.ts` (the one transport this MCP builds) and its
|
|
7
|
+
* optional `@fetchproxy/server` peer. Both are read at CALL time, not module
|
|
8
|
+
* load, so `TEAMS_CAPTURE_TIMEOUT` set by the host's env (or a `.env` loaded
|
|
9
|
+
* after import) is honoured.
|
|
10
|
+
*/
|
|
11
|
+
import { readTtlMsEnv } from '@chrischall/mcp-utils';
|
|
12
|
+
/**
|
|
13
|
+
* The capture window when `TEAMS_CAPTURE_TIMEOUT` is unset, unparseable or 0.
|
|
14
|
+
*
|
|
15
|
+
* The window IS the mechanism: capture resolves on the NEXT matching request,
|
|
16
|
+
* so nothing the page did before the listener came up counts. 30s is long
|
|
17
|
+
* enough for the user to click into a chat, short enough that an idle tab does
|
|
18
|
+
* not hang a tool call for minutes.
|
|
19
|
+
*/
|
|
20
|
+
export const DEFAULT_CAPTURE_WINDOW_MS = 30_000;
|
|
21
|
+
/** How far the bridge deadline outlasts the capture window (one round trip, generously). */
|
|
22
|
+
export const DEADLINE_MARGIN_MS = 15_000;
|
|
23
|
+
/** `@fetchproxy/server`'s own default deadline; never go below it. */
|
|
24
|
+
const MIN_DEADLINE_MS = 30_000;
|
|
25
|
+
/** `TEAMS_CAPTURE_TIMEOUT` (seconds) as milliseconds. */
|
|
26
|
+
export function captureWindowMs(env = process.env) {
|
|
27
|
+
const ms = readTtlMsEnv('TEAMS_CAPTURE_TIMEOUT', DEFAULT_CAPTURE_WINDOW_MS, { env });
|
|
28
|
+
return ms > 0 ? ms : DEFAULT_CAPTURE_WINDOW_MS;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The transport-wide deadline (`fetchTimeoutMs`) for a capture window.
|
|
32
|
+
*
|
|
33
|
+
* A verb's own `timeoutMs` is cut off by `fetchTimeoutMs` on older bridges, so
|
|
34
|
+
* a window raised past the deadline fails early at the deadline's number —
|
|
35
|
+
* which reads as a timeout nobody configured. Deriving it means the two cannot
|
|
36
|
+
* disagree, and the extension's own "no request arrived" answer is the one the
|
|
37
|
+
* caller sees.
|
|
38
|
+
*/
|
|
39
|
+
export function bridgeDeadlineMs(windowMs) {
|
|
40
|
+
return Math.max(windowMs + DEADLINE_MARGIN_MS, MIN_DEADLINE_MS);
|
|
41
|
+
}
|
package/dist/chatsvc.js
ADDED
|
@@ -0,0 +1,580 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Teams chat-service REST client.
|
|
3
|
+
*
|
|
4
|
+
* Auth is a bearer token whose only source is the user's browser (see
|
|
5
|
+
* `auth-fetchproxy.ts`), or a `TEAMS_ACCESS_TOKEN` supplied directly. Once
|
|
6
|
+
* held, every request is a plain Node `fetch` — the bridge is never on the hot
|
|
7
|
+
* path.
|
|
8
|
+
*
|
|
9
|
+
* Reads are `listConversations`, `getMessages` (which also reads the Activity
|
|
10
|
+
* feed, conversation `48:notifications`), `getMessage` and
|
|
11
|
+
* `fetchImage`; the writes are `sendMessage`, `setReaction`,
|
|
12
|
+
* `removeReaction` and `setConsumptionHorizon`, which only the confirm-gated
|
|
13
|
+
* `teams_send_message`, `teams_react` and `teams_mark_read` (and the read
|
|
14
|
+
* tools' opt-in `mark_read`) call. A read never writes the read marker
|
|
15
|
+
* (`consumptionhorizon`) on its own, so reading a chat through this MCP leaves
|
|
16
|
+
* the user's unread badges alone unless they ask for it to be marked read.
|
|
17
|
+
*
|
|
18
|
+
* Verified live 2026-10-10 against a real Teams tenant — see the "Verified
|
|
19
|
+
* live facts" section of `docs/plans/2026-10-10-chatsvc-api.md` for the
|
|
20
|
+
* response shapes the types below describe.
|
|
21
|
+
*/
|
|
22
|
+
import { decodeJwtClaim, decodeJwtExp, fetchBounded, McpToolError, parseBoolEnv, readEnvVar, RequestTimeoutError, WriteOutcomeUnknownError, } from '@chrischall/mcp-utils';
|
|
23
|
+
import { TokenManager } from '@chrischall/mcp-utils/session';
|
|
24
|
+
import { createTokenCache, reportCacheWriteFailure } from './token-cache.js';
|
|
25
|
+
import { SELF_CHAT } from './model.js';
|
|
26
|
+
/**
|
|
27
|
+
* Load the bridge bootstrap lazily.
|
|
28
|
+
*
|
|
29
|
+
* `auth-fetchproxy.ts` pulls in `@chrischall/mcp-utils/fetchproxy`, which
|
|
30
|
+
* imports the OPTIONAL `@fetchproxy/server` peer. The `.mcpb` bundle ships no
|
|
31
|
+
* `node_modules`, so a top-level import here would throw
|
|
32
|
+
* `ERR_MODULE_NOT_FOUND` before the server could answer `initialize`. Deferring
|
|
33
|
+
* it means a user who supplies `TEAMS_ACCESS_TOKEN` never needs it installed.
|
|
34
|
+
*/
|
|
35
|
+
async function captureTokenLazily() {
|
|
36
|
+
const mod = await import('./auth-fetchproxy.js');
|
|
37
|
+
return mod.captureTokenViaFetchproxy();
|
|
38
|
+
}
|
|
39
|
+
/** The chat-service region this tenant was verified on. */
|
|
40
|
+
export const DEFAULT_REGION = 'amer';
|
|
41
|
+
/**
|
|
42
|
+
* The chat-service base URL: `TEAMS_CHATSVC_BASE` verbatim when set, else the
|
|
43
|
+
* New Teams proxy path for `TEAMS_CHATSVC_REGION` (default `amer`).
|
|
44
|
+
*/
|
|
45
|
+
export function chatServiceBase(env = process.env) {
|
|
46
|
+
const override = readEnvVar('TEAMS_CHATSVC_BASE', { env });
|
|
47
|
+
if (override !== undefined)
|
|
48
|
+
return override.replace(/\/+$/, '');
|
|
49
|
+
const region = readEnvVar('TEAMS_CHATSVC_REGION', { env }) ?? DEFAULT_REGION;
|
|
50
|
+
return `https://teams.cloud.microsoft/api/chatsvc/${encodeURIComponent(region)}/v1`;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Fallback lifetime for a token whose `exp` we cannot read.
|
|
54
|
+
*
|
|
55
|
+
* Real tokens are JWTs carrying `exp` (~23.5h out), so this is only reached
|
|
56
|
+
* for a hand-supplied opaque `TEAMS_ACCESS_TOKEN`. Deliberately short: being
|
|
57
|
+
* wrong in this direction costs one extra 401-and-replay.
|
|
58
|
+
*/
|
|
59
|
+
const UNKNOWN_TOKEN_TTL_MS = 10 * 60 * 1000;
|
|
60
|
+
/**
|
|
61
|
+
* Sentinel standing in for a refresh token this flow does not have.
|
|
62
|
+
*
|
|
63
|
+
* The token comes from MSAL's hidden-iframe flow; there is no refresh grant we
|
|
64
|
+
* can drive, so "refreshing" means capturing a new one. `TokenManager` only
|
|
65
|
+
* calls `refresh` when a refresh token is present, hence the sentinel.
|
|
66
|
+
*/
|
|
67
|
+
const RECAPTURE_SENTINEL = 'fetchproxy:recapture';
|
|
68
|
+
/** Per-request deadline, covering the body read. */
|
|
69
|
+
const REQUEST_TIMEOUT_MS = 60_000;
|
|
70
|
+
/** Paging caps — a runaway `backwardLink` chain must not hold a tool call open. */
|
|
71
|
+
const MAX_CONVERSATION_PAGES = 10;
|
|
72
|
+
const MAX_MESSAGE_PAGES = 20;
|
|
73
|
+
/** Messages per `getMessages` request unless the caller asks for fewer. */
|
|
74
|
+
const DEFAULT_MESSAGE_PAGE_SIZE = 200;
|
|
75
|
+
/** Largest inline image we will buffer (they measured 8–18 KB live). */
|
|
76
|
+
const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
|
|
77
|
+
/**
|
|
78
|
+
* Inline images live on Skype's AMS object store (`us-api.asm.skype.com`, the
|
|
79
|
+
* host varies by region). The bearer is sent ONLY to hosts under this suffix.
|
|
80
|
+
*/
|
|
81
|
+
const IMAGE_HOST_SUFFIX = '.asm.skype.com';
|
|
82
|
+
/**
|
|
83
|
+
* A write that failed after it may have reached Teams. A timeout or a
|
|
84
|
+
* transport failure (dropped connection, broken body, the caller cancelling)
|
|
85
|
+
* leaves the outcome unknown; an `McpToolError` raised before anything was
|
|
86
|
+
* sent (an oversized body cap, a bad URL) is a real failure and passes through.
|
|
87
|
+
*/
|
|
88
|
+
function outcomeUnknown(method, e, hint) {
|
|
89
|
+
if (e instanceof RequestTimeoutError) {
|
|
90
|
+
return new WriteOutcomeUnknownError('Teams', method, { timeoutMs: e.timeoutMs, cause: e, hint });
|
|
91
|
+
}
|
|
92
|
+
if (e instanceof McpToolError)
|
|
93
|
+
return e;
|
|
94
|
+
return new WriteOutcomeUnknownError('Teams', method, { cause: e, hint });
|
|
95
|
+
}
|
|
96
|
+
const SEND_OUTCOME_HINT = 'The message may already have been posted — check the conversation (teams_read_conversation) before retrying; do not resend blindly.';
|
|
97
|
+
const REACTION_OUTCOME_HINT = 'The reaction change may already have been applied — check the message (teams_read_conversation) before retrying.';
|
|
98
|
+
const HORIZON_OUTCOME_HINT = 'The read marker may already have moved — check the conversation (teams_read_conversation) before retrying; ' +
|
|
99
|
+
'moving it again to the same message is harmless.';
|
|
100
|
+
/**
|
|
101
|
+
* The HTTP status behind a {@link WriteOutcomeUnknownError} that Teams
|
|
102
|
+
* answered with a 5xx, or `undefined` when it timed out or the connection
|
|
103
|
+
* dropped instead.
|
|
104
|
+
*/
|
|
105
|
+
export function outcomeUnknownStatus(e) {
|
|
106
|
+
const status = e.cause?.status;
|
|
107
|
+
return typeof status === 'number' ? status : undefined;
|
|
108
|
+
}
|
|
109
|
+
function toBearerTokens(accessToken) {
|
|
110
|
+
let expiresAt;
|
|
111
|
+
try {
|
|
112
|
+
// decodeJwtExp returns seconds; a non-JWT throws.
|
|
113
|
+
expiresAt = decodeJwtExp(accessToken) * 1000;
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
expiresAt = Date.now() + UNKNOWN_TOKEN_TTL_MS;
|
|
117
|
+
}
|
|
118
|
+
return { accessToken, refreshToken: RECAPTURE_SENTINEL, expiresAt };
|
|
119
|
+
}
|
|
120
|
+
export class ChatServiceClient {
|
|
121
|
+
#baseUrl;
|
|
122
|
+
/**
|
|
123
|
+
* Deferred configuration error. The constructor never throws, so the server
|
|
124
|
+
* still boots (and answers `tools/list`) with no credential present.
|
|
125
|
+
*/
|
|
126
|
+
#configError = null;
|
|
127
|
+
#env;
|
|
128
|
+
#capture;
|
|
129
|
+
#fetchImpl;
|
|
130
|
+
#direct;
|
|
131
|
+
#tokens = null;
|
|
132
|
+
constructor(opts = {}) {
|
|
133
|
+
this.#env = opts.env ?? process.env;
|
|
134
|
+
this.#capture = opts.captureToken ?? captureTokenLazily;
|
|
135
|
+
// A receiver-safe wrapper, never the bare global: older undici throws
|
|
136
|
+
// `Illegal invocation` when `fetch` is called with a non-global receiver.
|
|
137
|
+
this.#fetchImpl = opts.fetchImpl ?? ((input, init) => fetch(input, init));
|
|
138
|
+
this.#baseUrl = chatServiceBase(this.#env);
|
|
139
|
+
this.#direct = readEnvVar('TEAMS_ACCESS_TOKEN', { env: this.#env });
|
|
140
|
+
const bridgeOff = parseBoolEnv('TEAMS_DISABLE_FETCHPROXY', { env: this.#env });
|
|
141
|
+
if (this.#direct === undefined && bridgeOff) {
|
|
142
|
+
this.#configError = new McpToolError('No Teams credential is configured.', {
|
|
143
|
+
kind: 'no_credential',
|
|
144
|
+
hint: 'Set TEAMS_ACCESS_TOKEN, or unset TEAMS_DISABLE_FETCHPROXY so the token can ' +
|
|
145
|
+
'be captured from a signed-in Teams browser tab.',
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
/** Non-secret description of where the credential comes from. */
|
|
150
|
+
get tokenSource() {
|
|
151
|
+
return this.#direct !== undefined ? 'TEAMS_ACCESS_TOKEN' : 'browser capture';
|
|
152
|
+
}
|
|
153
|
+
/** The API base this client talks to. Non-secret; safe for healthcheck output. */
|
|
154
|
+
get apiBase() {
|
|
155
|
+
return this.#baseUrl;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Epoch ms at which the current token expires, or `null` if none is held —
|
|
159
|
+
* including after a capture that failed, when the token manager exists but
|
|
160
|
+
* holds nothing (it reports that as expiry 0, i.e. 1970).
|
|
161
|
+
*/
|
|
162
|
+
tokenExpiresAt() {
|
|
163
|
+
const at = this.#tokens?.getExpiresAt();
|
|
164
|
+
return at !== undefined && Number.isFinite(at) && at > 0 ? at : null;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Hold a token — the cached one, or a fresh capture — without calling the
|
|
168
|
+
* API. The healthcheck resolves the credential with this before probing, so
|
|
169
|
+
* a capture failure is reported as one rather than as a failed request.
|
|
170
|
+
*/
|
|
171
|
+
async ensureToken() {
|
|
172
|
+
this.#requireConfigured();
|
|
173
|
+
await this.#tokenManager().getAccessToken();
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* The signed-in user's MRI, `8:orgid:<oid>`, from the token's `oid` claim.
|
|
177
|
+
* Needed to tell the user's own messages from everyone else's.
|
|
178
|
+
*/
|
|
179
|
+
async meMri() {
|
|
180
|
+
this.#requireConfigured();
|
|
181
|
+
const token = await this.#tokenManager().getAccessToken();
|
|
182
|
+
let oid;
|
|
183
|
+
try {
|
|
184
|
+
oid = decodeJwtClaim(token, 'oid');
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
oid = undefined;
|
|
188
|
+
}
|
|
189
|
+
if (typeof oid !== 'string' || oid === '') {
|
|
190
|
+
throw new McpToolError('The Teams token does not identify the signed-in user (no oid claim).', {
|
|
191
|
+
hint: 'Capture a fresh token from a signed-in teams.cloud.microsoft tab, or supply a ' +
|
|
192
|
+
'TEAMS_ACCESS_TOKEN that is the chat-service JWT itself.',
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
return `8:orgid:${oid}`;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* The signed-in user's display name, from the token's `name` claim — what a
|
|
199
|
+
* sent message carries as `imdisplayname`. `''` when the token has none.
|
|
200
|
+
*/
|
|
201
|
+
async meDisplayName() {
|
|
202
|
+
this.#requireConfigured();
|
|
203
|
+
const token = await this.#tokenManager().getAccessToken();
|
|
204
|
+
try {
|
|
205
|
+
const name = decodeJwtClaim(token, 'name');
|
|
206
|
+
return typeof name === 'string' ? name : '';
|
|
207
|
+
}
|
|
208
|
+
catch {
|
|
209
|
+
return '';
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Every conversation the user is in, across up to 10 pages, minus the
|
|
214
|
+
* `48:*` system threads (calendar, notifications, …) which are not chats —
|
|
215
|
+
* except `48:notes`, the user's self-chat, which is.
|
|
216
|
+
*/
|
|
217
|
+
async listConversations() {
|
|
218
|
+
this.#requireConfigured();
|
|
219
|
+
const out = [];
|
|
220
|
+
let url = `${this.#baseUrl}/users/ME/conversations?view=msnp24Equivalent&pageSize=200`;
|
|
221
|
+
for (let page = 0; url !== undefined && page < MAX_CONVERSATION_PAGES; page++) {
|
|
222
|
+
const body = await this.#getJson(url);
|
|
223
|
+
const convs = body.conversations ?? [];
|
|
224
|
+
if (convs.length === 0)
|
|
225
|
+
break;
|
|
226
|
+
for (const c of convs) {
|
|
227
|
+
if (typeof c?.id === 'string' && (!c.id.startsWith('48:') || c.id === SELF_CHAT))
|
|
228
|
+
out.push(c);
|
|
229
|
+
}
|
|
230
|
+
url = this.#nextLink(body);
|
|
231
|
+
}
|
|
232
|
+
return out;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* A conversation's messages, newest first, paging back until `stopAt`
|
|
236
|
+
* accepts a message, `max` are collected, the pages run out, or 20 pages
|
|
237
|
+
* have been read.
|
|
238
|
+
*/
|
|
239
|
+
async getMessages(id, opts) {
|
|
240
|
+
this.#requireConfigured();
|
|
241
|
+
const out = [];
|
|
242
|
+
if (!(opts.max > 0))
|
|
243
|
+
return out;
|
|
244
|
+
let url = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(id)}/messages` +
|
|
245
|
+
`?view=msnp24Equivalent|supportsMessageProperties&pageSize=${opts.pageSize ?? DEFAULT_MESSAGE_PAGE_SIZE}&startTime=1`;
|
|
246
|
+
for (let page = 0; url !== undefined; page++) {
|
|
247
|
+
if (page >= MAX_MESSAGE_PAGES) {
|
|
248
|
+
opts.onCapped?.();
|
|
249
|
+
break;
|
|
250
|
+
}
|
|
251
|
+
const body = await this.#getJson(url);
|
|
252
|
+
const msgs = body.messages ?? [];
|
|
253
|
+
if (msgs.length === 0)
|
|
254
|
+
break;
|
|
255
|
+
// A page is newest first but not strictly ordered (seen live
|
|
256
|
+
// 2026-10-10), so the page `stopAt` fires in is finished — skipping
|
|
257
|
+
// each message it rejects — and only the NEXT page is not fetched.
|
|
258
|
+
let stopped = false;
|
|
259
|
+
for (const m of msgs) {
|
|
260
|
+
if (opts.stopAt?.(m)) {
|
|
261
|
+
stopped = true;
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
out.push(m);
|
|
265
|
+
if (out.length >= opts.max) {
|
|
266
|
+
opts.onCapped?.();
|
|
267
|
+
return out;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
if (stopped)
|
|
271
|
+
return out;
|
|
272
|
+
url = this.#nextLink(body);
|
|
273
|
+
}
|
|
274
|
+
return out;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* One message by id, or `undefined` when the service answers 404. Used to
|
|
278
|
+
* quote a message (its sender and text go into the quote) and to fill in a
|
|
279
|
+
* channel thread's root post when it is older than a read's window — a
|
|
280
|
+
* channel root fetched by its id answers like any message (verified live
|
|
281
|
+
* 2026-10-12). An id the channel does not hold was answered 403, not 404,
|
|
282
|
+
* live, so that surfaces as an error.
|
|
283
|
+
*/
|
|
284
|
+
async getMessage(conversationId, messageId) {
|
|
285
|
+
this.#requireConfigured();
|
|
286
|
+
const url = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(conversationId)}` +
|
|
287
|
+
`/messages/${encodeURIComponent(messageId)}`;
|
|
288
|
+
const { status, body } = await this.#send(url, 'text');
|
|
289
|
+
if (status === 404)
|
|
290
|
+
return undefined;
|
|
291
|
+
return this.#parseJson(status, body);
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Post a message (the body `compose.ts` builds). `conversationId` is the
|
|
295
|
+
* chat or channel — or, for a threaded channel reply, `<channelId>;messageid=<rootId>`,
|
|
296
|
+
* encoded as one path segment. Resolves the new message's id from the
|
|
297
|
+
* `Location` header when the service sends one.
|
|
298
|
+
*
|
|
299
|
+
* Not idempotent, so a request that was SENT but got no usable answer (a
|
|
300
|
+
* timeout, a dropped connection, a 5xx from a gateway or a failing backend)
|
|
301
|
+
* is a `WriteOutcomeUnknownError` — the post may already be in the chat,
|
|
302
|
+
* and a blind retry would post it twice. A 4xx is a refusal and stays a
|
|
303
|
+
* plain error. A 401 is still replayed once after a re-capture: Teams
|
|
304
|
+
* refused that request, so nothing was posted.
|
|
305
|
+
*/
|
|
306
|
+
async sendMessage(conversationId, body) {
|
|
307
|
+
this.#requireConfigured();
|
|
308
|
+
const url = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(conversationId)}/messages`;
|
|
309
|
+
const { status, headers } = await this.#send(url, 'text', undefined, { method: 'POST', body, hint: SEND_OUTCOME_HINT });
|
|
310
|
+
this.#checkWriteStatus('POST', status, SEND_OUTCOME_HINT);
|
|
311
|
+
const id = /\/messages\/([^/?#]+)\/?(?:[?#].*)?$/.exec(headers.get('location') ?? '')?.[1];
|
|
312
|
+
return id !== undefined ? { id: decodeURIComponent(id) } : {};
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* React to a message: `PUT …/messages/{id}/properties?name=emotions` with
|
|
316
|
+
* `{ emotions: { key, value: <epoch ms> } }` (captured live). Only the
|
|
317
|
+
* message's `emotions` property is written — never the user's
|
|
318
|
+
* `recentReactions` preference, which Teams updates as a UI nicety.
|
|
319
|
+
*
|
|
320
|
+
* A timeout, a dropped connection or a 5xx after the request was sent is a
|
|
321
|
+
* `WriteOutcomeUnknownError`, as for a post: the change may have landed.
|
|
322
|
+
* Repeating it is harmless (the same key twice is still one reaction), but
|
|
323
|
+
* the tool reads the message back rather than reporting a plain failure for
|
|
324
|
+
* a change that may well be visible already.
|
|
325
|
+
*/
|
|
326
|
+
async setReaction(conversationId, messageId, key, at = Date.now()) {
|
|
327
|
+
await this.#writeEmotions('PUT', conversationId, messageId, { key, value: at });
|
|
328
|
+
}
|
|
329
|
+
/** Withdraw the user's reaction: `DELETE` on the same property (unverified live — see the plan). */
|
|
330
|
+
async removeReaction(conversationId, messageId, key) {
|
|
331
|
+
await this.#writeEmotions('DELETE', conversationId, messageId, { key });
|
|
332
|
+
}
|
|
333
|
+
async #writeEmotions(method, conversationId, messageId, emotions) {
|
|
334
|
+
this.#requireConfigured();
|
|
335
|
+
const url = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(conversationId)}` +
|
|
336
|
+
`/messages/${encodeURIComponent(messageId)}/properties?name=emotions`;
|
|
337
|
+
const { status } = await this.#send(url, 'text', undefined, { method, body: { emotions }, hint: REACTION_OUTCOME_HINT });
|
|
338
|
+
this.#checkWriteStatus(method, status, REACTION_OUTCOME_HINT);
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Move the user's read marker in a conversation to `messageId`:
|
|
342
|
+
* `PUT …/conversations/{id}/properties?name=consumptionhorizon` with
|
|
343
|
+
* `{ consumptionhorizon: "<id>;<client ms>;<id>" }` — the shape `readHorizon`
|
|
344
|
+
* parses, its first segment the message's arrival ms (which is its id).
|
|
345
|
+
* Teams clears the unread badge for everything up to it.
|
|
346
|
+
*
|
|
347
|
+
* Verified live 2026-10-12 on `48:notes`: 200, and the listing then carries
|
|
348
|
+
* the new horizon. A move BACKWARDS is also answered 200 but ignored, so a
|
|
349
|
+
* 200 does not prove the marker moved; never sending one is the caller's
|
|
350
|
+
* rule (`teams_mark_read`), which reports it as a no-op instead. A lost
|
|
351
|
+
* answer is a `WriteOutcomeUnknownError`, as for a reaction.
|
|
352
|
+
*/
|
|
353
|
+
async setConsumptionHorizon(conversationId, messageId, at = Date.now()) {
|
|
354
|
+
this.#requireConfigured();
|
|
355
|
+
const url = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(conversationId)}` +
|
|
356
|
+
'/properties?name=consumptionhorizon';
|
|
357
|
+
const body = { consumptionhorizon: `${messageId};${at};${messageId}` };
|
|
358
|
+
const { status } = await this.#send(url, 'text', undefined, { method: 'PUT', body, hint: HORIZON_OUTCOME_HINT });
|
|
359
|
+
this.#checkWriteStatus('PUT', status, HORIZON_OUTCOME_HINT);
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Download an inline image (`<img src>` in a message body).
|
|
363
|
+
*
|
|
364
|
+
* The URL comes out of message content — i.e. it is attacker-influenced —
|
|
365
|
+
* so it is checked BEFORE a token is even resolved: https only, and a host
|
|
366
|
+
* under `.asm.skype.com`. Anything else would hand the user's bearer to
|
|
367
|
+
* whoever wrote the message.
|
|
368
|
+
*/
|
|
369
|
+
async fetchImage(url) {
|
|
370
|
+
this.#requireConfigured();
|
|
371
|
+
let target;
|
|
372
|
+
try {
|
|
373
|
+
target = new URL(url);
|
|
374
|
+
}
|
|
375
|
+
catch {
|
|
376
|
+
throw new McpToolError('Refusing to fetch an image link that is not a URL.', {
|
|
377
|
+
hint: 'Pass an image ref exactly as a message listing returned it.',
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
if (target.protocol !== 'https:' || !target.hostname.endsWith(IMAGE_HOST_SUFFIX)) {
|
|
381
|
+
throw new McpToolError(`Refusing to fetch an image from ${target.protocol}//${target.hostname}.`, {
|
|
382
|
+
hint: `Only https images on *${IMAGE_HOST_SUFFIX} (Teams' own image store) are fetched.`,
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
const { status, headers, body } = await this.#send(target.toString(), 'bytes', MAX_IMAGE_BYTES);
|
|
386
|
+
this.#checkStatus(status);
|
|
387
|
+
const mimeType = (headers.get('content-type') ?? 'application/octet-stream').split(';')[0].trim();
|
|
388
|
+
return { mimeType, data: Buffer.from(body) };
|
|
389
|
+
}
|
|
390
|
+
#requireConfigured() {
|
|
391
|
+
if (this.#configError)
|
|
392
|
+
throw this.#configError;
|
|
393
|
+
}
|
|
394
|
+
#tokenManager() {
|
|
395
|
+
if (this.#tokens)
|
|
396
|
+
return this.#tokens;
|
|
397
|
+
const direct = this.#direct;
|
|
398
|
+
const persistence = direct === undefined ? createTokenCache(this.#env) : null;
|
|
399
|
+
const mint = async () => toBearerTokens(direct ?? (await this.#capture()));
|
|
400
|
+
this.#tokens = new TokenManager({
|
|
401
|
+
initial: mint,
|
|
402
|
+
// There is no refresh grant — re-capture instead. But a token supplied as
|
|
403
|
+
// TEAMS_ACCESS_TOKEN must NOT be "refreshed" from the browser: that would
|
|
404
|
+
// silently swap the operator's chosen credential for whichever account a
|
|
405
|
+
// tab is signed into.
|
|
406
|
+
refresh: async () => {
|
|
407
|
+
if (direct !== undefined)
|
|
408
|
+
throw this.#directRejected();
|
|
409
|
+
return toBearerTokens(await this.#capture());
|
|
410
|
+
},
|
|
411
|
+
// A failed cache write must not fail the call that triggered it.
|
|
412
|
+
...(persistence
|
|
413
|
+
? {
|
|
414
|
+
persistence: {
|
|
415
|
+
load: () => persistence.load(),
|
|
416
|
+
save: (t) => {
|
|
417
|
+
try {
|
|
418
|
+
persistence.save(t);
|
|
419
|
+
}
|
|
420
|
+
catch (e) {
|
|
421
|
+
reportCacheWriteFailure(e);
|
|
422
|
+
}
|
|
423
|
+
},
|
|
424
|
+
clear: () => {
|
|
425
|
+
try {
|
|
426
|
+
persistence.clear();
|
|
427
|
+
}
|
|
428
|
+
catch {
|
|
429
|
+
/* nothing useful to do; the next capture overwrites it */
|
|
430
|
+
}
|
|
431
|
+
},
|
|
432
|
+
},
|
|
433
|
+
}
|
|
434
|
+
: {}),
|
|
435
|
+
});
|
|
436
|
+
return this.#tokens;
|
|
437
|
+
}
|
|
438
|
+
#directRejected() {
|
|
439
|
+
return new McpToolError('TEAMS_ACCESS_TOKEN was rejected by Teams (401).', {
|
|
440
|
+
status: 401,
|
|
441
|
+
kind: 'credential_rejected',
|
|
442
|
+
hint: 'A directly-supplied token cannot be refreshed automatically. Replace ' +
|
|
443
|
+
'TEAMS_ACCESS_TOKEN with a current one, or unset it to capture from a signed-in ' +
|
|
444
|
+
'Teams browser tab instead.',
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* One authenticated GET. `TokenManager.withAuth` supplies the token and, on a
|
|
449
|
+
* 401, re-captures once and replays once — so a 401 that reaches the caller
|
|
450
|
+
* is the second one.
|
|
451
|
+
*
|
|
452
|
+
* The body is read as text/bytes rather than JSON so a 401's non-JSON body
|
|
453
|
+
* cannot throw inside the call and pre-empt that replay.
|
|
454
|
+
*/
|
|
455
|
+
async #send(url, read, maxBytes,
|
|
456
|
+
/** A write: a lost answer is a `WriteOutcomeUnknownError` carrying `hint`. */
|
|
457
|
+
write) {
|
|
458
|
+
let body = '';
|
|
459
|
+
const method = write?.method ?? 'GET';
|
|
460
|
+
const res = await this.#tokenManager().withAuth(async (token) => {
|
|
461
|
+
const init = {
|
|
462
|
+
method,
|
|
463
|
+
headers: {
|
|
464
|
+
authorization: `Bearer ${token}`,
|
|
465
|
+
// Verified live: without it the service answers some failures with
|
|
466
|
+
// a redirect to a sign-in page instead of a status we can act on.
|
|
467
|
+
behavioroverride: 'redirectAs404',
|
|
468
|
+
accept: read === 'text' ? 'application/json' : '*/*',
|
|
469
|
+
...(write ? { 'content-type': 'application/json' } : {}),
|
|
470
|
+
},
|
|
471
|
+
...(write ? { body: JSON.stringify(write.body) } : {}),
|
|
472
|
+
// Never let a redirect carry the bearer somewhere we did not vet.
|
|
473
|
+
redirect: 'error',
|
|
474
|
+
};
|
|
475
|
+
const opts = { read, maxBytes, service: 'Teams', timeoutMs: REQUEST_TIMEOUT_MS, fetchImpl: this.#fetchImpl };
|
|
476
|
+
let r;
|
|
477
|
+
try {
|
|
478
|
+
r = await fetchBounded(url, init, opts);
|
|
479
|
+
}
|
|
480
|
+
catch (e) {
|
|
481
|
+
throw write ? outcomeUnknown(method, e, write.hint) : e;
|
|
482
|
+
}
|
|
483
|
+
body = r.body;
|
|
484
|
+
return r.res;
|
|
485
|
+
});
|
|
486
|
+
return { status: res.status, headers: res.headers, body };
|
|
487
|
+
}
|
|
488
|
+
async #getJson(url) {
|
|
489
|
+
const { status, body } = await this.#send(url, 'text');
|
|
490
|
+
return this.#parseJson(status, body);
|
|
491
|
+
}
|
|
492
|
+
#parseJson(status, body) {
|
|
493
|
+
this.#checkStatus(status);
|
|
494
|
+
try {
|
|
495
|
+
return JSON.parse(body);
|
|
496
|
+
}
|
|
497
|
+
catch {
|
|
498
|
+
// Never echo the body: it is the user's message content.
|
|
499
|
+
throw new McpToolError('Teams chat service returned a response that is not JSON.', {
|
|
500
|
+
status,
|
|
501
|
+
kind: 'http',
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* A write's status: a 5xx means the request reached Teams and failed
|
|
507
|
+
* somewhere past the front door — a gateway that lost the backend's answer
|
|
508
|
+
* (502/504) or a backend that may have committed before failing — so the
|
|
509
|
+
* outcome is unknown, never a plain "retry shortly". Anything else maps as
|
|
510
|
+
* for a read.
|
|
511
|
+
*/
|
|
512
|
+
#checkWriteStatus(method, status, hint) {
|
|
513
|
+
if (status >= 500 && status < 600) {
|
|
514
|
+
throw new WriteOutcomeUnknownError('Teams', method, {
|
|
515
|
+
cause: new McpToolError(`Teams chat service returned HTTP ${status}.`, { status, kind: 'http' }),
|
|
516
|
+
hint,
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
this.#checkStatus(status);
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Map a non-2xx to an `McpToolError` carrying its status. No retry loop: a
|
|
523
|
+
* 429 or 5xx is reported, and the model decides whether to try again. The
|
|
524
|
+
* body is never included — it may be message content.
|
|
525
|
+
*/
|
|
526
|
+
#checkStatus(status) {
|
|
527
|
+
if (status >= 200 && status < 300)
|
|
528
|
+
return;
|
|
529
|
+
if (status === 401) {
|
|
530
|
+
if (this.#direct !== undefined)
|
|
531
|
+
throw this.#directRejected();
|
|
532
|
+
throw new McpToolError('Teams rejected the access token (401) even after a fresh capture.', {
|
|
533
|
+
status,
|
|
534
|
+
kind: 'credential_rejected',
|
|
535
|
+
hint: 'Re-open Teams in a signed-in teams.cloud.microsoft tab (sign in again if it ' +
|
|
536
|
+
'asks), click into any chat, then retry.',
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
if (status === 429) {
|
|
540
|
+
throw new McpToolError('Teams chat service is rate-limiting requests (429).', {
|
|
541
|
+
status,
|
|
542
|
+
kind: 'http',
|
|
543
|
+
hint: 'Wait a minute before retrying.',
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
throw new McpToolError(`Teams chat service returned HTTP ${status}.`, {
|
|
547
|
+
status,
|
|
548
|
+
kind: 'http',
|
|
549
|
+
...(status >= 500 ? { hint: 'A Teams-side failure; retry shortly.' } : {}),
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* The next (older) page's URL, re-rooted onto the configured base.
|
|
554
|
+
*
|
|
555
|
+
* The service hands back an absolute `backwardLink`. Rather than trust its
|
|
556
|
+
* origin with the bearer token, only its `/users/…` path and query are kept
|
|
557
|
+
* and requested against our own base — so a link naming another host (the
|
|
558
|
+
* service's internal one, or anything else) can never receive the token. A
|
|
559
|
+
* link with no `/v1/users/` path is refused outright.
|
|
560
|
+
*/
|
|
561
|
+
#nextLink(page) {
|
|
562
|
+
const link = page._metadata?.backwardLink;
|
|
563
|
+
if (typeof link !== 'string' || link === '')
|
|
564
|
+
return undefined;
|
|
565
|
+
let target;
|
|
566
|
+
try {
|
|
567
|
+
target = new URL(link);
|
|
568
|
+
}
|
|
569
|
+
catch {
|
|
570
|
+
throw new McpToolError('Refusing to follow a Teams paging link that is not a URL.');
|
|
571
|
+
}
|
|
572
|
+
const at = target.pathname.indexOf('/v1/users/');
|
|
573
|
+
if (at < 0) {
|
|
574
|
+
throw new McpToolError(`Refusing to follow a Teams paging link to ${target.origin}${target.pathname}.`, {
|
|
575
|
+
hint: 'Paging links must be chat-service /v1/users/… paths.',
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
return `${this.#baseUrl}${target.pathname.slice(at + '/v1'.length)}${target.search}`;
|
|
579
|
+
}
|
|
580
|
+
}
|