@chrischall/microsoft-teams-mcp 0.3.0 → 0.4.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 +279 -93
- package/dist/auth-fetchproxy.js +138 -0
- package/dist/bundle.js +42380 -37144
- package/dist/capture-window.js +41 -0
- package/dist/chatsvc.js +552 -0
- package/dist/compose.js +241 -0
- package/dist/deps.js +1 -0
- package/dist/index.js +26 -6
- package/dist/model.js +499 -0
- package/dist/sharepoint-auth.js +162 -0
- package/dist/sharepoint-token-cache.js +105 -0
- package/dist/sharepoint.js +289 -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/channels.js +60 -44
- package/dist/tools/chat.js +47 -42
- package/dist/tools/confirm.js +145 -0
- package/dist/tools/conversation.js +172 -32
- package/dist/tools/errors.js +18 -17
- package/dist/tools/healthcheck.js +86 -27
- package/dist/tools/limit.js +43 -12
- package/dist/tools/listing.js +116 -0
- package/dist/tools/react.js +217 -0
- package/dist/tools/send.js +309 -0
- package/dist/tools/titles.js +180 -0
- package/dist/tools/unread.js +162 -0
- package/dist/tools/untrusted.js +16 -1
- package/dist/version.js +1 -1
- package/mint.yaml +63 -20
- package/package.json +1 -2
- package/server.json +80 -3
- package/skills/teams-fpx/SKILL.md +108 -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,105 @@
|
|
|
1
|
+
import { createFileStatePersistence, resolveStateFile, } from '@chrischall/mcp-utils/session';
|
|
2
|
+
import { parseBoolEnv } from '@chrischall/mcp-utils';
|
|
3
|
+
import { reportCacheWriteFailure } from './token-cache.js';
|
|
4
|
+
/**
|
|
5
|
+
* Where the captured SharePoint access tokens are cached between runs.
|
|
6
|
+
*
|
|
7
|
+
* A SEPARATE file from the chat-service `token.json`: a SharePoint token is a
|
|
8
|
+
* different audience with a very different lifetime (~53 min vs chatsvc's ~23h),
|
|
9
|
+
* and there is one per SharePoint host rather than one overall — so this file
|
|
10
|
+
* holds a `Record<host, BearerTokens>`, not a single token. Deliberately its own
|
|
11
|
+
* directory for the same reason `tokenCachePath` is.
|
|
12
|
+
*/
|
|
13
|
+
export function sharePointTokenCachePath(env = process.env) {
|
|
14
|
+
return resolveStateFile({
|
|
15
|
+
env,
|
|
16
|
+
envVar: 'TEAMS_SHAREPOINT_TOKEN_FILE',
|
|
17
|
+
subdir: '.microsoft-teams-mcp',
|
|
18
|
+
fileName: 'sharepoint-tokens.json',
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
/** Same `BearerTokens` guard as the chatsvc cache; copied, as it is module-private there. */
|
|
22
|
+
function isToken(raw) {
|
|
23
|
+
if (raw === null || typeof raw !== 'object')
|
|
24
|
+
return false;
|
|
25
|
+
const t = raw;
|
|
26
|
+
return (typeof t.accessToken === 'string' &&
|
|
27
|
+
t.accessToken !== '' &&
|
|
28
|
+
typeof t.expiresAt === 'number' &&
|
|
29
|
+
(t.refreshToken === undefined || typeof t.refreshToken === 'string'));
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Narrow the stored blob to a map of valid tokens.
|
|
33
|
+
*
|
|
34
|
+
* A non-object (or array) blob is `null` — the whole file is unusable. Otherwise
|
|
35
|
+
* each host's slice is validated independently and a MALFORMED one is dropped
|
|
36
|
+
* rather than discarding the file: a single corrupt entry must not cost every
|
|
37
|
+
* other host its cached token.
|
|
38
|
+
*/
|
|
39
|
+
function validateMap(raw) {
|
|
40
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
|
|
41
|
+
return null;
|
|
42
|
+
const out = {};
|
|
43
|
+
for (const [host, value] of Object.entries(raw)) {
|
|
44
|
+
if (isToken(value))
|
|
45
|
+
out[host] = value;
|
|
46
|
+
}
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The SharePoint token cache, or `null` when it is off or there is nothing to
|
|
51
|
+
* cache.
|
|
52
|
+
*
|
|
53
|
+
* Gated by the same `TEAMS_TOKEN_CACHE` (default on) as the chatsvc cache, and
|
|
54
|
+
* `null` under `TEAMS_DISABLE_FETCHPROXY`: a SharePoint token is only ever
|
|
55
|
+
* captured from the browser bridge — unlike chatsvc there is no direct-token
|
|
56
|
+
* env var — so with the bridge off there is nothing to cache.
|
|
57
|
+
*/
|
|
58
|
+
export function createSharePointTokenCache(env = process.env) {
|
|
59
|
+
if (!parseBoolEnv('TEAMS_TOKEN_CACHE', { env, default: true }))
|
|
60
|
+
return null;
|
|
61
|
+
if (parseBoolEnv('TEAMS_DISABLE_FETCHPROXY', { env }))
|
|
62
|
+
return null;
|
|
63
|
+
// One file-backed persistence for the whole map; the per-host views below read
|
|
64
|
+
// and write it. No `boundTo`: there is no single credential the whole map is
|
|
65
|
+
// minted from — each host's token stands or falls on its own shape.
|
|
66
|
+
const file = createFileStatePersistence({
|
|
67
|
+
filePath: sharePointTokenCachePath(env),
|
|
68
|
+
validate: validateMap,
|
|
69
|
+
});
|
|
70
|
+
return {
|
|
71
|
+
forHost(host) {
|
|
72
|
+
return {
|
|
73
|
+
load() {
|
|
74
|
+
return file.load()?.[host] ?? null;
|
|
75
|
+
},
|
|
76
|
+
save(tokens) {
|
|
77
|
+
// Read-modify-write the shared map so a sibling host's token survives.
|
|
78
|
+
// A failed write is reported, never thrown: a SharePoint token is
|
|
79
|
+
// cheap to re-capture, and a read-only data dir must not take the
|
|
80
|
+
// tool down — it just loses the between-run cache.
|
|
81
|
+
try {
|
|
82
|
+
const map = file.load() ?? {};
|
|
83
|
+
map[host] = tokens;
|
|
84
|
+
file.save(map);
|
|
85
|
+
}
|
|
86
|
+
catch (err) {
|
|
87
|
+
reportCacheWriteFailure(err);
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
clear() {
|
|
91
|
+
try {
|
|
92
|
+
const map = file.load();
|
|
93
|
+
if (map && host in map) {
|
|
94
|
+
delete map[host];
|
|
95
|
+
file.save(map);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
catch (err) {
|
|
99
|
+
reportCacheWriteFailure(err);
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
}
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The SharePoint download client — fetches the CONTENTS of a shared file that
|
|
3
|
+
* lives in a Teams chat.
|
|
4
|
+
*
|
|
5
|
+
* A shared file is not in the Teams AMS object store inline images come from; it
|
|
6
|
+
* is in SharePoint, and reading it needs a SharePoint token, NOT the chat-service
|
|
7
|
+
* token `chatsvc.ts` holds (chatsvc's token returns 401 on SharePoint, and Graph
|
|
8
|
+
* `/shares` returns 403). Verified live 2026-10-11, the one route that works:
|
|
9
|
+
*
|
|
10
|
+
* GET https://{host}/_api/v2.1/shares/u!{base64url(objectUrl)}/driveItem
|
|
11
|
+
* ?$select=id,size,@content.downloadUrl [Authorization: Bearer <SP>]
|
|
12
|
+
* GET {@content.downloadUrl} [no auth — pre-signed]
|
|
13
|
+
* → the file's bytes
|
|
14
|
+
*
|
|
15
|
+
* The SP token is captured per host from the user's browser (see
|
|
16
|
+
* `sharepoint-auth.ts`), is short-lived (~53 min) and host-family-scoped, so this
|
|
17
|
+
* client holds one `TokenManager` per host — each with the same capture-on-401
|
|
18
|
+
* recovery `ChatServiceClient` has. A 403 is expected (an account that cannot
|
|
19
|
+
* open the file, or a host the captured token does not cover) and degrades
|
|
20
|
+
* gracefully; it never crashes the tool.
|
|
21
|
+
*
|
|
22
|
+
* As with `chatsvc.ts`, once a token is held every request is a plain Node
|
|
23
|
+
* `fetch` — the bridge is only ever touched to capture the token.
|
|
24
|
+
*/
|
|
25
|
+
import { decodeJwtExp, fetchBounded, McpToolError, parseBoolEnv } from '@chrischall/mcp-utils';
|
|
26
|
+
import { TokenManager } from '@chrischall/mcp-utils/session';
|
|
27
|
+
import { createSharePointTokenCache } from './sharepoint-token-cache.js';
|
|
28
|
+
/**
|
|
29
|
+
* Capture a SharePoint token for `host` lazily.
|
|
30
|
+
*
|
|
31
|
+
* `sharepoint-auth.ts` pulls in `@chrischall/mcp-utils/fetchproxy`, whose
|
|
32
|
+
* optional `@fetchproxy/server` peer the `.mcpb` bundle ships no `node_modules`
|
|
33
|
+
* for — so a top-level import would throw `ERR_MODULE_NOT_FOUND` before the
|
|
34
|
+
* server could answer `initialize`. Deferring it (exactly as `chatsvc.ts` does
|
|
35
|
+
* for its own capture) keeps boot free of the bridge.
|
|
36
|
+
*/
|
|
37
|
+
async function captureSharePointTokenLazily(host) {
|
|
38
|
+
const mod = await import('./sharepoint-auth.js');
|
|
39
|
+
return mod.captureSharePointTokenViaFetchproxy(host);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Fallback lifetime for a token whose `exp` we cannot read. Real SP tokens are
|
|
43
|
+
* JWTs carrying `exp` (~53 min out), so this is only reached for a malformed
|
|
44
|
+
* capture; deliberately short — being wrong here costs one extra 401-and-replay.
|
|
45
|
+
*/
|
|
46
|
+
const UNKNOWN_TOKEN_TTL_MS = 10 * 60 * 1000;
|
|
47
|
+
/**
|
|
48
|
+
* Sentinel standing in for a refresh token this flow does not have. The token
|
|
49
|
+
* comes from the browser; "refreshing" means capturing a new one. `TokenManager`
|
|
50
|
+
* only calls `refresh` when a refresh token is present, hence the sentinel.
|
|
51
|
+
* (Copied from `chatsvc.ts`, where it is module-private.)
|
|
52
|
+
*/
|
|
53
|
+
const RECAPTURE_SENTINEL = 'fetchproxy:recapture';
|
|
54
|
+
/** Per-request deadline, covering the body read. */
|
|
55
|
+
const REQUEST_TIMEOUT_MS = 60_000;
|
|
56
|
+
/** Copied faithfully from `chatsvc.ts`: a captured token as `TokenManager` input. */
|
|
57
|
+
function toBearerTokens(accessToken) {
|
|
58
|
+
let expiresAt;
|
|
59
|
+
try {
|
|
60
|
+
// decodeJwtExp returns seconds; a non-JWT throws.
|
|
61
|
+
expiresAt = decodeJwtExp(accessToken) * 1000;
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
expiresAt = Date.now() + UNKNOWN_TOKEN_TTL_MS;
|
|
65
|
+
}
|
|
66
|
+
return { accessToken, refreshToken: RECAPTURE_SENTINEL, expiresAt };
|
|
67
|
+
}
|
|
68
|
+
export class SharePointClient {
|
|
69
|
+
#env;
|
|
70
|
+
#capture;
|
|
71
|
+
#fetchImpl;
|
|
72
|
+
#cache;
|
|
73
|
+
/**
|
|
74
|
+
* Deferred configuration error. The constructor never throws, so the server
|
|
75
|
+
* still boots (and answers `tools/list`) with no credential present.
|
|
76
|
+
*/
|
|
77
|
+
#configError = null;
|
|
78
|
+
/** One `TokenManager` per SharePoint host — SP tokens are host-scoped. */
|
|
79
|
+
#managers = new Map();
|
|
80
|
+
constructor(opts = {}) {
|
|
81
|
+
this.#env = opts.env ?? process.env;
|
|
82
|
+
this.#capture = opts.captureToken ?? captureSharePointTokenLazily;
|
|
83
|
+
// A receiver-safe wrapper, never the bare global: older undici throws
|
|
84
|
+
// `Illegal invocation` when `fetch` is called with a non-global receiver.
|
|
85
|
+
this.#fetchImpl = opts.fetchImpl ?? ((input, init) => fetch(input, init));
|
|
86
|
+
this.#cache = createSharePointTokenCache(this.#env);
|
|
87
|
+
// Unlike chatsvc there is NO direct-token env var: a SharePoint token is
|
|
88
|
+
// only ever captured from the browser, so with the bridge off there is no
|
|
89
|
+
// way to get one. Defer that as a clean no_credential rather than letting a
|
|
90
|
+
// download attempt the bridge.
|
|
91
|
+
if (parseBoolEnv('TEAMS_DISABLE_FETCHPROXY', { env: this.#env })) {
|
|
92
|
+
this.#configError = new McpToolError('SharePoint file download is disabled (no token source).', {
|
|
93
|
+
kind: 'no_credential',
|
|
94
|
+
hint: 'Unset TEAMS_DISABLE_FETCHPROXY so a SharePoint token can be captured from a ' +
|
|
95
|
+
'signed-in Teams browser tab when a shared file is opened.',
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/** Whether a token could be obtained at all (the bridge is not disabled). */
|
|
100
|
+
isConfigured() {
|
|
101
|
+
return this.#configError === null;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Download the contents of a shared file by its `objectUrl` (the `url` a file
|
|
105
|
+
* attachment carries). Returns the bytes, the mime type and the byte count.
|
|
106
|
+
*
|
|
107
|
+
* The URL comes out of message content — i.e. it is attacker-influenced — so
|
|
108
|
+
* it is vetted BEFORE a token is resolved: https only, and a concrete
|
|
109
|
+
* `*.sharepoint.com` tenant host. Anything else would hand the SharePoint
|
|
110
|
+
* bearer to whoever wrote the message.
|
|
111
|
+
*/
|
|
112
|
+
async downloadFile(objectUrl, maxBytes) {
|
|
113
|
+
this.#requireConfigured();
|
|
114
|
+
let target;
|
|
115
|
+
try {
|
|
116
|
+
target = new URL(objectUrl);
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
throw new McpToolError('Refusing to download a file whose link is not a URL.', {
|
|
120
|
+
hint: 'Pass a file url exactly as a message listing returned it.',
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
// `isSharePointHost` lives in the lazily-imported auth module (see
|
|
124
|
+
// `captureSharePointTokenLazily`); loaded here too so the host is vetted with
|
|
125
|
+
// the one authoritative check rather than a duplicate.
|
|
126
|
+
const { isSharePointHost } = await import('./sharepoint-auth.js');
|
|
127
|
+
const host = target.hostname;
|
|
128
|
+
if (target.protocol !== 'https:' || !isSharePointHost(host)) {
|
|
129
|
+
throw new McpToolError(`Refusing to download a file from ${target.protocol}//${host}.`, {
|
|
130
|
+
hint: 'Only https files on a *.sharepoint.com tenant host are downloaded.',
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
// The driveItem GET goes to the FILE's host, but the token is captured from
|
|
134
|
+
// (and cached under) the user's OneDrive host — the browser authenticates
|
|
135
|
+
// that host, and its token reads the tenant root too. See `captureHostFor`.
|
|
136
|
+
const { captureHostFor } = await import('./sharepoint-auth.js');
|
|
137
|
+
const captureHost = captureHostFor(host);
|
|
138
|
+
// `u!` + unpadded base64url of the full objectUrl (Node's `base64url` already
|
|
139
|
+
// uses `-`/`_` and drops padding), matching the live spike.
|
|
140
|
+
const share = `u!${Buffer.from(objectUrl, 'utf8').toString('base64url')}`;
|
|
141
|
+
const driveItemUrl = `https://${host}/_api/v2.1/shares/${share}/driveItem?$select=id,size,@content.downloadUrl`;
|
|
142
|
+
const meta = await this.#getDriveItem(captureHost, driveItemUrl);
|
|
143
|
+
// Refuse an oversize file BEFORE streaming it: the driveItem carries `size`,
|
|
144
|
+
// so a file past the cap degrades to metadata + link (the attachment tool
|
|
145
|
+
// surfaces this hint) instead of fetching to the byte limit and tripping a
|
|
146
|
+
// less actionable read error.
|
|
147
|
+
if (typeof meta.size === 'number' && meta.size > maxBytes) {
|
|
148
|
+
const mb = (n) => `${Math.round(n / (1024 * 1024))} MB`;
|
|
149
|
+
throw new McpToolError(`The file is ${mb(meta.size)}, larger than the ${mb(maxBytes)} download limit.`, {
|
|
150
|
+
kind: 'http',
|
|
151
|
+
hint: `This file is ${mb(meta.size)}; open it with its link rather than downloading it here.`,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
const downloadUrl = meta['@content.downloadUrl'];
|
|
155
|
+
if (typeof downloadUrl !== 'string' || downloadUrl === '') {
|
|
156
|
+
throw new McpToolError('SharePoint returned no download link for the file.', {
|
|
157
|
+
kind: 'http',
|
|
158
|
+
hint: 'The file may be a folder or a format with no direct content; open it with its link.',
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
return this.#fetchContent(downloadUrl, maxBytes);
|
|
162
|
+
// fallback: sharepointIds route — the proven shares route above has not 404'd
|
|
163
|
+
// in testing; the documented driveId/siteId/listItemUniqueId addressing stays
|
|
164
|
+
// out until a real 404 warrants it (plan Task 3, optional).
|
|
165
|
+
}
|
|
166
|
+
#requireConfigured() {
|
|
167
|
+
if (this.#configError)
|
|
168
|
+
throw this.#configError;
|
|
169
|
+
}
|
|
170
|
+
/** The `TokenManager` for `host`, created (and cached) on first use. */
|
|
171
|
+
#managerFor(host) {
|
|
172
|
+
const existing = this.#managers.get(host);
|
|
173
|
+
if (existing)
|
|
174
|
+
return existing;
|
|
175
|
+
// The per-host cache view already swallows-and-reports its own write
|
|
176
|
+
// failures (see `sharepoint-token-cache.ts`), so it is passed straight
|
|
177
|
+
// through — no inline wrapping as chatsvc needs for its raw persistence.
|
|
178
|
+
const persistence = this.#cache?.forHost(host);
|
|
179
|
+
const mgr = new TokenManager({
|
|
180
|
+
initial: async () => toBearerTokens(await this.#capture(host)),
|
|
181
|
+
// No refresh grant — re-capture instead.
|
|
182
|
+
refresh: async () => toBearerTokens(await this.#capture(host)),
|
|
183
|
+
...(persistence ? { persistence } : {}),
|
|
184
|
+
});
|
|
185
|
+
this.#managers.set(host, mgr);
|
|
186
|
+
return mgr;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* The authed driveItem GET, with chatsvc's discipline: `behavioroverride:
|
|
190
|
+
* redirectAs404` so a failure is a status rather than a sign-in redirect, and
|
|
191
|
+
* `redirect: 'error'` so a redirect never carries the bearer somewhere unvetted.
|
|
192
|
+
* `TokenManager.withAuth` supplies the token and, on a 401, re-captures once
|
|
193
|
+
* and replays once — so a 401 that reaches here is the second one.
|
|
194
|
+
*/
|
|
195
|
+
async #getDriveItem(captureHost, url) {
|
|
196
|
+
let body = '';
|
|
197
|
+
const res = await this.#managerFor(captureHost).withAuth(async (token) => {
|
|
198
|
+
const r = await fetchBounded(url, {
|
|
199
|
+
method: 'GET',
|
|
200
|
+
headers: {
|
|
201
|
+
authorization: `Bearer ${token}`,
|
|
202
|
+
accept: 'application/json',
|
|
203
|
+
behavioroverride: 'redirectAs404',
|
|
204
|
+
},
|
|
205
|
+
redirect: 'error',
|
|
206
|
+
}, { read: 'text', service: 'SharePoint', timeoutMs: REQUEST_TIMEOUT_MS, fetchImpl: this.#fetchImpl });
|
|
207
|
+
body = r.body;
|
|
208
|
+
return r.res;
|
|
209
|
+
});
|
|
210
|
+
const status = res.status;
|
|
211
|
+
if (status === 403) {
|
|
212
|
+
// mcp-utils' `kind` vocabulary has no 'forbidden'; the 403 is carried by
|
|
213
|
+
// `status`, which the attachment tool reads to degrade to metadata + link.
|
|
214
|
+
throw new McpToolError('SharePoint refused access to the file (403).', {
|
|
215
|
+
status,
|
|
216
|
+
kind: 'http',
|
|
217
|
+
hint: 'Your account cannot open this file, or it is on a SharePoint host your captured ' +
|
|
218
|
+
'token does not cover. Open it once in Teams, then retry.',
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
if (status === 404) {
|
|
222
|
+
throw new McpToolError('SharePoint has no such file (404).', {
|
|
223
|
+
status,
|
|
224
|
+
kind: 'http',
|
|
225
|
+
hint: 'The file may have moved or been deleted; open it with its link to check.',
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
return this.#parseJson(status, body);
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Fetch the pre-signed download link with NO Authorization header. It 302s to
|
|
232
|
+
* a CDN/blob host, which is safe to follow precisely because no bearer is
|
|
233
|
+
* attached; the read is bounded to `maxBytes`. https only.
|
|
234
|
+
*/
|
|
235
|
+
async #fetchContent(downloadUrl, maxBytes) {
|
|
236
|
+
let target;
|
|
237
|
+
try {
|
|
238
|
+
target = new URL(downloadUrl);
|
|
239
|
+
}
|
|
240
|
+
catch {
|
|
241
|
+
throw new McpToolError('SharePoint returned a download link that is not a URL.', { kind: 'http' });
|
|
242
|
+
}
|
|
243
|
+
if (target.protocol !== 'https:') {
|
|
244
|
+
throw new McpToolError(`Refusing to fetch a download link over ${target.protocol}.`, {
|
|
245
|
+
kind: 'http',
|
|
246
|
+
hint: 'SharePoint download links are expected to be https.',
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
const r = await fetchBounded(target.toString(), { method: 'GET', headers: { accept: '*/*' }, redirect: 'follow' }, { read: 'bytes', maxBytes, service: 'SharePoint', timeoutMs: REQUEST_TIMEOUT_MS, fetchImpl: this.#fetchImpl });
|
|
250
|
+
this.#checkStatus(r.status);
|
|
251
|
+
const mimeType = (r.headers.get('content-type') ?? 'application/octet-stream').split(';')[0].trim();
|
|
252
|
+
const data = Buffer.from(r.body);
|
|
253
|
+
return { mimeType, data, size: data.length };
|
|
254
|
+
}
|
|
255
|
+
#parseJson(status, body) {
|
|
256
|
+
this.#checkStatus(status);
|
|
257
|
+
try {
|
|
258
|
+
return JSON.parse(body);
|
|
259
|
+
}
|
|
260
|
+
catch {
|
|
261
|
+
// Never echo the body: it may be the file's metadata or an error page.
|
|
262
|
+
throw new McpToolError('SharePoint returned a response that is not JSON.', { status, kind: 'http' });
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
/** Map a non-2xx to an `McpToolError` carrying its status. The body is never included. */
|
|
266
|
+
#checkStatus(status) {
|
|
267
|
+
if (status >= 200 && status < 300)
|
|
268
|
+
return;
|
|
269
|
+
if (status === 401) {
|
|
270
|
+
throw new McpToolError('SharePoint rejected the access token (401) even after a fresh capture.', {
|
|
271
|
+
status,
|
|
272
|
+
kind: 'credential_rejected',
|
|
273
|
+
hint: 'Open the shared file once in a signed-in Teams tab to mint a fresh SharePoint token, then retry.',
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
if (status === 429) {
|
|
277
|
+
throw new McpToolError('SharePoint is rate-limiting requests (429).', {
|
|
278
|
+
status,
|
|
279
|
+
kind: 'http',
|
|
280
|
+
hint: 'Wait a minute before retrying.',
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
throw new McpToolError(`SharePoint returned HTTP ${status}.`, {
|
|
284
|
+
status,
|
|
285
|
+
kind: 'http',
|
|
286
|
+
...(status >= 500 ? { hint: 'A SharePoint-side failure; retry shortly.' } : {}),
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { createFileStatePersistence, resolveStateFile, } from '@chrischall/mcp-utils/session';
|
|
2
|
+
import { readEnvVar, parseBoolEnv } from '@chrischall/mcp-utils';
|
|
3
|
+
/**
|
|
4
|
+
* Where the captured chat-service access token is cached between runs.
|
|
5
|
+
*
|
|
6
|
+
* Deliberately its OWN directory, so nothing else that keeps Teams
|
|
7
|
+
* credentials (the `teams-fpx` access skill, say) can corrupt it by writing a
|
|
8
|
+
* different format to the same file.
|
|
9
|
+
*/
|
|
10
|
+
export function tokenCachePath(env = process.env) {
|
|
11
|
+
return resolveStateFile({
|
|
12
|
+
env,
|
|
13
|
+
envVar: 'TEAMS_TOKEN_FILE',
|
|
14
|
+
subdir: '.microsoft-teams-mcp',
|
|
15
|
+
fileName: 'token.json',
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
function isToken(raw) {
|
|
19
|
+
if (raw === null || typeof raw !== 'object')
|
|
20
|
+
return false;
|
|
21
|
+
const t = raw;
|
|
22
|
+
return (typeof t.accessToken === 'string' &&
|
|
23
|
+
t.accessToken !== '' &&
|
|
24
|
+
typeof t.expiresAt === 'number' &&
|
|
25
|
+
(t.refreshToken === undefined || typeof t.refreshToken === 'string'));
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* What a cached token is bound to, or `null` when there is nothing worth
|
|
29
|
+
* caching.
|
|
30
|
+
*
|
|
31
|
+
* A `TEAMS_ACCESS_TOKEN` IS the environment variable — there is no capture to
|
|
32
|
+
* skip, so caching it would only copy a credential onto disk. A captured token
|
|
33
|
+
* is worth caching most of all: it lets a cold start proceed with no browser
|
|
34
|
+
* present for the token's ~23h lifetime.
|
|
35
|
+
*/
|
|
36
|
+
function bindingFor(env) {
|
|
37
|
+
if (readEnvVar('TEAMS_ACCESS_TOKEN', { env }) !== undefined)
|
|
38
|
+
return null;
|
|
39
|
+
if (parseBoolEnv('TEAMS_DISABLE_FETCHPROXY', { env }))
|
|
40
|
+
return null;
|
|
41
|
+
return 'fetchproxy';
|
|
42
|
+
}
|
|
43
|
+
/** The token cache, or `null` when it is off or there is nothing to cache. */
|
|
44
|
+
export function createTokenCache(env = process.env) {
|
|
45
|
+
if (!parseBoolEnv('TEAMS_TOKEN_CACHE', { env, default: true }))
|
|
46
|
+
return null;
|
|
47
|
+
const boundTo = bindingFor(env);
|
|
48
|
+
if (boundTo === null)
|
|
49
|
+
return null;
|
|
50
|
+
return createFileStatePersistence({
|
|
51
|
+
filePath: tokenCachePath(env),
|
|
52
|
+
boundTo,
|
|
53
|
+
validate: (raw) => (isToken(raw) ? raw : null),
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Report a cache write that failed. Not fatal — the token is re-capturable —
|
|
58
|
+
* but worth saying, because a read-only data dir otherwise looks exactly like a
|
|
59
|
+
* server that simply never caches.
|
|
60
|
+
*
|
|
61
|
+
* stderr only; stdout is the JSON-RPC channel.
|
|
62
|
+
*/
|
|
63
|
+
export function reportCacheWriteFailure(err) {
|
|
64
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
65
|
+
console.error(`[microsoft-teams-mcp] could not cache the access token (${detail}); continuing ` +
|
|
66
|
+
'without the cache — every restart will re-capture from the browser.');
|
|
67
|
+
}
|
package/dist/tools/activity.js
CHANGED
|
@@ -1,31 +1,167 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
1
2
|
import { toolAnnotations } from '@chrischall/mcp-utils';
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
3
|
+
import { htmlToText } from '../model.js';
|
|
4
|
+
import { arrivalMs } from './conversation.js';
|
|
5
|
+
import { sinceCutoff, DEFAULT_SINCE_DAYS, MAX_SINCE_DAYS } from './confirm.js';
|
|
4
6
|
import { limitArg, trimRows } from './limit.js';
|
|
5
|
-
|
|
7
|
+
import { wrapApiError } from './errors.js';
|
|
8
|
+
import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
|
|
9
|
+
/** The chat-service conversation that holds the Activity feed. */
|
|
10
|
+
export const ACTIVITY_FEED_ID = '48:notifications';
|
|
11
|
+
const MAX_ROWS = 200;
|
|
12
|
+
/** Feed entries read before giving up — five pages; the real bound is `since_days`. */
|
|
13
|
+
const MAX_RAW_ENTRIES = 1000;
|
|
14
|
+
const MAX_PREVIEW_CHARS = 200;
|
|
15
|
+
export const ACTIVITY_KINDS = ['mention', 'reaction', 'reply', 'meeting', 'call', 'other'];
|
|
16
|
+
/** `activityType` → the bucket the `kinds` filter and each row's `kind` use. */
|
|
17
|
+
const KIND_OF_TYPE = {
|
|
18
|
+
mention: 'mention',
|
|
19
|
+
mentionInChat: 'mention',
|
|
20
|
+
reaction: 'reaction',
|
|
21
|
+
reactionInChat: 'reaction',
|
|
22
|
+
reply: 'reply',
|
|
23
|
+
replyToReply: 'reply',
|
|
24
|
+
// Every msGraph entry seen live was a private-meeting notice
|
|
25
|
+
// (privateMeetingCreated / Updated / Forwarded / …).
|
|
26
|
+
msGraph: 'meeting',
|
|
27
|
+
call: 'call',
|
|
28
|
+
};
|
|
29
|
+
export function activityKind(type) {
|
|
30
|
+
return Object.hasOwn(KIND_OF_TYPE, type) ? KIND_OF_TYPE[type] : 'other';
|
|
31
|
+
}
|
|
32
|
+
/** `properties.activity` as an object — it arrives as a JSON string or already parsed. */
|
|
33
|
+
function activityOf(m) {
|
|
34
|
+
const raw = m.properties?.activity;
|
|
35
|
+
let value = raw;
|
|
36
|
+
if (typeof raw === 'string') {
|
|
37
|
+
try {
|
|
38
|
+
value = JSON.parse(raw);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
|
|
45
|
+
}
|
|
46
|
+
/** A wire value as a non-empty string (ids can arrive as numbers), else undefined. */
|
|
47
|
+
function str(v) {
|
|
48
|
+
if (typeof v === 'string')
|
|
49
|
+
return v === '' ? undefined : v;
|
|
50
|
+
if (typeof v === 'number' && Number.isFinite(v))
|
|
51
|
+
return String(v);
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
function isoOrUndefined(v) {
|
|
55
|
+
const s = str(v);
|
|
56
|
+
if (s === undefined)
|
|
57
|
+
return undefined;
|
|
58
|
+
const ms = /^\d+$/.test(s) ? Number(s) : Date.parse(s);
|
|
59
|
+
return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined;
|
|
60
|
+
}
|
|
61
|
+
function clip(text) {
|
|
62
|
+
return text.length <= MAX_PREVIEW_CHARS ? text : `${text.slice(0, MAX_PREVIEW_CHARS - 1).trimEnd()}…`;
|
|
63
|
+
}
|
|
64
|
+
/** One feed entry as a row, or `undefined` for a deleted entry or one with no activity payload. */
|
|
65
|
+
export function activityRow(m) {
|
|
66
|
+
if (m.properties?.deletetime)
|
|
67
|
+
return undefined;
|
|
68
|
+
const a = activityOf(m);
|
|
69
|
+
if (a === undefined)
|
|
70
|
+
return undefined;
|
|
71
|
+
const type = str(a.activityType) ?? '';
|
|
72
|
+
const replyChain = str(a.sourceReplyChainId);
|
|
73
|
+
const isread = m.properties?.isread;
|
|
74
|
+
return {
|
|
75
|
+
id: m.id,
|
|
76
|
+
time: isoOrUndefined(a.activityTimestamp) ?? isoOrUndefined(m.originalarrivaltime),
|
|
77
|
+
kind: activityKind(type),
|
|
78
|
+
type,
|
|
79
|
+
subtype: str(a.activitySubtype) ?? '',
|
|
80
|
+
read: isread === true || isread === 'true',
|
|
81
|
+
from: str(a.sourceUserImDisplayName),
|
|
82
|
+
where: {
|
|
83
|
+
conversation_id: str(a.sourceThreadId),
|
|
84
|
+
title: str(a.sourceThreadTopic),
|
|
85
|
+
type: str(a.sourceThreadType),
|
|
86
|
+
},
|
|
87
|
+
message_id: str(a.sourceMessageId),
|
|
88
|
+
...(replyChain !== undefined ? { reply_chain_id: replyChain } : {}),
|
|
89
|
+
preview: clip(htmlToText(str(a.messagePreview) ?? '')),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
const newestFirst = (a, b) => (b.time ?? '').localeCompare(a.time ?? '');
|
|
93
|
+
export function registerActivityTools(server, { chatsvc }) {
|
|
6
94
|
server.registerTool('teams_get_activity', {
|
|
7
95
|
title: 'Read the Activity feed',
|
|
8
|
-
description: '
|
|
9
|
-
'
|
|
10
|
-
'
|
|
11
|
-
'
|
|
12
|
-
'
|
|
96
|
+
description: 'Read the Teams Activity feed (the bell icon) — mentions, reactions, replies, meeting ' +
|
|
97
|
+
'notices and missed calls across every chat and channel — newest first, through the ' +
|
|
98
|
+
'Teams chat-service API, so it works without the Activity view (or any particular view) ' +
|
|
99
|
+
'open in the browser. Each row has id, time (ISO 8601), kind (mention, reaction, reply, ' +
|
|
100
|
+
'meeting, call or other) with the raw type/subtype, read, from (who did it), where ' +
|
|
101
|
+
'(conversation_id, title, type), message_id, reply_chain_id (a channel thread\'s root, when there is one), ' +
|
|
102
|
+
'and a plain-text preview (at most 200 characters). Pass where.conversation_id to ' +
|
|
103
|
+
'teams_read_conversation to read the message in context. unread_only keeps rows the user ' +
|
|
104
|
+
'has not seen; kinds narrows to some buckets; since_days (default 14) sets how far back ' +
|
|
105
|
+
'to look. This does NOT mark anything read — the user\'s Activity badge is unaffected.' +
|
|
13
106
|
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
14
107
|
annotations: toolAnnotations({ readOnly: true, openWorld: true }),
|
|
15
|
-
inputSchema: {
|
|
16
|
-
|
|
108
|
+
inputSchema: {
|
|
109
|
+
unread_only: z
|
|
110
|
+
.boolean()
|
|
111
|
+
.optional()
|
|
112
|
+
.describe('Only return activity the user has not seen yet (default false). Never marks it read.'),
|
|
113
|
+
kinds: z
|
|
114
|
+
.array(z.enum(ACTIVITY_KINDS))
|
|
115
|
+
.min(1)
|
|
116
|
+
.optional()
|
|
117
|
+
.describe('Only these kinds of activity (default all): mention (incl. @team / @everyone), reaction, ' +
|
|
118
|
+
'reply, meeting (meeting invitations and updates), call (missed calls and meeting nudges), other.'),
|
|
119
|
+
since_days: z
|
|
120
|
+
.number()
|
|
121
|
+
.int()
|
|
122
|
+
.min(1)
|
|
123
|
+
.max(MAX_SINCE_DAYS)
|
|
124
|
+
.optional()
|
|
125
|
+
.describe(`Only activity from the last since_days days (default ${DEFAULT_SINCE_DAYS}, max ${MAX_SINCE_DAYS}).`),
|
|
126
|
+
limit: limitArg(MAX_ROWS, 'activity rows'),
|
|
127
|
+
},
|
|
128
|
+
}, async ({ unread_only, kinds, since_days, limit }) => {
|
|
17
129
|
try {
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
:
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
}
|
|
130
|
+
const cutoff = sinceCutoff(since_days);
|
|
131
|
+
let scanCapped = false;
|
|
132
|
+
const entries = await chatsvc.getMessages(ACTIVITY_FEED_ID, {
|
|
133
|
+
max: MAX_RAW_ENTRIES,
|
|
134
|
+
stopAt: (m) => {
|
|
135
|
+
const at = arrivalMs(m);
|
|
136
|
+
return Number.isFinite(at) && at < cutoff;
|
|
137
|
+
},
|
|
138
|
+
onCapped: () => {
|
|
139
|
+
scanCapped = true;
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
const wanted = kinds !== undefined ? new Set(kinds) : undefined;
|
|
143
|
+
const rows = entries
|
|
144
|
+
.map(activityRow)
|
|
145
|
+
.filter((r) => r !== undefined)
|
|
146
|
+
.filter((r) => r.time === undefined || Date.parse(r.time) >= cutoff)
|
|
147
|
+
.filter((r) => !unread_only || !r.read)
|
|
148
|
+
.filter((r) => wanted === undefined || wanted.has(r.kind))
|
|
149
|
+
.sort(newestFirst);
|
|
150
|
+
return untrustedResult({
|
|
151
|
+
...trimRows(rows, limit, 'start', MAX_ROWS),
|
|
152
|
+
...(scanCapped
|
|
153
|
+
? {
|
|
154
|
+
scan_capped: {
|
|
155
|
+
entries_read: MAX_RAW_ENTRIES,
|
|
156
|
+
hint: `Only the newest ${MAX_RAW_ENTRIES} feed entries were read, so older activity inside ` +
|
|
157
|
+
'since_days may be missing; pass a smaller since_days to look at a shorter window.',
|
|
158
|
+
},
|
|
159
|
+
}
|
|
160
|
+
: {}),
|
|
161
|
+
});
|
|
26
162
|
}
|
|
27
163
|
catch (err) {
|
|
28
|
-
throw
|
|
164
|
+
throw wrapApiError(err, 'read the Activity feed');
|
|
29
165
|
}
|
|
30
166
|
});
|
|
31
167
|
}
|