@chrischall/microsoft-teams-mcp 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +241 -33
  4. package/dist/attachments.js +238 -0
  5. package/dist/auth-fetchproxy.js +7 -6
  6. package/dist/browser-open.js +138 -0
  7. package/dist/bundle.js +6840 -3949
  8. package/dist/capture-feedback.js +283 -0
  9. package/dist/chatsvc.js +132 -7
  10. package/dist/compose.js +9 -1
  11. package/dist/file-upload.js +335 -0
  12. package/dist/index.js +11 -1
  13. package/dist/model.js +1 -0
  14. package/dist/presence.js +120 -0
  15. package/dist/profile.js +182 -0
  16. package/dist/recap-auth.js +6 -4
  17. package/dist/recap.js +3 -1
  18. package/dist/sender-email.js +147 -0
  19. package/dist/sharepoint-auth.js +42 -21
  20. package/dist/sharepoint.js +150 -3
  21. package/dist/substrate-auth.js +8 -7
  22. package/dist/substrate.js +98 -4
  23. package/dist/tools/attach.js +167 -0
  24. package/dist/tools/attachment.js +3 -1
  25. package/dist/tools/conversation.js +14 -5
  26. package/dist/tools/edit.js +42 -14
  27. package/dist/tools/errors.js +10 -11
  28. package/dist/tools/export.js +30 -3
  29. package/dist/tools/format.js +29 -6
  30. package/dist/tools/group-chat.js +349 -33
  31. package/dist/tools/healthcheck.js +23 -9
  32. package/dist/tools/mention-check.js +225 -0
  33. package/dist/tools/people.js +149 -39
  34. package/dist/tools/profile.js +67 -0
  35. package/dist/tools/send.js +134 -37
  36. package/dist/tools/sender-email-arg.js +37 -0
  37. package/dist/tools/token-status.js +97 -0
  38. package/dist/tools/unread.js +3 -2
  39. package/dist/tools/upload-slots.js +51 -0
  40. package/dist/version.js +1 -1
  41. package/mint.yaml +19 -0
  42. package/package.json +4 -1
  43. package/server.json +30 -2
  44. package/skills/teams-fpx/references/teams-env.sh +1 -1
@@ -0,0 +1,335 @@
1
+ /**
2
+ * Uploading an attached file where Teams keeps it, sharing it with the chat,
3
+ * and the `properties.files` file cards that make it show in the message.
4
+ *
5
+ * Where Teams puts a file (the owner's spec, mirroring the Teams client):
6
+ * - a chat (1:1, group, meeting, the self-chat): the sender's OneDrive, in
7
+ * the "Microsoft Teams Chat Files" folder, then shared with the chat's
8
+ * members;
9
+ * - a channel: the team's SharePoint site, default library ("Shared
10
+ * Documents"), in the channel's folder; team members already have access.
11
+ *
12
+ * Wire design — the SharePoint "vroom" v2.0 API with the SharePoint token this
13
+ * server already captures for downloads (`sharepoint.ts`; `aud` = SharePoint,
14
+ * one token serves every host of the tenant — verified live 2026-11-09 for
15
+ * reads). Executed live 2026-12-01 (`scripts/manual-send-attachment.mjs`):
16
+ * `me/drive`, the small PUT (69 B), the upload session (4.5 MiB) and the
17
+ * file cards, in the self-chat; and `invite` to the one other member of a 1:1
18
+ * chat, which returned success. Not yet run live: the channel rows (the team
19
+ * site url key below is still unverified), and a group chat's invite.
20
+ *
21
+ * GET https://{tenant}-my.sharepoint.com/_api/v2.0/me/drive → {id, webUrl} (OneDrive)
22
+ * GET {teamSiteUrl}/_api/v2.0/drive → {id, webUrl} (channel)
23
+ * PUT {siteUrl}/_api/v2.0/drives/{id}/root:/{folder}/{name}:/content?@microsoft.graph.conflictBehavior=rename
24
+ * (files up to {@link SIMPLE_UPLOAD_MAX}) → driveItem
25
+ * POST {siteUrl}/_api/v2.0/drives/{id}/root:/{folder}/{name}:/createUploadSession → {uploadUrl}
26
+ * PUT {uploadUrl} in {@link CHUNK_BYTES} chunks, Content-Range, NO bearer (pre-authenticated)
27
+ * POST {siteUrl}/_api/v2.0/drives/{id}/items/{itemId}/invite {recipients:[{objectId}], roles:["read"], …}
28
+ *
29
+ * The file card shape mirrors what received messages carry in
30
+ * `properties.files` (keys recorded live in docs/plans/2026-10-10-chatsvc-api.md:
31
+ * fileName, fileType, title, objectUrl, baseUrl, id, itemid, type, state,
32
+ * fileInfo{fileUrl,itemId,serverRelativeUrl,shareId,shareUrl,siteUrl}) — the
33
+ * values this writes for them were inferred, and Teams stored them unchanged
34
+ * and rendered them as file cards on 2026-12-01.
35
+ */
36
+ import { fetchBounded, McpToolError, readEnvVar } from '@chrischall/mcp-utils';
37
+ import { isSharePointHost } from './bridge-scope.js';
38
+ /** The OneDrive folder Teams keeps chat files in. */
39
+ export const CHAT_FILES_FOLDER = 'Microsoft Teams Chat Files';
40
+ /** Largest file sent in one PUT; bigger ones go through an upload session. */
41
+ export const SIMPLE_UPLOAD_MAX = 4 * 1024 * 1024;
42
+ /** Upload-session chunk: a multiple of 320 KiB, as the API requires. */
43
+ export const CHUNK_BYTES = 10 * 320 * 1024;
44
+ /** Per-chunk deadline. */
45
+ const CHUNK_TIMEOUT_MS = 120_000;
46
+ /** `contoso.sharepoint.com` / `contoso-my.sharepoint.com` → `contoso-my.sharepoint.com`. */
47
+ function myHostOf(host) {
48
+ const h = host.toLowerCase();
49
+ if (/-my\.sharepoint\.com$/.test(h))
50
+ return h;
51
+ const m = /^([a-z0-9][a-z0-9-]*)\.sharepoint\.com$/.exec(h);
52
+ return m ? `${m[1]}-my.sharepoint.com` : h;
53
+ }
54
+ /**
55
+ * The OneDrive a chat's files go to: `TEAMS_ONEDRIVE_HOST`, else the OneDrive
56
+ * host of a SharePoint host the bridge has already granted (a `-my` one
57
+ * first). Network-free, so a preview can refuse before anything is uploaded.
58
+ */
59
+ export function oneDriveDestination(env, knownHosts) {
60
+ const set = readEnvVar('TEAMS_ONEDRIVE_HOST', { env });
61
+ if (set !== undefined) {
62
+ const h = set.trim().toLowerCase().replace(/^https:\/\//, '').replace(/\/.*$/, '');
63
+ if (!isSharePointHost(h)) {
64
+ throw new McpToolError(`TEAMS_ONEDRIVE_HOST "${set}" is not a *.sharepoint.com host.`, {
65
+ kind: 'unknown',
66
+ hint: 'Set it to your OneDrive host, e.g. contoso-my.sharepoint.com.',
67
+ });
68
+ }
69
+ return { kind: 'onedrive', host: h, folder: CHAT_FILES_FOLDER };
70
+ }
71
+ const hosts = knownHosts.map((h) => h.toLowerCase()).filter(isSharePointHost);
72
+ const host = hosts.find((h) => h.endsWith('-my.sharepoint.com')) ?? hosts[0];
73
+ if (host === undefined) {
74
+ throw new McpToolError('Cannot tell which OneDrive to upload the file to: no SharePoint host is known yet and TEAMS_ONEDRIVE_HOST is not set.', {
75
+ kind: 'no_credential',
76
+ hint: 'Set TEAMS_ONEDRIVE_HOST to your OneDrive host (contoso-my.sharepoint.com — open OneDrive in the browser to see it), ' +
77
+ 'or fetch any shared file once with teams_get_attachment so the server learns it. Nothing was uploaded or sent.',
78
+ });
79
+ }
80
+ return { kind: 'onedrive', host: myHostOf(host), folder: CHAT_FILES_FOLDER };
81
+ }
82
+ /** A thread property that should hold the team's SharePoint site url (UNVERIFIED key: see the module note). */
83
+ const SITE_KEYS = ['sharepointSiteUrl', 'spoSiteUrl'];
84
+ /**
85
+ * A channel's files destination: the team's SharePoint site, read from the
86
+ * channel's or its team's thread properties, and the channel's name as the
87
+ * folder ("General" for the team's own thread). The property key is not
88
+ * confirmed live, so a thread without it is a clear refusal, never a guess.
89
+ */
90
+ export function channelDestination(channel, all, channelName) {
91
+ const tp = channel.threadProperties ?? {};
92
+ const team = tp.spaceId !== undefined ? all.find((c) => c.id === tp.spaceId) : undefined;
93
+ const raw = [channel, team]
94
+ .flatMap((c) => SITE_KEYS.map((k) => c?.threadProperties?.[k]))
95
+ .find((v) => typeof v === 'string' && v !== '');
96
+ let siteUrl;
97
+ if (raw !== undefined) {
98
+ try {
99
+ const u = new URL(raw);
100
+ if (u.protocol === 'https:' && isSharePointHost(u.hostname))
101
+ siteUrl = `${u.origin}${u.pathname.replace(/\/+$/, '')}`;
102
+ }
103
+ catch {
104
+ siteUrl = undefined;
105
+ }
106
+ }
107
+ if (siteUrl === undefined) {
108
+ throw new McpToolError("Cannot attach files in this channel: its team's SharePoint site is not on the channel's details.", {
109
+ kind: 'unknown',
110
+ hint: 'Channel attachments need the team site Teams lists for the channel (not found here — this part is not yet verified ' +
111
+ 'against a live tenant). Send the files in a chat instead, or post a link to them. Nothing was uploaded or sent.',
112
+ });
113
+ }
114
+ return { kind: 'channel', siteUrl, folder: channelName };
115
+ }
116
+ /** Encode each path segment, keeping the slashes. */
117
+ const encodePath = (p) => p.split('/').map(encodeURIComponent).join('/');
118
+ /** The site of a library: its web url without the library segment. */
119
+ function siteOf(driveWebUrl) {
120
+ return driveWebUrl.replace(/\/+$/, '').replace(/\/[^/]+$/, '');
121
+ }
122
+ /** The extension of a name, lower case, no dot. */
123
+ function extOf(name) {
124
+ const dot = name.lastIndexOf('.');
125
+ return dot > 0 ? name.slice(dot + 1).toLowerCase() : '';
126
+ }
127
+ const GUID = /\{?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\}?/i;
128
+ const describeDest = (d) => d.kind === 'onedrive' ? `your OneDrive (${d.host}, "${d.folder}")` : `the channel folder "${d.folder}" on ${d.siteUrl}`;
129
+ export class SharePointUploader {
130
+ #sp;
131
+ #fetchImpl;
132
+ /** Library per destination: one discovery per process. */
133
+ #drives = new Map();
134
+ constructor(sp, opts = {}) {
135
+ this.#sp = sp;
136
+ this.#fetchImpl = opts.fetchImpl ?? ((input, init) => fetch(input, init));
137
+ }
138
+ async upload(dest, file) {
139
+ const drive = await this.#drive(dest);
140
+ const site = siteOf(drive.webUrl);
141
+ const itemPath = `${site}/_api/v2.0/drives/${encodeURIComponent(drive.id)}/root:/${encodePath(dest.folder)}/${encodeURIComponent(file.fileName)}:`;
142
+ const item = file.bytes.length <= SIMPLE_UPLOAD_MAX
143
+ ? await this.#simple(itemPath, file, dest)
144
+ : await this.#session(itemPath, file, dest);
145
+ return this.#uploaded(item, drive, dest, file);
146
+ }
147
+ async share(file, objectIds) {
148
+ if (objectIds.length === 0)
149
+ return;
150
+ const url = `${file.siteUrl}/_api/v2.0/drives/${encodeURIComponent(file.driveId)}/items/${encodeURIComponent(file.itemId)}/invite`;
151
+ const r = await this.#sp.spRequest(url, {
152
+ method: 'POST',
153
+ headers: { 'content-type': 'application/json' },
154
+ body: JSON.stringify({
155
+ requireSignIn: true,
156
+ sendInvitation: false,
157
+ roles: ['read'],
158
+ recipients: objectIds.map((objectId) => ({ objectId })),
159
+ }),
160
+ });
161
+ if (r.status >= 200 && r.status < 300)
162
+ return;
163
+ throw await this.#refused(r.status, `share "${file.name}" with the chat's members`, 'permission to share files with people in your organisation (Sites.Manage / AllSites.Manage, and a tenant sharing policy that allows it)');
164
+ }
165
+ /** The library a destination writes to: `{id, webUrl}`. */
166
+ #drive(dest) {
167
+ const key = dest.kind === 'onedrive' ? `od:${dest.host}` : `ch:${dest.siteUrl}`;
168
+ let p = this.#drives.get(key);
169
+ if (p === undefined) {
170
+ p = this.#discover(dest);
171
+ this.#drives.set(key, p);
172
+ p.catch(() => this.#drives.delete(key));
173
+ }
174
+ return p;
175
+ }
176
+ async #discover(dest) {
177
+ const url = dest.kind === 'onedrive'
178
+ ? `https://${dest.host}/_api/v2.0/me/drive?$select=id,webUrl`
179
+ : `${dest.siteUrl}/_api/v2.0/drive?$select=id,webUrl`;
180
+ const r = await this.#sp.spRequest(url, { method: 'GET' });
181
+ if (r.status < 200 || r.status >= 300) {
182
+ throw await this.#refused(r.status, `find ${describeDest(dest)}`, writeScopeFor(dest));
183
+ }
184
+ const d = parse(r.body);
185
+ if (typeof d.id !== 'string' || typeof d.webUrl !== 'string') {
186
+ throw new McpToolError(`SharePoint did not say where ${describeDest(dest)} is.`, { kind: 'http' });
187
+ }
188
+ return { id: d.id, webUrl: d.webUrl.replace(/\/+$/, '') };
189
+ }
190
+ async #simple(itemPath, file, dest) {
191
+ const r = await this.#sp.spRequest(`${itemPath}/content?@microsoft.graph.conflictBehavior=rename`, {
192
+ method: 'PUT',
193
+ headers: { 'content-type': file.mimeType },
194
+ body: file.bytes,
195
+ });
196
+ if (r.status < 200 || r.status >= 300)
197
+ throw await this.#refused(r.status, `save "${file.fileName}" to ${describeDest(dest)}`, writeScopeFor(dest));
198
+ return parse(r.body);
199
+ }
200
+ async #session(itemPath, file, dest) {
201
+ const r = await this.#sp.spRequest(`${itemPath}/createUploadSession`, {
202
+ method: 'POST',
203
+ headers: { 'content-type': 'application/json' },
204
+ body: JSON.stringify({ item: { '@microsoft.graph.conflictBehavior': 'rename' } }),
205
+ });
206
+ if (r.status < 200 || r.status >= 300)
207
+ throw await this.#refused(r.status, `start uploading "${file.fileName}" to ${describeDest(dest)}`, writeScopeFor(dest));
208
+ const uploadUrl = parse(r.body).uploadUrl;
209
+ let target;
210
+ try {
211
+ target = typeof uploadUrl === 'string' ? new URL(uploadUrl) : undefined;
212
+ }
213
+ catch {
214
+ target = undefined;
215
+ }
216
+ if (target === undefined || target.protocol !== 'https:' || !isSharePointHost(target.hostname)) {
217
+ throw new McpToolError('SharePoint returned an upload session address that is not a SharePoint https url; nothing was uploaded.', { kind: 'http' });
218
+ }
219
+ const total = file.bytes.length;
220
+ for (let start = 0; start < total; start += CHUNK_BYTES) {
221
+ const end = Math.min(start + CHUNK_BYTES, total) - 1;
222
+ const res = await fetchBounded(target.toString(), {
223
+ method: 'PUT',
224
+ headers: { 'content-range': `bytes ${start}-${end}/${total}`, 'content-length': String(end - start + 1) },
225
+ body: file.bytes.subarray(start, end + 1),
226
+ redirect: 'error',
227
+ }, { read: 'text', service: 'SharePoint', timeoutMs: CHUNK_TIMEOUT_MS, fetchImpl: this.#fetchImpl });
228
+ if (res.status === 202)
229
+ continue;
230
+ if (res.status === 200 || res.status === 201)
231
+ return parse(res.body);
232
+ // Abandon the session (best effort) so no half-file lingers.
233
+ await fetchBounded(target.toString(), { method: 'DELETE', redirect: 'error' }, { read: 'none', fetchImpl: this.#fetchImpl }).catch(() => { });
234
+ throw new McpToolError(`SharePoint refused part of "${file.fileName}" (HTTP ${res.status}); nothing was sent.`, {
235
+ kind: 'http',
236
+ status: res.status,
237
+ hint: 'Retry; a 413 or 416 means the upload session was lost.',
238
+ });
239
+ }
240
+ throw new McpToolError(`SharePoint never confirmed the upload of "${file.fileName}"; nothing was sent.`, { kind: 'http' });
241
+ }
242
+ #uploaded(item, drive, dest, file) {
243
+ const uniqueId = item.sharepointIds?.listItemUniqueId ?? GUID.exec(item.eTag ?? '')?.[1] ?? GUID.exec(item.cTag ?? '')?.[1];
244
+ if (typeof item.id !== 'string' || uniqueId === undefined) {
245
+ throw new McpToolError(`SharePoint stored "${file.fileName}" but did not return its id, so it cannot be attached; nothing was sent.`, {
246
+ kind: 'http',
247
+ hint: `The file is in ${describeDest(dest)}; remove it there if it is not wanted.`,
248
+ });
249
+ }
250
+ const name = typeof item.name === 'string' && item.name !== '' ? item.name : file.fileName;
251
+ const objectUrl = `${drive.webUrl}/${encodePath(dest.folder)}/${encodeURIComponent(name)}`;
252
+ return {
253
+ name,
254
+ size: typeof item.size === 'number' ? item.size : file.bytes.length,
255
+ fileType: extOf(name),
256
+ driveId: drive.id,
257
+ itemId: item.id,
258
+ uniqueId: uniqueId.toLowerCase(),
259
+ siteUrl: siteOf(drive.webUrl),
260
+ objectUrl,
261
+ webUrl: typeof item.webUrl === 'string' ? item.webUrl : objectUrl,
262
+ };
263
+ }
264
+ /** The error for a refused SharePoint call; a 401/403 names the permission it needed and the token's scopes. */
265
+ async #refused(status, what, needed) {
266
+ if (status === 401 || status === 403) {
267
+ const held = await this.#sp.grantedScopes().catch(() => undefined);
268
+ return new McpToolError(`SharePoint refused to ${what} (${status}): this needs ${needed}.`, {
269
+ kind: status === 401 ? 'credential_rejected' : 'http',
270
+ status,
271
+ hint: (held !== undefined ? `The captured SharePoint token carries: ${held}. ` : '') +
272
+ 'Nothing was sent. Reload your Teams tab (so a fresh token is captured) and retry; if it is refused again, the account or tenant does not allow it.',
273
+ });
274
+ }
275
+ if (status === 404)
276
+ return new McpToolError(`SharePoint could not ${what}: not found (404).`, { kind: 'http', status });
277
+ if (status === 507)
278
+ return new McpToolError(`SharePoint could not ${what}: the storage is full (507).`, { kind: 'http', status });
279
+ return new McpToolError(`SharePoint could not ${what} (HTTP ${status}). Nothing was sent.`, {
280
+ kind: 'http',
281
+ status,
282
+ ...(status >= 500 || status === 429 ? { hint: 'Retry shortly.' } : {}),
283
+ });
284
+ }
285
+ }
286
+ /** The delegated permission a write to `dest` needs, for the 401/403 message. */
287
+ function writeScopeFor(dest) {
288
+ return dest.kind === 'onedrive'
289
+ ? 'write access to your OneDrive (delegated permission MyFiles.Write)'
290
+ : "write access to the team's SharePoint site (delegated permission AllSites.Write)";
291
+ }
292
+ function parse(body) {
293
+ try {
294
+ return JSON.parse(body);
295
+ }
296
+ catch {
297
+ throw new McpToolError('SharePoint returned a response that is not JSON.', { kind: 'http' });
298
+ }
299
+ }
300
+ /**
301
+ * `properties.files` for a message carrying these files: a JSON STRING, as
302
+ * every `properties.*` value is, of Teams file cards. The keys are those
303
+ * received messages carry (docs/plans/2026-10-10-chatsvc-api.md); the
304
+ * constant values (`version`, `state`, `permissionScope`, `fileChicletState`)
305
+ * are inferred; Teams kept them as written and rendered the cards (live
306
+ * 2026-12-01).
307
+ */
308
+ export function filesProperty(files) {
309
+ return JSON.stringify(files.map((f) => ({
310
+ '@type': 'http://schema.skype.com/File',
311
+ version: 2,
312
+ id: f.uniqueId,
313
+ baseUrl: `${f.siteUrl}/`,
314
+ type: f.fileType,
315
+ title: f.name,
316
+ state: 'active',
317
+ objectUrl: f.objectUrl,
318
+ providerData: '',
319
+ itemid: f.uniqueId,
320
+ fileName: f.name,
321
+ fileType: f.fileType,
322
+ fileInfo: {
323
+ itemId: null,
324
+ fileUrl: f.objectUrl,
325
+ siteUrl: `${f.siteUrl}/`,
326
+ serverRelativeUrl: '',
327
+ shareUrl: f.webUrl,
328
+ shareId: null,
329
+ },
330
+ botFileProperties: {},
331
+ permissionScope: 'users',
332
+ filePreview: {},
333
+ fileChicletState: { serviceName: 'p2p', state: 'active' },
334
+ })));
335
+ }
package/dist/index.js CHANGED
@@ -20,9 +20,13 @@ import { registerGroupChatTools } from './tools/group-chat.js';
20
20
  import { registerActivityTools } from './tools/activity.js';
21
21
  import { registerSearchTools } from './tools/search.js';
22
22
  import { registerHealthcheckTool } from './tools/healthcheck.js';
23
+ import { registerTokenStatusTool } from './tools/token-status.js';
23
24
  import { registerExportTools } from './tools/export.js';
24
25
  import { registerTranscriptTools } from './tools/transcript.js';
25
26
  import { registerRecapTools } from './tools/recap.js';
27
+ import { registerUploadSlotTools } from './tools/upload-slots.js';
28
+ import { registerProfileTools } from './tools/profile.js';
29
+ import { SharePointUploader } from './file-upload.js';
26
30
  loadDotenvSafely();
27
31
  /**
28
32
  * Built HERE, in the caller, not inside a registrar — see office-outlook-mcp
@@ -34,11 +38,14 @@ loadDotenvSafely();
34
38
  * `SubstrateClient`, which holds the search token, and `RecapClient`, which
35
39
  * holds the meeting-recap token.
36
40
  */
41
+ const sharepoint = new SharePointClient();
37
42
  const deps = {
38
43
  chatsvc: new ChatServiceClient(),
39
- sharepoint: new SharePointClient(),
44
+ sharepoint,
40
45
  substrate: new SubstrateClient(),
41
46
  recap: new RecapClient(),
47
+ // Uploads attachments through the same SharePoint token manager.
48
+ files: new SharePointUploader(sharepoint),
42
49
  };
43
50
  await runMcp({
44
51
  name: 'microsoft-teams-mcp',
@@ -63,6 +70,9 @@ await runMcp({
63
70
  registerExportTools,
64
71
  registerTranscriptTools,
65
72
  registerRecapTools,
73
+ registerProfileTools,
74
+ registerUploadSlotTools,
66
75
  registerHealthcheckTool,
76
+ registerTokenStatusTool,
67
77
  ],
68
78
  });
package/dist/model.js CHANGED
@@ -457,6 +457,7 @@ export function normaliseMessage(m, meMri, opts = {}) {
457
457
  time,
458
458
  ...(timeLocal !== undefined ? { time_local: timeLocal } : {}),
459
459
  sender: nonEmpty(m.imdisplayname) ?? mri ?? 'unknown',
460
+ ...(mri !== undefined ? { senderMri: mri } : {}),
460
461
  fromMe: mri !== undefined && mri === meMri,
461
462
  text: htmlToText(content),
462
463
  ...(contentHtml !== undefined ? { content_html: contentHtml } : {}),
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Presence for `teams_get_profile`'s opt-in `include_presence`: the "last
3
+ * seen" and "local time" lines of the Teams profile card. Fetched only when
4
+ * asked for, never cached or stored.
5
+ *
6
+ * POST https://teams.cloud.microsoft/ups/<chat-service region>/v1/presence/getpresence/
7
+ * [Authorization: Bearer <chat-service token>] [{ mri }, …]
8
+ * → [{ mri, presence: { availability, activity, lastActiveTime?,
9
+ * calendarData?: { workingHours?: { timeZone?: { name } } } } }]
10
+ *
11
+ * NOT verified live (2026-12-02). The URL is the unified presence service
12
+ * (UPS) as the Teams web client proxies it under its own host, and the token
13
+ * is the chat-service one this server already captures — so the bearer only
14
+ * ever goes to the host it was captured on, and no new bridge scope is
15
+ * declared. If UPS refuses that token, presence reports the failure beside
16
+ * the profiles; it never fails the lookup. The response is parsed tolerantly:
17
+ * every field is optional, several spellings are read, and nothing throws on
18
+ * shape.
19
+ */
20
+ import { isTimeZone, localIsoTime } from './model.js';
21
+ import { readEnvVar } from '@chrischall/mcp-utils';
22
+ /** The presence region asked when `TEAMS_CHATSVC_REGION` is unset — the chat service's default. */
23
+ export const DEFAULT_PRESENCE_REGION = 'amer';
24
+ /**
25
+ * The presence URL, in the same region as the chat service
26
+ * (`TEAMS_CHATSVC_REGION`): New Teams proxies both under its own host by
27
+ * region. Not a separate setting, so no new configuration surface for an
28
+ * unverified endpoint.
29
+ */
30
+ export function presenceUrl(env = process.env) {
31
+ const region = readEnvVar('TEAMS_CHATSVC_REGION', { env }) ?? DEFAULT_PRESENCE_REGION;
32
+ return `https://teams.cloud.microsoft/ups/${encodeURIComponent(region)}/v1/presence/getpresence/`;
33
+ }
34
+ /** Common Windows zone names (what Exchange working hours carry) as IANA zones. */
35
+ const WINDOWS_ZONES = {
36
+ 'utc': 'UTC',
37
+ 'coordinated universal time': 'UTC',
38
+ 'hawaiian standard time': 'Pacific/Honolulu',
39
+ 'alaskan standard time': 'America/Anchorage',
40
+ 'pacific standard time': 'America/Los_Angeles',
41
+ 'us mountain standard time': 'America/Phoenix',
42
+ 'mountain standard time': 'America/Denver',
43
+ 'central standard time': 'America/Chicago',
44
+ 'eastern standard time': 'America/New_York',
45
+ 'atlantic standard time': 'America/Halifax',
46
+ 'e. south america standard time': 'America/Sao_Paulo',
47
+ 'gmt standard time': 'Europe/London',
48
+ 'greenwich standard time': 'Atlantic/Reykjavik',
49
+ 'w. europe standard time': 'Europe/Berlin',
50
+ 'romance standard time': 'Europe/Paris',
51
+ 'central europe standard time': 'Europe/Budapest',
52
+ 'central european standard time': 'Europe/Warsaw',
53
+ 'e. europe standard time': 'Europe/Chisinau',
54
+ 'fle standard time': 'Europe/Kiev',
55
+ 'gtb standard time': 'Europe/Bucharest',
56
+ 'israel standard time': 'Asia/Jerusalem',
57
+ 'south africa standard time': 'Africa/Johannesburg',
58
+ 'arabian standard time': 'Asia/Dubai',
59
+ 'india standard time': 'Asia/Kolkata',
60
+ 'singapore standard time': 'Asia/Singapore',
61
+ 'china standard time': 'Asia/Shanghai',
62
+ 'tokyo standard time': 'Asia/Tokyo',
63
+ 'aus eastern standard time': 'Australia/Sydney',
64
+ 'new zealand standard time': 'Pacific/Auckland',
65
+ };
66
+ /** A time zone as an IANA name: an IANA name as is, a known Windows name mapped, else `undefined`. */
67
+ export function zoneOf(name) {
68
+ const s = name?.trim();
69
+ if (!s)
70
+ return undefined;
71
+ const mapped = WINDOWS_ZONES[s.toLowerCase()];
72
+ if (mapped !== undefined)
73
+ return mapped;
74
+ return s.includes('/') && isTimeZone(s) ? s : undefined;
75
+ }
76
+ const obj = (v) => (v !== null && typeof v === 'object' && !Array.isArray(v) ? v : undefined);
77
+ const str = (v) => (typeof v === 'string' && v.trim() !== '' ? v.trim() : undefined);
78
+ function isoOf(v) {
79
+ const s = str(v);
80
+ if (s === undefined)
81
+ return undefined;
82
+ const ms = Date.parse(s);
83
+ // UPS uses 0001-01-01 for "never".
84
+ return Number.isFinite(ms) && ms > 0 ? new Date(ms).toISOString() : undefined;
85
+ }
86
+ function zoneName(p) {
87
+ const hours = obj(obj(p.calendarData)?.workingHours) ?? obj(p.workingHours);
88
+ const tz = hours?.timeZone ?? p.timeZone ?? p.timezone;
89
+ return str(obj(tz)?.name) ?? str(tz);
90
+ }
91
+ /**
92
+ * A presence response as one entry per person, with their local time at `now`
93
+ * when their zone is known. A bare array or `{ value: [...] }`; never throws
94
+ * on shape.
95
+ */
96
+ export function parsePresenceResponse(body, now) {
97
+ const list = Array.isArray(body) ? body : Array.isArray(obj(body)?.value) ? obj(body).value : [];
98
+ const out = [];
99
+ for (const raw of list) {
100
+ const r = obj(raw);
101
+ const mri = str(r?.mri);
102
+ if (r === undefined || mri === undefined)
103
+ continue;
104
+ const p = obj(r.presence) ?? {};
105
+ const availability = str(p.availability);
106
+ const activity = str(p.activity);
107
+ const lastSeen = isoOf(p.lastActiveTime) ?? isoOf(p.lastSeenTime) ?? isoOf(p.lastActivityTime);
108
+ const timeZone = zoneOf(zoneName(p));
109
+ const localTime = timeZone !== undefined ? localIsoTime(new Date(now).toISOString(), timeZone) : undefined;
110
+ out.push({
111
+ mri,
112
+ ...(availability !== undefined ? { availability } : {}),
113
+ ...(activity !== undefined ? { activity } : {}),
114
+ ...(lastSeen !== undefined ? { lastSeen } : {}),
115
+ ...(timeZone !== undefined ? { timeZone } : {}),
116
+ ...(localTime !== undefined ? { localTime } : {}),
117
+ });
118
+ }
119
+ return out;
120
+ }