@chrischall/microsoft-teams-mcp 0.4.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +344 -32
- package/dist/bundle.js +2216 -474
- package/dist/chatsvc.js +81 -9
- package/dist/index.js +10 -1
- package/dist/model.js +119 -15
- package/dist/network-error.js +124 -0
- package/dist/sharepoint.js +13 -3
- package/dist/substrate-auth.js +104 -0
- package/dist/substrate-token-cache.js +64 -0
- package/dist/substrate.js +326 -0
- package/dist/tools/attachment.js +5 -0
- package/dist/tools/changes.js +241 -0
- package/dist/tools/channels.js +5 -3
- package/dist/tools/chat-search.js +65 -0
- package/dist/tools/chat.js +89 -14
- package/dist/tools/confirm.js +50 -7
- package/dist/tools/conversation.js +326 -102
- package/dist/tools/cursor.js +43 -0
- package/dist/tools/format.js +135 -0
- package/dist/tools/healthcheck.js +7 -2
- package/dist/tools/listing.js +74 -10
- package/dist/tools/markread.js +246 -0
- package/dist/tools/roots.js +73 -0
- package/dist/tools/search.js +426 -0
- package/dist/tools/timezone.js +38 -0
- package/dist/tools/unread.js +140 -39
- package/dist/version.js +1 -1
- package/mint.yaml +16 -2
- package/package.json +1 -1
- package/server.json +10 -3
- package/skills/teams-fpx/SKILL.md +6 -3
package/dist/bundle.js
CHANGED
|
@@ -326,8 +326,8 @@ function defineLazy(object2, key, getter) {
|
|
|
326
326
|
configurable: true
|
|
327
327
|
});
|
|
328
328
|
}
|
|
329
|
-
function objectClone(
|
|
330
|
-
return Object.create(Object.getPrototypeOf(
|
|
329
|
+
function objectClone(obj2) {
|
|
330
|
+
return Object.create(Object.getPrototypeOf(obj2), Object.getOwnPropertyDescriptors(obj2));
|
|
331
331
|
}
|
|
332
332
|
function assignProp(target, prop, value) {
|
|
333
333
|
Object.defineProperty(target, prop, {
|
|
@@ -398,10 +398,10 @@ function mergeDefs(...defs) {
|
|
|
398
398
|
function cloneDef(schema) {
|
|
399
399
|
return mergeDefs(schema._zod.def);
|
|
400
400
|
}
|
|
401
|
-
function getElementAtPath(
|
|
401
|
+
function getElementAtPath(obj2, path) {
|
|
402
402
|
if (!path)
|
|
403
|
-
return
|
|
404
|
-
return path.reduce((acc, key) => acc?.[key],
|
|
403
|
+
return obj2;
|
|
404
|
+
return path.reduce((acc, key) => acc?.[key], obj2);
|
|
405
405
|
}
|
|
406
406
|
function promiseAllObject(promisesObj) {
|
|
407
407
|
const keys = Object.keys(promisesObj);
|
|
@@ -416,14 +416,14 @@ function promiseAllObject(promisesObj) {
|
|
|
416
416
|
}
|
|
417
417
|
function randomString(length = 10) {
|
|
418
418
|
const chars = "abcdefghijklmnopqrstuvwxyz";
|
|
419
|
-
let
|
|
419
|
+
let str3 = "";
|
|
420
420
|
for (let i = 0; i < length; i++) {
|
|
421
|
-
|
|
421
|
+
str3 += chars[Math.floor(Math.random() * chars.length)];
|
|
422
422
|
}
|
|
423
|
-
return
|
|
423
|
+
return str3;
|
|
424
424
|
}
|
|
425
|
-
function esc(
|
|
426
|
-
return JSON.stringify(
|
|
425
|
+
function esc(str3) {
|
|
426
|
+
return JSON.stringify(str3);
|
|
427
427
|
}
|
|
428
428
|
function slugify(input2) {
|
|
429
429
|
return input2.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
|
|
@@ -467,8 +467,8 @@ function numKeys(data) {
|
|
|
467
467
|
}
|
|
468
468
|
return keyCount;
|
|
469
469
|
}
|
|
470
|
-
function escapeRegex(
|
|
471
|
-
return
|
|
470
|
+
function escapeRegex(str3) {
|
|
471
|
+
return str3.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
472
472
|
}
|
|
473
473
|
function clone(inst, def, params) {
|
|
474
474
|
const cl = new inst._zod.constr(def ?? inst._zod.def);
|
|
@@ -710,13 +710,13 @@ function getSizableOrigin(input2) {
|
|
|
710
710
|
return "file";
|
|
711
711
|
return "unknown";
|
|
712
712
|
}
|
|
713
|
-
function codePointLength(
|
|
714
|
-
const units =
|
|
715
|
-
if (!highSurrogate.test(
|
|
713
|
+
function codePointLength(str3) {
|
|
714
|
+
const units = str3.length;
|
|
715
|
+
if (!highSurrogate.test(str3))
|
|
716
716
|
return units;
|
|
717
717
|
let count = units;
|
|
718
718
|
for (let i = 0; i < units - 1; i++) {
|
|
719
|
-
if ((
|
|
719
|
+
if ((str3.charCodeAt(i) & 64512) === 55296 && (str3.charCodeAt(i + 1) & 64512) === 56320) {
|
|
720
720
|
count--;
|
|
721
721
|
i++;
|
|
722
722
|
}
|
|
@@ -743,9 +743,9 @@ function parsedType(data) {
|
|
|
743
743
|
if (Array.isArray(data)) {
|
|
744
744
|
return "array";
|
|
745
745
|
}
|
|
746
|
-
const
|
|
747
|
-
if (
|
|
748
|
-
return
|
|
746
|
+
const obj2 = data;
|
|
747
|
+
if (obj2 && Object.getPrototypeOf(obj2) !== Object.prototype && "constructor" in obj2 && obj2.constructor) {
|
|
748
|
+
return obj2.constructor.name;
|
|
749
749
|
}
|
|
750
750
|
}
|
|
751
751
|
}
|
|
@@ -763,8 +763,8 @@ function issue(...args) {
|
|
|
763
763
|
}
|
|
764
764
|
return { ...iss };
|
|
765
765
|
}
|
|
766
|
-
function cleanEnum(
|
|
767
|
-
return Object.entries(
|
|
766
|
+
function cleanEnum(obj2) {
|
|
767
|
+
return Object.entries(obj2).filter(([k, _]) => {
|
|
768
768
|
return Number.isNaN(Number.parseInt(k, 10));
|
|
769
769
|
}).map((el) => el[1]);
|
|
770
770
|
}
|
|
@@ -1161,15 +1161,15 @@ function _getMessage() {
|
|
|
1161
1161
|
function _setMessage(value) {
|
|
1162
1162
|
this._zod.message = value;
|
|
1163
1163
|
}
|
|
1164
|
-
function node(
|
|
1165
|
-
if (!Object.prototype.hasOwnProperty.call(
|
|
1164
|
+
function node(obj2, key, make) {
|
|
1165
|
+
if (!Object.prototype.hasOwnProperty.call(obj2, key)) {
|
|
1166
1166
|
if (key === "__proto__") {
|
|
1167
|
-
Object.defineProperty(
|
|
1167
|
+
Object.defineProperty(obj2, key, { value: make(), writable: true, enumerable: true, configurable: true });
|
|
1168
1168
|
} else {
|
|
1169
|
-
|
|
1169
|
+
obj2[key] = make();
|
|
1170
1170
|
}
|
|
1171
1171
|
}
|
|
1172
|
-
return
|
|
1172
|
+
return obj2[key];
|
|
1173
1173
|
}
|
|
1174
1174
|
function flattenError(error62, mapper = (issue2) => issue2.message) {
|
|
1175
1175
|
const fieldErrors = {};
|
|
@@ -23727,11 +23727,11 @@ function assertCompleteRequestResourceTemplate(request) {
|
|
|
23727
23727
|
function scanXMcpHeaderDeclarations(inputSchema) {
|
|
23728
23728
|
const declarations = [];
|
|
23729
23729
|
const seenLower = /* @__PURE__ */ new Map();
|
|
23730
|
-
const visit2 = (node2, path,
|
|
23730
|
+
const visit2 = (node2, path, reachable2) => {
|
|
23731
23731
|
if (node2 === null || typeof node2 !== "object") return void 0;
|
|
23732
23732
|
const schema = node2;
|
|
23733
23733
|
if (X_MCP_HEADER_KEY in schema) {
|
|
23734
|
-
if (!
|
|
23734
|
+
if (!reachable2 || path.length === 0) return `${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;
|
|
23735
23735
|
const raw = schema[X_MCP_HEADER_KEY];
|
|
23736
23736
|
if (typeof raw !== "string" || raw.length === 0) return `${pathName(path)}: x-mcp-header MUST be a non-empty string`;
|
|
23737
23737
|
if (!RFC9110_TOKEN.test(raw)) return `${pathName(path)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;
|
|
@@ -23749,7 +23749,7 @@ function scanXMcpHeaderDeclarations(inputSchema) {
|
|
|
23749
23749
|
}
|
|
23750
23750
|
const properties = schema.properties;
|
|
23751
23751
|
if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) {
|
|
23752
|
-
const fault$1 = visit2(child, [...path, key],
|
|
23752
|
+
const fault$1 = visit2(child, [...path, key], reachable2);
|
|
23753
23753
|
if (fault$1 !== void 0) return fault$1;
|
|
23754
23754
|
}
|
|
23755
23755
|
for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) {
|
|
@@ -24258,12 +24258,12 @@ function isZodV4Schema(v) {
|
|
|
24258
24258
|
function looksLikeZodV3(v) {
|
|
24259
24259
|
return typeof v === "object" && v !== null && !("_zod" in v) && "_def" in v && typeof v._def?.typeName === "string";
|
|
24260
24260
|
}
|
|
24261
|
-
function isZodRawShape(
|
|
24262
|
-
if (typeof
|
|
24263
|
-
if (isStandardSchema(
|
|
24264
|
-
const proto = Object.getPrototypeOf(
|
|
24261
|
+
function isZodRawShape(obj2) {
|
|
24262
|
+
if (typeof obj2 !== "object" || obj2 === null) return false;
|
|
24263
|
+
if (isStandardSchema(obj2)) return false;
|
|
24264
|
+
const proto = Object.getPrototypeOf(obj2);
|
|
24265
24265
|
if (proto !== Object.prototype && proto !== null) return false;
|
|
24266
|
-
return Object.values(
|
|
24266
|
+
return Object.values(obj2).every((v) => isZodV4Schema(v));
|
|
24267
24267
|
}
|
|
24268
24268
|
function normalizeRawShapeSchema(schema) {
|
|
24269
24269
|
if (schema === void 0) return void 0;
|
|
@@ -25515,8 +25515,8 @@ var init_src_Cqbh3MYc = __esm({
|
|
|
25515
25515
|
if (notification.params.requestId === void 0) return;
|
|
25516
25516
|
this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason);
|
|
25517
25517
|
}
|
|
25518
|
-
_setupTimeout(
|
|
25519
|
-
this._timeoutInfo.set(
|
|
25518
|
+
_setupTimeout(messageId2, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
|
|
25519
|
+
this._timeoutInfo.set(messageId2, {
|
|
25520
25520
|
timeoutId: setTimeout(onTimeout, timeout),
|
|
25521
25521
|
startTime: Date.now(),
|
|
25522
25522
|
timeout,
|
|
@@ -25525,12 +25525,12 @@ var init_src_Cqbh3MYc = __esm({
|
|
|
25525
25525
|
onTimeout
|
|
25526
25526
|
});
|
|
25527
25527
|
}
|
|
25528
|
-
_resetTimeout(
|
|
25529
|
-
const info = this._timeoutInfo.get(
|
|
25528
|
+
_resetTimeout(messageId2) {
|
|
25529
|
+
const info = this._timeoutInfo.get(messageId2);
|
|
25530
25530
|
if (!info) return false;
|
|
25531
25531
|
const totalElapsed = Date.now() - info.startTime;
|
|
25532
25532
|
if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {
|
|
25533
|
-
this._timeoutInfo.delete(
|
|
25533
|
+
this._timeoutInfo.delete(messageId2);
|
|
25534
25534
|
throw new SdkError(SdkErrorCode.RequestTimeout, "Maximum total timeout exceeded", {
|
|
25535
25535
|
maxTotalTimeout: info.maxTotalTimeout,
|
|
25536
25536
|
totalElapsed
|
|
@@ -25540,11 +25540,11 @@ var init_src_Cqbh3MYc = __esm({
|
|
|
25540
25540
|
info.timeoutId = setTimeout(info.onTimeout, info.timeout);
|
|
25541
25541
|
return true;
|
|
25542
25542
|
}
|
|
25543
|
-
_cleanupTimeout(
|
|
25544
|
-
const info = this._timeoutInfo.get(
|
|
25543
|
+
_cleanupTimeout(messageId2) {
|
|
25544
|
+
const info = this._timeoutInfo.get(messageId2);
|
|
25545
25545
|
if (info) {
|
|
25546
25546
|
clearTimeout(info.timeoutId);
|
|
25547
|
-
this._timeoutInfo.delete(
|
|
25547
|
+
this._timeoutInfo.delete(messageId2);
|
|
25548
25548
|
}
|
|
25549
25549
|
}
|
|
25550
25550
|
/**
|
|
@@ -25743,20 +25743,20 @@ var init_src_Cqbh3MYc = __esm({
|
|
|
25743
25743
|
}
|
|
25744
25744
|
_onprogress(notification) {
|
|
25745
25745
|
const { progressToken, ...params } = notification.params;
|
|
25746
|
-
const
|
|
25747
|
-
const handler = this._progressHandlers.get(
|
|
25746
|
+
const messageId2 = Number(progressToken);
|
|
25747
|
+
const handler = this._progressHandlers.get(messageId2);
|
|
25748
25748
|
if (!handler) {
|
|
25749
25749
|
this._onerror(/* @__PURE__ */ new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));
|
|
25750
25750
|
return;
|
|
25751
25751
|
}
|
|
25752
|
-
const responseHandler = this._responseHandlers.get(
|
|
25753
|
-
const timeoutInfo = this._timeoutInfo.get(
|
|
25752
|
+
const responseHandler = this._responseHandlers.get(messageId2);
|
|
25753
|
+
const timeoutInfo = this._timeoutInfo.get(messageId2);
|
|
25754
25754
|
if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) try {
|
|
25755
|
-
this._resetTimeout(
|
|
25755
|
+
this._resetTimeout(messageId2);
|
|
25756
25756
|
} catch (error62) {
|
|
25757
|
-
this._responseHandlers.delete(
|
|
25758
|
-
this._progressHandlers.delete(
|
|
25759
|
-
this._cleanupTimeout(
|
|
25757
|
+
this._responseHandlers.delete(messageId2);
|
|
25758
|
+
this._progressHandlers.delete(messageId2);
|
|
25759
|
+
this._cleanupTimeout(messageId2);
|
|
25760
25760
|
responseHandler(error62);
|
|
25761
25761
|
return;
|
|
25762
25762
|
}
|
|
@@ -25769,15 +25769,15 @@ var init_src_Cqbh3MYc = __esm({
|
|
|
25769
25769
|
* else.
|
|
25770
25770
|
*/
|
|
25771
25771
|
_onresponse(response) {
|
|
25772
|
-
const
|
|
25773
|
-
const handler = this._responseHandlers.get(
|
|
25772
|
+
const messageId2 = Number(response.id);
|
|
25773
|
+
const handler = this._responseHandlers.get(messageId2);
|
|
25774
25774
|
if (handler === void 0) {
|
|
25775
25775
|
this._onerror(/* @__PURE__ */ new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));
|
|
25776
25776
|
return;
|
|
25777
25777
|
}
|
|
25778
|
-
this._responseHandlers.delete(
|
|
25779
|
-
this._cleanupTimeout(
|
|
25780
|
-
this._progressHandlers.delete(
|
|
25778
|
+
this._responseHandlers.delete(messageId2);
|
|
25779
|
+
this._cleanupTimeout(messageId2);
|
|
25780
|
+
this._progressHandlers.delete(messageId2);
|
|
25781
25781
|
if (isJSONRPCResultResponse(response)) handler(response);
|
|
25782
25782
|
else handler(ProtocolError.fromError(response.error.code, response.error.message, response.error.data));
|
|
25783
25783
|
}
|
|
@@ -25892,20 +25892,20 @@ var init_src_Cqbh3MYc = __esm({
|
|
|
25892
25892
|
throw reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason));
|
|
25893
25893
|
}
|
|
25894
25894
|
const requestAbort = codec2.era === MODERN_WIRE_REVISION && this._transport.hasPerRequestStream === true ? new AbortController() : void 0;
|
|
25895
|
-
const
|
|
25896
|
-
cleanupMessageId =
|
|
25895
|
+
const messageId2 = this._requestMessageId++;
|
|
25896
|
+
cleanupMessageId = messageId2;
|
|
25897
25897
|
const jsonrpcRequest = {
|
|
25898
25898
|
...request,
|
|
25899
25899
|
jsonrpc: "2.0",
|
|
25900
|
-
id:
|
|
25900
|
+
id: messageId2
|
|
25901
25901
|
};
|
|
25902
25902
|
if (options?.onprogress) {
|
|
25903
|
-
this._progressHandlers.set(
|
|
25903
|
+
this._progressHandlers.set(messageId2, options.onprogress);
|
|
25904
25904
|
jsonrpcRequest.params = {
|
|
25905
25905
|
...request.params,
|
|
25906
25906
|
_meta: {
|
|
25907
25907
|
...request.params?._meta,
|
|
25908
|
-
progressToken:
|
|
25908
|
+
progressToken: messageId2
|
|
25909
25909
|
}
|
|
25910
25910
|
};
|
|
25911
25911
|
}
|
|
@@ -25913,13 +25913,13 @@ var init_src_Cqbh3MYc = __esm({
|
|
|
25913
25913
|
let responseReceived = false;
|
|
25914
25914
|
const cancel = (reason) => {
|
|
25915
25915
|
if (responseReceived) return;
|
|
25916
|
-
this._progressHandlers.delete(
|
|
25916
|
+
this._progressHandlers.delete(messageId2);
|
|
25917
25917
|
if (requestAbort === void 0) {
|
|
25918
25918
|
if (request.method !== "initialize") this._transport?.send(this._envelopeOutbound({
|
|
25919
25919
|
jsonrpc: "2.0",
|
|
25920
25920
|
method: "notifications/cancelled",
|
|
25921
25921
|
params: {
|
|
25922
|
-
requestId:
|
|
25922
|
+
requestId: messageId2,
|
|
25923
25923
|
reason: String(reason)
|
|
25924
25924
|
}
|
|
25925
25925
|
}), {
|
|
@@ -25930,7 +25930,7 @@ var init_src_Cqbh3MYc = __esm({
|
|
|
25930
25930
|
} else requestAbort.abort();
|
|
25931
25931
|
reject(reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason)));
|
|
25932
25932
|
};
|
|
25933
|
-
this._responseHandlers.set(
|
|
25933
|
+
this._responseHandlers.set(messageId2, (response) => {
|
|
25934
25934
|
if (options?.signal?.aborted) return;
|
|
25935
25935
|
responseReceived = true;
|
|
25936
25936
|
if (response instanceof Error) return reject(response);
|
|
@@ -25966,7 +25966,7 @@ var init_src_Cqbh3MYc = __esm({
|
|
|
25966
25966
|
options?.signal?.addEventListener("abort", onAbort, { once: true });
|
|
25967
25967
|
const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;
|
|
25968
25968
|
const timeoutHandler = () => cancel(new SdkError(SdkErrorCode.RequestTimeout, "Request timed out", { timeout }));
|
|
25969
|
-
this._setupTimeout(
|
|
25969
|
+
this._setupTimeout(messageId2, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);
|
|
25970
25970
|
this._transport.send(outbound, {
|
|
25971
25971
|
relatedRequestId,
|
|
25972
25972
|
resumptionToken,
|
|
@@ -25974,7 +25974,7 @@ var init_src_Cqbh3MYc = __esm({
|
|
|
25974
25974
|
headers,
|
|
25975
25975
|
requestSignal: requestAbort?.signal
|
|
25976
25976
|
}).catch((error62) => {
|
|
25977
|
-
this._progressHandlers.delete(
|
|
25977
|
+
this._progressHandlers.delete(messageId2);
|
|
25978
25978
|
reject(error62);
|
|
25979
25979
|
});
|
|
25980
25980
|
}).finally(() => {
|
|
@@ -26118,7 +26118,7 @@ var init_src_Cqbh3MYc = __esm({
|
|
|
26118
26118
|
var index = header.indexOf(";");
|
|
26119
26119
|
var type = index !== -1 ? header.slice(0, index).trim() : header.trim();
|
|
26120
26120
|
if (!TYPE_REGEXP.test(type)) throw new TypeError("invalid media type");
|
|
26121
|
-
var
|
|
26121
|
+
var obj2 = new ContentType(type.toLowerCase());
|
|
26122
26122
|
if (index !== -1) {
|
|
26123
26123
|
var key;
|
|
26124
26124
|
var match;
|
|
@@ -26133,16 +26133,16 @@ var init_src_Cqbh3MYc = __esm({
|
|
|
26133
26133
|
value = value.slice(1, -1);
|
|
26134
26134
|
if (value.indexOf("\\") !== -1) value = value.replace(QESC_REGEXP, "$1");
|
|
26135
26135
|
}
|
|
26136
|
-
|
|
26136
|
+
obj2.parameters[key] = value;
|
|
26137
26137
|
}
|
|
26138
26138
|
if (index !== header.length) throw new TypeError("invalid parameter format");
|
|
26139
26139
|
}
|
|
26140
|
-
return
|
|
26140
|
+
return obj2;
|
|
26141
26141
|
}
|
|
26142
|
-
function getcontenttype(
|
|
26142
|
+
function getcontenttype(obj2) {
|
|
26143
26143
|
var header;
|
|
26144
|
-
if (typeof
|
|
26145
|
-
else if (typeof
|
|
26144
|
+
if (typeof obj2.getHeader === "function") header = obj2.getHeader("content-type");
|
|
26145
|
+
else if (typeof obj2.headers === "object") header = obj2.headers && obj2.headers["content-type"];
|
|
26146
26146
|
if (typeof header !== "string") throw new TypeError("content-type header is missing from object");
|
|
26147
26147
|
return header;
|
|
26148
26148
|
}
|
|
@@ -26267,7 +26267,7 @@ var init_ajvProvider_CEoC_sr = __esm({
|
|
|
26267
26267
|
}
|
|
26268
26268
|
exports._ = _;
|
|
26269
26269
|
const plus = new _Code("+");
|
|
26270
|
-
function
|
|
26270
|
+
function str3(strs, ...args) {
|
|
26271
26271
|
const expr = [safeStringify(strs[0])];
|
|
26272
26272
|
let i = 0;
|
|
26273
26273
|
while (i < args.length) {
|
|
@@ -26278,7 +26278,7 @@ var init_ajvProvider_CEoC_sr = __esm({
|
|
|
26278
26278
|
optimize(expr);
|
|
26279
26279
|
return new _Code(expr);
|
|
26280
26280
|
}
|
|
26281
|
-
exports.str =
|
|
26281
|
+
exports.str = str3;
|
|
26282
26282
|
function addCodeArg(code2, arg) {
|
|
26283
26283
|
if (arg instanceof _Code) code2.push(...arg._items);
|
|
26284
26284
|
else if (arg instanceof Name) code2.push(arg);
|
|
@@ -26311,7 +26311,7 @@ var init_ajvProvider_CEoC_sr = __esm({
|
|
|
26311
26311
|
if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}`;
|
|
26312
26312
|
}
|
|
26313
26313
|
function strConcat(c1, c2) {
|
|
26314
|
-
return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 :
|
|
26314
|
+
return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str3`${c1}${c2}`;
|
|
26315
26315
|
}
|
|
26316
26316
|
exports.strConcat = strConcat;
|
|
26317
26317
|
function interpolate(x) {
|
|
@@ -26992,10 +26992,10 @@ var init_ajvProvider_CEoC_sr = __esm({
|
|
|
26992
26992
|
}
|
|
26993
26993
|
return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
|
|
26994
26994
|
}
|
|
26995
|
-
forIn(nameOrPrefix,
|
|
26996
|
-
if (this.opts.ownProperties) return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${
|
|
26995
|
+
forIn(nameOrPrefix, obj2, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
|
|
26996
|
+
if (this.opts.ownProperties) return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj2})`, forBody);
|
|
26997
26997
|
const name = this._scope.toName(nameOrPrefix);
|
|
26998
|
-
return this._for(new ForIter("in", varKind, name,
|
|
26998
|
+
return this._for(new ForIter("in", varKind, name, obj2), () => forBody(name));
|
|
26999
26999
|
}
|
|
27000
27000
|
endFor() {
|
|
27001
27001
|
return this._endBlockNode(For);
|
|
@@ -27190,21 +27190,21 @@ var init_ajvProvider_CEoC_sr = __esm({
|
|
|
27190
27190
|
return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;
|
|
27191
27191
|
}
|
|
27192
27192
|
exports.schemaRefOrVal = schemaRefOrVal;
|
|
27193
|
-
function unescapeFragment(
|
|
27194
|
-
return unescapeJsonPointer(decodeURIComponent(
|
|
27193
|
+
function unescapeFragment(str3) {
|
|
27194
|
+
return unescapeJsonPointer(decodeURIComponent(str3));
|
|
27195
27195
|
}
|
|
27196
27196
|
exports.unescapeFragment = unescapeFragment;
|
|
27197
|
-
function escapeFragment(
|
|
27198
|
-
return encodeURIComponent(escapeJsonPointer(
|
|
27197
|
+
function escapeFragment(str3) {
|
|
27198
|
+
return encodeURIComponent(escapeJsonPointer(str3));
|
|
27199
27199
|
}
|
|
27200
27200
|
exports.escapeFragment = escapeFragment;
|
|
27201
|
-
function escapeJsonPointer(
|
|
27202
|
-
if (typeof
|
|
27203
|
-
return
|
|
27201
|
+
function escapeJsonPointer(str3) {
|
|
27202
|
+
if (typeof str3 == "number") return `${str3}`;
|
|
27203
|
+
return str3.replace(/~/g, "~0").replace(/\//g, "~1");
|
|
27204
27204
|
}
|
|
27205
27205
|
exports.escapeJsonPointer = escapeJsonPointer;
|
|
27206
|
-
function unescapeJsonPointer(
|
|
27207
|
-
return
|
|
27206
|
+
function unescapeJsonPointer(str3) {
|
|
27207
|
+
return str3.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
27208
27208
|
}
|
|
27209
27209
|
exports.unescapeJsonPointer = unescapeJsonPointer;
|
|
27210
27210
|
function eachItem(xs, f) {
|
|
@@ -28090,8 +28090,8 @@ var init_ajvProvider_CEoC_sr = __esm({
|
|
|
28090
28090
|
post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
|
|
28091
28091
|
}
|
|
28092
28092
|
}
|
|
28093
|
-
function escapeJsonPtr(
|
|
28094
|
-
return
|
|
28093
|
+
function escapeJsonPtr(str3) {
|
|
28094
|
+
return str3.replace(/~/g, "~0").replace(/\//g, "~1");
|
|
28095
28095
|
}
|
|
28096
28096
|
}));
|
|
28097
28097
|
require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
@@ -28523,9 +28523,9 @@ var init_ajvProvider_CEoC_sr = __esm({
|
|
|
28523
28523
|
ok(cond) {
|
|
28524
28524
|
if (!this.allErrors) this.gen.if(cond);
|
|
28525
28525
|
}
|
|
28526
|
-
setParams(
|
|
28527
|
-
if (assign) Object.assign(this.params,
|
|
28528
|
-
else this.params =
|
|
28526
|
+
setParams(obj2, assign) {
|
|
28527
|
+
if (assign) Object.assign(this.params, obj2);
|
|
28528
|
+
else this.params = obj2;
|
|
28529
28529
|
}
|
|
28530
28530
|
block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
|
|
28531
28531
|
this.gen.block(() => {
|
|
@@ -28983,9 +28983,9 @@ var init_ajvProvider_CEoC_sr = __esm({
|
|
|
28983
28983
|
isIPV6: false
|
|
28984
28984
|
};
|
|
28985
28985
|
}
|
|
28986
|
-
function findToken(
|
|
28986
|
+
function findToken(str3, token) {
|
|
28987
28987
|
let ind = 0;
|
|
28988
|
-
for (let i = 0; i <
|
|
28988
|
+
for (let i = 0; i < str3.length; i++) if (str3[i] === token) ind++;
|
|
28989
28989
|
return ind;
|
|
28990
28990
|
}
|
|
28991
28991
|
function removeDotSegments(path) {
|
|
@@ -29500,7 +29500,7 @@ var init_ajvProvider_CEoC_sr = __esm({
|
|
|
29500
29500
|
const util_1 = require_util();
|
|
29501
29501
|
const $dataRefSchema = require_data();
|
|
29502
29502
|
const uri_1 = require_uri();
|
|
29503
|
-
const defaultRegExp = (
|
|
29503
|
+
const defaultRegExp = (str3, flags) => new RegExp(str3, flags);
|
|
29504
29504
|
defaultRegExp.code = "new RegExp";
|
|
29505
29505
|
const META_IGNORE_OPTIONS = [
|
|
29506
29506
|
"removeAdditional",
|
|
@@ -30206,16 +30206,16 @@ var init_ajvProvider_CEoC_sr = __esm({
|
|
|
30206
30206
|
}));
|
|
30207
30207
|
require_ucs2length = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
30208
30208
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
30209
|
-
function ucs2length(
|
|
30210
|
-
const len =
|
|
30209
|
+
function ucs2length(str3) {
|
|
30210
|
+
const len = str3.length;
|
|
30211
30211
|
let length = 0;
|
|
30212
30212
|
let pos = 0;
|
|
30213
30213
|
let value;
|
|
30214
30214
|
while (pos < len) {
|
|
30215
30215
|
length++;
|
|
30216
|
-
value =
|
|
30216
|
+
value = str3.charCodeAt(pos++);
|
|
30217
30217
|
if (value >= 55296 && value <= 56319 && pos < len) {
|
|
30218
|
-
value =
|
|
30218
|
+
value = str3.charCodeAt(pos);
|
|
30219
30219
|
if ((value & 64512) === 56320) pos++;
|
|
30220
30220
|
}
|
|
30221
30221
|
}
|
|
@@ -32926,8 +32926,8 @@ var init_ajvProvider_CEoC_sr = __esm({
|
|
|
32926
32926
|
30,
|
|
32927
32927
|
31
|
|
32928
32928
|
];
|
|
32929
|
-
function date5(
|
|
32930
|
-
const matches = DATE.exec(
|
|
32929
|
+
function date5(str3) {
|
|
32930
|
+
const matches = DATE.exec(str3);
|
|
32931
32931
|
if (!matches) return false;
|
|
32932
32932
|
const year = +matches[1];
|
|
32933
32933
|
const month = +matches[2];
|
|
@@ -32942,8 +32942,8 @@ var init_ajvProvider_CEoC_sr = __esm({
|
|
|
32942
32942
|
}
|
|
32943
32943
|
const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;
|
|
32944
32944
|
function getTime(strictTimeZone) {
|
|
32945
|
-
return function time3(
|
|
32946
|
-
const matches = TIME.exec(
|
|
32945
|
+
return function time3(str3) {
|
|
32946
|
+
const matches = TIME.exec(str3);
|
|
32947
32947
|
if (!matches) return false;
|
|
32948
32948
|
const hr = +matches[1];
|
|
32949
32949
|
const min = +matches[2];
|
|
@@ -32980,8 +32980,8 @@ var init_ajvProvider_CEoC_sr = __esm({
|
|
|
32980
32980
|
const DATE_TIME_SEPARATOR = /t|\s/i;
|
|
32981
32981
|
function getDateTime(strictTimeZone) {
|
|
32982
32982
|
const time3 = getTime(strictTimeZone);
|
|
32983
|
-
return function date_time(
|
|
32984
|
-
const dateTime =
|
|
32983
|
+
return function date_time(str3) {
|
|
32984
|
+
const dateTime = str3.split(DATE_TIME_SEPARATOR);
|
|
32985
32985
|
return dateTime.length === 2 && date5(dateTime[0]) && time3(dateTime[1]);
|
|
32986
32986
|
};
|
|
32987
32987
|
}
|
|
@@ -33002,13 +33002,13 @@ var init_ajvProvider_CEoC_sr = __esm({
|
|
|
33002
33002
|
}
|
|
33003
33003
|
const NOT_URI_FRAGMENT = /\/|:/;
|
|
33004
33004
|
const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
|
|
33005
|
-
function uri(
|
|
33006
|
-
return NOT_URI_FRAGMENT.test(
|
|
33005
|
+
function uri(str3) {
|
|
33006
|
+
return NOT_URI_FRAGMENT.test(str3) && URI.test(str3);
|
|
33007
33007
|
}
|
|
33008
33008
|
const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;
|
|
33009
|
-
function byte(
|
|
33009
|
+
function byte(str3) {
|
|
33010
33010
|
BYTE.lastIndex = 0;
|
|
33011
|
-
return BYTE.test(
|
|
33011
|
+
return BYTE.test(str3);
|
|
33012
33012
|
}
|
|
33013
33013
|
const MIN_INT32 = -(2 ** 31);
|
|
33014
33014
|
const MAX_INT32 = 2 ** 31 - 1;
|
|
@@ -33022,10 +33022,10 @@ var init_ajvProvider_CEoC_sr = __esm({
|
|
|
33022
33022
|
return true;
|
|
33023
33023
|
}
|
|
33024
33024
|
const Z_ANCHOR = /[^\\]\\Z/;
|
|
33025
|
-
function regex(
|
|
33026
|
-
if (Z_ANCHOR.test(
|
|
33025
|
+
function regex(str3) {
|
|
33026
|
+
if (Z_ANCHOR.test(str3)) return false;
|
|
33027
33027
|
try {
|
|
33028
|
-
new RegExp(
|
|
33028
|
+
new RegExp(str3);
|
|
33029
33029
|
return true;
|
|
33030
33030
|
} catch (e) {
|
|
33031
33031
|
return false;
|
|
@@ -35373,9 +35373,9 @@ function redactSecrets(text) {
|
|
|
35373
35373
|
return text.replace(BEARER_RE, "$1[REDACTED]").replace(BASIC_AUTH_RE, "$1[REDACTED]").replace(SET_COOKIE_RE, "$1$2=[REDACTED]").replace(COOKIE_HEADER_RE, (_m, prefix, pairs) => `${prefix}${pairs.replace(/=[^;,\s]*/g, "=[REDACTED]")}`).replace(API_KEY_RE, "[REDACTED]").replace(GOOGLE_OAUTH_TOKEN_RE, "[REDACTED]").replace(HEADER_SECRET_RE, "$1[REDACTED]").replace(QUERY_SECRET_RE, "$1[REDACTED]").replace(OAUTH_CODE_RE, "$1[REDACTED]").replace(FORM_PASSWORD_RE, "$1[REDACTED]").replace(AWS_SIGV4_RE, "$1[REDACTED]").replace(JSON_COOKIE_DQ_RE, redactJsonCookie('"')).replace(JSON_COOKIE_SQ_RE, redactJsonCookie("'")).replace(JSON_SECRET_DQ_RE, "$1[REDACTED]$2").replace(JSON_SECRET_SQ_RE, "$1[REDACTED]$2").replace(JSON_SECRET_NUM_RE, "$1[REDACTED]").replace(JWT_RE, "[REDACTED]");
|
|
35374
35374
|
}
|
|
35375
35375
|
function truncateErrorMessage(text, max = DEFAULT_ERROR_MESSAGE_MAX) {
|
|
35376
|
-
const
|
|
35376
|
+
const str3 = text === null || text === void 0 ? "" : String(text);
|
|
35377
35377
|
const cap = Math.max(ERROR_REDACTION_INPUT_MAX, max);
|
|
35378
|
-
const redacted = redactSecrets(
|
|
35378
|
+
const redacted = redactSecrets(str3.length > cap ? str3.slice(0, cap) : str3);
|
|
35379
35379
|
if (redacted.length <= max)
|
|
35380
35380
|
return redacted;
|
|
35381
35381
|
return `${redacted.slice(0, max)}\u2026 [truncated]`;
|
|
@@ -37080,7 +37080,7 @@ var init_version = __esm({
|
|
|
37080
37080
|
"src/version.ts"() {
|
|
37081
37081
|
"use strict";
|
|
37082
37082
|
PACKAGE_NAME = "microsoft-teams-mcp";
|
|
37083
|
-
VERSION = "0.
|
|
37083
|
+
VERSION = "0.5.1";
|
|
37084
37084
|
}
|
|
37085
37085
|
});
|
|
37086
37086
|
|
|
@@ -37662,8 +37662,8 @@ function assertBase64(x, label) {
|
|
|
37662
37662
|
function base64ByteLength(s) {
|
|
37663
37663
|
if (s.length % 4 !== 0)
|
|
37664
37664
|
return null;
|
|
37665
|
-
const
|
|
37666
|
-
return s.length / 4 * 3 -
|
|
37665
|
+
const pad2 = s.endsWith("==") ? 2 : s.endsWith("=") ? 1 : 0;
|
|
37666
|
+
return s.length / 4 * 3 - pad2;
|
|
37667
37667
|
}
|
|
37668
37668
|
function assertBase64Bytes(x, label, bytes) {
|
|
37669
37669
|
assertBase64(x, label);
|
|
@@ -47591,6 +47591,73 @@ var init_sharepoint_auth = __esm({
|
|
|
47591
47591
|
}
|
|
47592
47592
|
});
|
|
47593
47593
|
|
|
47594
|
+
// src/substrate-auth.ts
|
|
47595
|
+
var substrate_auth_exports = {};
|
|
47596
|
+
__export(substrate_auth_exports, {
|
|
47597
|
+
SUBSTRATE_CAPTURE_DECL: () => SUBSTRATE_CAPTURE_DECL,
|
|
47598
|
+
SUBSTRATE_TRUST_DOMAINS: () => SUBSTRATE_TRUST_DOMAINS,
|
|
47599
|
+
captureSubstrateTokenViaFetchproxy: () => captureSubstrateTokenViaFetchproxy
|
|
47600
|
+
});
|
|
47601
|
+
async function captureSubstrateTokenViaFetchproxy(env = process.env) {
|
|
47602
|
+
const windowMs = captureWindowMs(env);
|
|
47603
|
+
const transport = createFetchproxyTransport({
|
|
47604
|
+
// Same verb set as the other two captures (`capture_request_header` beside
|
|
47605
|
+
// the always-on `fetch`); only the trusted domain differs.
|
|
47606
|
+
...createBootstrapOpts({
|
|
47607
|
+
domains: [...SUBSTRATE_TRUST_DOMAINS],
|
|
47608
|
+
bootstrap: { captureHeaders: [{ ...SUBSTRATE_CAPTURE_DECL }] }
|
|
47609
|
+
}),
|
|
47610
|
+
port: getWsPort(),
|
|
47611
|
+
fetchTimeoutMs: bridgeDeadlineMs(windowMs),
|
|
47612
|
+
captureWindowMs: windowMs,
|
|
47613
|
+
serverName: PACKAGE_NAME,
|
|
47614
|
+
version: VERSION
|
|
47615
|
+
});
|
|
47616
|
+
try {
|
|
47617
|
+
await transport.start();
|
|
47618
|
+
try {
|
|
47619
|
+
const raw = await transport.server.captureRequestHeader({ ...SUBSTRATE_CAPTURE_DECL, timeoutMs: windowMs });
|
|
47620
|
+
if (typeof raw !== "string") {
|
|
47621
|
+
throw new Error(`${SUBSTRATE_CAPTURE_DECL.host}: capture returned no header`);
|
|
47622
|
+
}
|
|
47623
|
+
const token = stripBearer(raw);
|
|
47624
|
+
if (token.length < MIN_TOKEN_LENGTH3) {
|
|
47625
|
+
throw new Error(
|
|
47626
|
+
`${SUBSTRATE_CAPTURE_DECL.host}: authorization header was present but too short to be a token (${token.length} chars)`
|
|
47627
|
+
);
|
|
47628
|
+
}
|
|
47629
|
+
return token;
|
|
47630
|
+
} catch (e) {
|
|
47631
|
+
const detail = e.message;
|
|
47632
|
+
throw new Error(
|
|
47633
|
+
`could not capture a Substrate search token from the browser (${detail}). In a signed-in teams.cloud.microsoft tab, type anything into the search box at the top and press Enter \u2014 that is what makes Teams call substrate.office.com, where the token is read from \u2014 then retry. A "not in declared set" error means the ContextMint Bridge pairing does not trust substrate.office.com yet: re-pair microsoft-teams-mcp once.`
|
|
47634
|
+
);
|
|
47635
|
+
}
|
|
47636
|
+
} finally {
|
|
47637
|
+
try {
|
|
47638
|
+
await transport.close();
|
|
47639
|
+
} catch {
|
|
47640
|
+
}
|
|
47641
|
+
}
|
|
47642
|
+
}
|
|
47643
|
+
var SUBSTRATE_CAPTURE_DECL, SUBSTRATE_TRUST_DOMAINS, MIN_TOKEN_LENGTH3;
|
|
47644
|
+
var init_substrate_auth = __esm({
|
|
47645
|
+
"src/substrate-auth.ts"() {
|
|
47646
|
+
"use strict";
|
|
47647
|
+
init_fetchproxy();
|
|
47648
|
+
init_capture_window();
|
|
47649
|
+
init_auth_fetchproxy();
|
|
47650
|
+
init_version();
|
|
47651
|
+
SUBSTRATE_CAPTURE_DECL = {
|
|
47652
|
+
host: "substrate.office.com",
|
|
47653
|
+
path: "/searchservice/*",
|
|
47654
|
+
headerName: "authorization"
|
|
47655
|
+
};
|
|
47656
|
+
SUBSTRATE_TRUST_DOMAINS = [SUBSTRATE_CAPTURE_DECL.host];
|
|
47657
|
+
MIN_TOKEN_LENGTH3 = 100;
|
|
47658
|
+
}
|
|
47659
|
+
});
|
|
47660
|
+
|
|
47594
47661
|
// src/index.ts
|
|
47595
47662
|
init_dist2();
|
|
47596
47663
|
init_version();
|
|
@@ -48286,6 +48353,16 @@ function newestActivityMs(c) {
|
|
|
48286
48353
|
const signals = [lastArrival, lastImReceivedMs(c)].filter((n) => n !== void 0 && Number.isFinite(n) && n > 0);
|
|
48287
48354
|
return signals.length === 0 ? void 0 : Math.max(...signals);
|
|
48288
48355
|
}
|
|
48356
|
+
function epochMs(raw) {
|
|
48357
|
+
const ms = typeof raw === "number" ? raw : typeof raw === "string" && /^\s*\d+\s*$/.test(raw) ? Number(raw) : NaN;
|
|
48358
|
+
return Number.isFinite(ms) && ms > 0 ? ms : void 0;
|
|
48359
|
+
}
|
|
48360
|
+
function lastChangeMs(c) {
|
|
48361
|
+
const signals = [newestActivityMs(c), epochMs(c.lastUpdatedMessageId), epochMs(c.lastUpdatedMessageVersion)].filter(
|
|
48362
|
+
(n) => n !== void 0
|
|
48363
|
+
);
|
|
48364
|
+
return signals.length === 0 ? void 0 : Math.max(...signals);
|
|
48365
|
+
}
|
|
48289
48366
|
function isUnreadCandidate(c, meMri) {
|
|
48290
48367
|
const horizon = readHorizon(c);
|
|
48291
48368
|
const last = c.lastMessage;
|
|
@@ -48312,6 +48389,10 @@ function flag(c, name) {
|
|
|
48312
48389
|
const v = c.properties?.[name];
|
|
48313
48390
|
return v === true || typeof v === "string" && v.trim().toLowerCase() === "true";
|
|
48314
48391
|
}
|
|
48392
|
+
function flagOff(c, name) {
|
|
48393
|
+
const v = c.properties?.[name];
|
|
48394
|
+
return v === false || typeof v === "string" && v.trim().toLowerCase() === "false";
|
|
48395
|
+
}
|
|
48315
48396
|
function isHiddenChannel(c) {
|
|
48316
48397
|
return c.memberProperties?.interest === "NotInterested";
|
|
48317
48398
|
}
|
|
@@ -48352,6 +48433,7 @@ function conversationSummary(c, meMri, all = []) {
|
|
|
48352
48433
|
unread,
|
|
48353
48434
|
unread_confirmed: false,
|
|
48354
48435
|
...hidden ? { hidden: true } : {},
|
|
48436
|
+
...flagOff(c, "alerts") ? { muted: true } : {},
|
|
48355
48437
|
...flag(c, "favorite") ? { favorite: true } : {},
|
|
48356
48438
|
...flag(c, "ispinned") ? { pinned: true } : {},
|
|
48357
48439
|
...lastActivity !== void 0 ? { lastActivity } : {},
|
|
@@ -48387,6 +48469,12 @@ function attr(tag, name) {
|
|
|
48387
48469
|
return m ? m[1] ?? m[2] : void 0;
|
|
48388
48470
|
}
|
|
48389
48471
|
var stripTags = (s) => s.replace(/<\/?[a-z!][^>]*>/gi, "");
|
|
48472
|
+
function tableRow(row) {
|
|
48473
|
+
const cells = [...row.matchAll(/<t[dh]\b[^>]*>([\s\S]*?)(?:<\/t[dh]\s*>|(?=<t[dh]\b)|$)/gi)].map(
|
|
48474
|
+
([, cell]) => cell.replace(/[\u0001\u0002]/g, "").replace(/<br\s*\/?>|<\/?(p|div|li|h[1-6])\b[^>]*>|\r?\n/gi, " ").trim()
|
|
48475
|
+
);
|
|
48476
|
+
return cells.length > 0 ? cells.join(" | ") : row;
|
|
48477
|
+
}
|
|
48390
48478
|
function htmlToText(html) {
|
|
48391
48479
|
let s = html.replace(/[\u0001\u0002]/g, "");
|
|
48392
48480
|
s = s.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/gi, "");
|
|
@@ -48406,6 +48494,9 @@ ${QUOTE_CLOSE}
|
|
|
48406
48494
|
if (label === "" || label === href) return href;
|
|
48407
48495
|
return `${inner} (${href})`;
|
|
48408
48496
|
});
|
|
48497
|
+
s = s.replace(/<tr\b[^>]*>([\s\S]*?)<\/tr\s*>/gi, (_whole, row) => `
|
|
48498
|
+
${tableRow(row)}
|
|
48499
|
+
`);
|
|
48409
48500
|
s = s.replace(/<br\s*\/?>/gi, "\n").replace(/<\/?(p|div|li|tr|h[1-6])\b[^>]*>/gi, "\n");
|
|
48410
48501
|
s = decodeEntities(stripTags(s));
|
|
48411
48502
|
const out = [];
|
|
@@ -48433,11 +48524,11 @@ function fileAttachments(raw) {
|
|
|
48433
48524
|
if (f === null || typeof f !== "object") continue;
|
|
48434
48525
|
const o = f;
|
|
48435
48526
|
const info = o.fileInfo && typeof o.fileInfo === "object" ? o.fileInfo : {};
|
|
48436
|
-
const
|
|
48437
|
-
const name =
|
|
48438
|
-
const type =
|
|
48439
|
-
const openUrl =
|
|
48440
|
-
const url2 =
|
|
48527
|
+
const str3 = (v) => typeof v === "string" && v !== "" ? v : void 0;
|
|
48528
|
+
const name = str3(o.fileName) ?? str3(o.title) ?? "(file)";
|
|
48529
|
+
const type = str3(o.fileType) ?? str3(o.type);
|
|
48530
|
+
const openUrl = str3(o.openUrl) ?? str3(info.shareUrl);
|
|
48531
|
+
const url2 = str3(o.objectUrl) ?? str3(info.fileUrl);
|
|
48441
48532
|
out.push({
|
|
48442
48533
|
name,
|
|
48443
48534
|
...type !== void 0 ? { type } : {},
|
|
@@ -48496,7 +48587,38 @@ function oldestFirst(messages) {
|
|
|
48496
48587
|
};
|
|
48497
48588
|
return messages.map((m, i) => ({ m, i, t: at(m) })).reverse().sort((a, b) => Number.isNaN(a.t) || Number.isNaN(b.t) ? 0 : a.t - b.t).map(({ m }) => m);
|
|
48498
48589
|
}
|
|
48499
|
-
function
|
|
48590
|
+
function isTimeZone(tz) {
|
|
48591
|
+
if (tz.trim() === "") return false;
|
|
48592
|
+
try {
|
|
48593
|
+
new Intl.DateTimeFormat("en-US", { timeZone: tz });
|
|
48594
|
+
return true;
|
|
48595
|
+
} catch {
|
|
48596
|
+
return false;
|
|
48597
|
+
}
|
|
48598
|
+
}
|
|
48599
|
+
var pad = (n, width = 2) => String(n).padStart(width, "0");
|
|
48600
|
+
function localIsoTime(iso, timeZone) {
|
|
48601
|
+
const ms = Date.parse(iso);
|
|
48602
|
+
if (Number.isNaN(ms)) return void 0;
|
|
48603
|
+
const parts = new Intl.DateTimeFormat("en-US", {
|
|
48604
|
+
timeZone,
|
|
48605
|
+
hourCycle: "h23",
|
|
48606
|
+
year: "numeric",
|
|
48607
|
+
month: "2-digit",
|
|
48608
|
+
day: "2-digit",
|
|
48609
|
+
hour: "2-digit",
|
|
48610
|
+
minute: "2-digit",
|
|
48611
|
+
second: "2-digit"
|
|
48612
|
+
}).formatToParts(new Date(ms));
|
|
48613
|
+
const get = (type) => Number(parts.find((p) => p.type === type)?.value);
|
|
48614
|
+
const millis = (ms % 1e3 + 1e3) % 1e3;
|
|
48615
|
+
const wall = Date.UTC(get("year"), get("month") - 1, get("day"), get("hour"), get("minute"), get("second"), millis);
|
|
48616
|
+
const offsetMin = Math.round((wall - ms) / 6e4);
|
|
48617
|
+
const sign2 = offsetMin < 0 ? "-" : "+";
|
|
48618
|
+
const abs = Math.abs(offsetMin);
|
|
48619
|
+
return `${pad(get("year"), 4)}-${pad(get("month"))}-${pad(get("day"))}T${pad(get("hour"))}:${pad(get("minute"))}:${pad(get("second"))}.${pad(millis, 3)}${sign2}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`;
|
|
48620
|
+
}
|
|
48621
|
+
function normaliseMessage(m, meMri, opts = {}) {
|
|
48500
48622
|
const props = m.properties ?? {};
|
|
48501
48623
|
const mri = senderMri(m.from);
|
|
48502
48624
|
const arrival = Number(m.id);
|
|
@@ -48505,9 +48627,11 @@ function normaliseMessage(m, meMri) {
|
|
|
48505
48627
|
const root = /;messageid=(\d+)/.exec(m.conversationLink ?? "")?.[1];
|
|
48506
48628
|
const content = m.content ?? "";
|
|
48507
48629
|
const reactions = reactionsOf(props.emotions, meMri);
|
|
48630
|
+
const timeLocal = opts.timeZone !== void 0 ? localIsoTime(time3, opts.timeZone) : void 0;
|
|
48508
48631
|
return {
|
|
48509
48632
|
id: m.id,
|
|
48510
48633
|
time: time3,
|
|
48634
|
+
...timeLocal !== void 0 ? { time_local: timeLocal } : {},
|
|
48511
48635
|
sender: nonEmpty(m.imdisplayname) ?? mri ?? "unknown",
|
|
48512
48636
|
fromMe: mri !== void 0 && mri === meMri,
|
|
48513
48637
|
text: htmlToText(content),
|
|
@@ -48524,22 +48648,120 @@ function summariseAll(raw, meMri) {
|
|
|
48524
48648
|
if (!out.some((s) => s.id === SELF_CHAT)) out.push(conversationSummary({ id: SELF_CHAT }, meMri));
|
|
48525
48649
|
return out;
|
|
48526
48650
|
}
|
|
48527
|
-
function matchConversations(summaries, query) {
|
|
48651
|
+
function matchConversations(summaries, query, { messages = false } = {}) {
|
|
48528
48652
|
const exact = summaries.find((s) => s.id === query);
|
|
48529
|
-
if (exact) return [exact];
|
|
48653
|
+
if (exact) return [{ ...exact, match_reason: "id" }];
|
|
48530
48654
|
const q = query.trim().toLowerCase();
|
|
48531
48655
|
if (q === "") return [];
|
|
48532
48656
|
if (SELF_CHAT_ALIASES.has(q)) {
|
|
48533
48657
|
const self = summaries.find((s) => s.id === SELF_CHAT);
|
|
48534
|
-
if (self) return [self];
|
|
48658
|
+
if (self) return [{ ...self, match_reason: "title" }];
|
|
48535
48659
|
}
|
|
48536
|
-
return summaries.
|
|
48537
|
-
|
|
48538
|
-
|
|
48660
|
+
return summaries.flatMap((s) => {
|
|
48661
|
+
const reason = matchReason(s, q, messages);
|
|
48662
|
+
return reason === void 0 ? [] : [{ ...s, match_reason: reason }];
|
|
48663
|
+
});
|
|
48664
|
+
}
|
|
48665
|
+
function matchReason(s, q, messages) {
|
|
48666
|
+
if (hasRealTitle(s) && s.title.toLowerCase().includes(q)) return "title";
|
|
48667
|
+
if (s.team?.toLowerCase().includes(q)) return "team";
|
|
48668
|
+
if (s.participants?.some((p) => p.toLowerCase().includes(q))) return "participant";
|
|
48669
|
+
if (messages && s.lastMessagePreview !== void 0 && s.lastMessagePreview !== SYSTEM_EVENT_PREVIEW) {
|
|
48670
|
+
if (s.lastMessagePreview.toLowerCase().includes(q)) return "message";
|
|
48671
|
+
}
|
|
48672
|
+
return void 0;
|
|
48539
48673
|
}
|
|
48540
48674
|
function hasRealTitle(s) {
|
|
48541
48675
|
if (s.title === UNTITLED_GROUP_TITLE || s.title === UNTITLED_ONE_ON_ONE_TITLE) return false;
|
|
48542
|
-
return
|
|
48676
|
+
return s.participants === void 0;
|
|
48677
|
+
}
|
|
48678
|
+
|
|
48679
|
+
// src/network-error.ts
|
|
48680
|
+
init_dist2();
|
|
48681
|
+
var MAX_CAUSE_DEPTH = 5;
|
|
48682
|
+
var DNS_CODES = /* @__PURE__ */ new Set(["ENOTFOUND", "EAI_AGAIN", "EAI_FAIL", "EAI_NONAME"]);
|
|
48683
|
+
var CONNECT_CODES = /* @__PURE__ */ new Set([
|
|
48684
|
+
"ECONNREFUSED",
|
|
48685
|
+
"ECONNRESET",
|
|
48686
|
+
"ETIMEDOUT",
|
|
48687
|
+
"ENETUNREACH",
|
|
48688
|
+
"EHOSTUNREACH",
|
|
48689
|
+
"EPIPE",
|
|
48690
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
48691
|
+
"UND_ERR_SOCKET",
|
|
48692
|
+
"UND_ERR_HEADERS_TIMEOUT"
|
|
48693
|
+
]);
|
|
48694
|
+
var CERT_CODES = /* @__PURE__ */ new Set([
|
|
48695
|
+
"UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
|
|
48696
|
+
"UNABLE_TO_GET_ISSUER_CERT",
|
|
48697
|
+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
|
|
48698
|
+
"SELF_SIGNED_CERT_IN_CHAIN",
|
|
48699
|
+
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
48700
|
+
"CERT_HAS_EXPIRED",
|
|
48701
|
+
"CERT_NOT_YET_VALID",
|
|
48702
|
+
"ERR_TLS_CERT_ALTNAME_INVALID"
|
|
48703
|
+
]);
|
|
48704
|
+
function codeOf(e) {
|
|
48705
|
+
if (e === null || typeof e !== "object") return void 0;
|
|
48706
|
+
const code2 = e.code;
|
|
48707
|
+
return typeof code2 === "string" && code2 !== "" ? code2 : void 0;
|
|
48708
|
+
}
|
|
48709
|
+
function causes(err) {
|
|
48710
|
+
const out = [];
|
|
48711
|
+
let at = err;
|
|
48712
|
+
for (let depth = 0; depth < MAX_CAUSE_DEPTH && at !== void 0 && at !== null; depth++) {
|
|
48713
|
+
out.push(at);
|
|
48714
|
+
if (at instanceof AggregateError) out.push(...at.errors);
|
|
48715
|
+
at = at.cause;
|
|
48716
|
+
}
|
|
48717
|
+
return out;
|
|
48718
|
+
}
|
|
48719
|
+
function transportCauseCode(err) {
|
|
48720
|
+
for (const e of causes(err)) {
|
|
48721
|
+
const code2 = codeOf(e);
|
|
48722
|
+
if (code2 !== void 0) return code2;
|
|
48723
|
+
}
|
|
48724
|
+
return void 0;
|
|
48725
|
+
}
|
|
48726
|
+
function causeMessage(err) {
|
|
48727
|
+
const chain = causes(err).slice(1);
|
|
48728
|
+
for (let i = chain.length - 1; i >= 0; i--) {
|
|
48729
|
+
const e = chain[i];
|
|
48730
|
+
if (e instanceof Error && e.message !== "") return e.message;
|
|
48731
|
+
}
|
|
48732
|
+
return void 0;
|
|
48733
|
+
}
|
|
48734
|
+
function isFetchFailed(err) {
|
|
48735
|
+
return err instanceof TypeError && err.message === "fetch failed";
|
|
48736
|
+
}
|
|
48737
|
+
function hintFor(code2, host) {
|
|
48738
|
+
if (code2 !== void 0 && DNS_CODES.has(code2)) {
|
|
48739
|
+
return `This machine could not resolve ${host}. Check DNS and VPN: a split-tunnel VPN that resolves teams.cloud.microsoft but not the regional *.asm.skype.com and *.sharepoint.com hosts fails exactly like this. \`nslookup ${host}\` on the machine running this server tells you which.`;
|
|
48740
|
+
}
|
|
48741
|
+
if (code2 !== void 0 && CERT_CODES.has(code2)) {
|
|
48742
|
+
return `Node did not trust the TLS certificate ${host} presented. On a corporate network this is usually TLS inspection: export your proxy's root CA as PEM and start this server with NODE_EXTRA_CA_CERTS=/path/to/ca.pem (Node does not read the system keychain). If the certificate is expired or not yet valid, also check the machine's clock.`;
|
|
48743
|
+
}
|
|
48744
|
+
if (code2 !== void 0 && CONNECT_CODES.has(code2)) {
|
|
48745
|
+
return `The connection to ${host} was refused, reset or timed out before Teams answered \u2014 usually a firewall, or a network that only lets traffic out through a proxy. Node's fetch ignores proxy settings unless told: start this server with HTTPS_PROXY=<your proxy URL> and NODE_USE_ENV_PROXY=1 (Node 22.21+ / 24.5+), or allow the host through the firewall.`;
|
|
48746
|
+
}
|
|
48747
|
+
return `No response from ${host}. Check this machine can reach it (VPN, proxy, firewall); \`curl -sI https://${host}/\` from the same machine is a quick test.`;
|
|
48748
|
+
}
|
|
48749
|
+
function describeTransportFailure(err, url2, service) {
|
|
48750
|
+
if (!isFetchFailed(err)) return void 0;
|
|
48751
|
+
let host;
|
|
48752
|
+
try {
|
|
48753
|
+
host = new URL(url2).hostname;
|
|
48754
|
+
} catch {
|
|
48755
|
+
host = "(unknown host)";
|
|
48756
|
+
}
|
|
48757
|
+
const code2 = transportCauseCode(err);
|
|
48758
|
+
const detail = [code2, causeMessage(err)].filter((s) => s !== void 0);
|
|
48759
|
+
const why = detail.length > 0 ? ` (${[...new Set(detail)].join(": ")})` : "";
|
|
48760
|
+
return new McpToolError(`Could not reach ${service} at ${host}${why}.`, {
|
|
48761
|
+
kind: "transport",
|
|
48762
|
+
hint: hintFor(code2, host),
|
|
48763
|
+
cause: err
|
|
48764
|
+
});
|
|
48543
48765
|
}
|
|
48544
48766
|
|
|
48545
48767
|
// src/chatsvc.ts
|
|
@@ -48562,6 +48784,16 @@ var MAX_MESSAGE_PAGES = 20;
|
|
|
48562
48784
|
var DEFAULT_MESSAGE_PAGE_SIZE = 200;
|
|
48563
48785
|
var MAX_IMAGE_BYTES = 5 * 1024 * 1024;
|
|
48564
48786
|
var IMAGE_HOST_SUFFIX2 = ".asm.skype.com";
|
|
48787
|
+
var IMAGE_GATEWAY_HOST = "us-prod.asyncgw.teams.microsoft.com";
|
|
48788
|
+
function serviceFor(url2) {
|
|
48789
|
+
try {
|
|
48790
|
+
const host = new URL(url2).hostname;
|
|
48791
|
+
if (host.endsWith(IMAGE_HOST_SUFFIX2)) return "Teams' image store";
|
|
48792
|
+
return host === IMAGE_GATEWAY_HOST ? "the Teams image gateway" : "the Teams chat service";
|
|
48793
|
+
} catch {
|
|
48794
|
+
return "the Teams chat service";
|
|
48795
|
+
}
|
|
48796
|
+
}
|
|
48565
48797
|
function outcomeUnknown(method, e, hint) {
|
|
48566
48798
|
if (e instanceof RequestTimeoutError) {
|
|
48567
48799
|
return new WriteOutcomeUnknownError("Teams", method, { timeoutMs: e.timeoutMs, cause: e, hint });
|
|
@@ -48571,6 +48803,7 @@ function outcomeUnknown(method, e, hint) {
|
|
|
48571
48803
|
}
|
|
48572
48804
|
var SEND_OUTCOME_HINT = "The message may already have been posted \u2014 check the conversation (teams_read_conversation) before retrying; do not resend blindly.";
|
|
48573
48805
|
var REACTION_OUTCOME_HINT = "The reaction change may already have been applied \u2014 check the message (teams_read_conversation) before retrying.";
|
|
48806
|
+
var HORIZON_OUTCOME_HINT = "The read marker may already have moved \u2014 check the conversation (teams_read_conversation) before retrying; moving it again to the same message is harmless.";
|
|
48574
48807
|
function outcomeUnknownStatus(e) {
|
|
48575
48808
|
const status = e.cause?.status;
|
|
48576
48809
|
return typeof status === "number" ? status : void 0;
|
|
@@ -48726,12 +48959,16 @@ var ChatServiceClient = class {
|
|
|
48726
48959
|
return out;
|
|
48727
48960
|
}
|
|
48728
48961
|
/**
|
|
48729
|
-
* One message by id, or `undefined` when the service
|
|
48730
|
-
*
|
|
48962
|
+
* One message by id, or `undefined` when the service answers 404. Used to
|
|
48963
|
+
* quote a message (its sender and text go into the quote) and to fill in a
|
|
48964
|
+
* channel thread's root post when it is older than a read's window — a
|
|
48965
|
+
* channel root fetched by its id answers like any message (verified live
|
|
48966
|
+
* 2026-10-12). An id the channel does not hold was answered 403, not 404,
|
|
48967
|
+
* live, so that surfaces as an error.
|
|
48731
48968
|
*/
|
|
48732
|
-
async getMessage(conversationId,
|
|
48969
|
+
async getMessage(conversationId, messageId2) {
|
|
48733
48970
|
this.#requireConfigured();
|
|
48734
|
-
const url2 = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(conversationId)}/messages/${encodeURIComponent(
|
|
48971
|
+
const url2 = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(conversationId)}/messages/${encodeURIComponent(messageId2)}`;
|
|
48735
48972
|
const { status, body } = await this.#send(url2, "text");
|
|
48736
48973
|
if (status === 404) return void 0;
|
|
48737
48974
|
return this.#parseJson(status, body);
|
|
@@ -48769,19 +49006,39 @@ var ChatServiceClient = class {
|
|
|
48769
49006
|
* the tool reads the message back rather than reporting a plain failure for
|
|
48770
49007
|
* a change that may well be visible already.
|
|
48771
49008
|
*/
|
|
48772
|
-
async setReaction(conversationId,
|
|
48773
|
-
await this.#writeEmotions("PUT", conversationId,
|
|
49009
|
+
async setReaction(conversationId, messageId2, key, at = Date.now()) {
|
|
49010
|
+
await this.#writeEmotions("PUT", conversationId, messageId2, { key, value: at });
|
|
48774
49011
|
}
|
|
48775
49012
|
/** Withdraw the user's reaction: `DELETE` on the same property (unverified live — see the plan). */
|
|
48776
|
-
async removeReaction(conversationId,
|
|
48777
|
-
await this.#writeEmotions("DELETE", conversationId,
|
|
49013
|
+
async removeReaction(conversationId, messageId2, key) {
|
|
49014
|
+
await this.#writeEmotions("DELETE", conversationId, messageId2, { key });
|
|
48778
49015
|
}
|
|
48779
|
-
async #writeEmotions(method, conversationId,
|
|
49016
|
+
async #writeEmotions(method, conversationId, messageId2, emotions) {
|
|
48780
49017
|
this.#requireConfigured();
|
|
48781
|
-
const url2 = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(conversationId)}/messages/${encodeURIComponent(
|
|
49018
|
+
const url2 = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(conversationId)}/messages/${encodeURIComponent(messageId2)}/properties?name=emotions`;
|
|
48782
49019
|
const { status } = await this.#send(url2, "text", void 0, { method, body: { emotions }, hint: REACTION_OUTCOME_HINT });
|
|
48783
49020
|
this.#checkWriteStatus(method, status, REACTION_OUTCOME_HINT);
|
|
48784
49021
|
}
|
|
49022
|
+
/**
|
|
49023
|
+
* Move the user's read marker in a conversation to `messageId`:
|
|
49024
|
+
* `PUT …/conversations/{id}/properties?name=consumptionhorizon` with
|
|
49025
|
+
* `{ consumptionhorizon: "<id>;<client ms>;<id>" }` — the shape `readHorizon`
|
|
49026
|
+
* parses, its first segment the message's arrival ms (which is its id).
|
|
49027
|
+
* Teams clears the unread badge for everything up to it.
|
|
49028
|
+
*
|
|
49029
|
+
* Verified live 2026-10-12 on `48:notes`: 200, and the listing then carries
|
|
49030
|
+
* the new horizon. A move BACKWARDS is also answered 200 but ignored, so a
|
|
49031
|
+
* 200 does not prove the marker moved; never sending one is the caller's
|
|
49032
|
+
* rule (`teams_mark_read`), which reports it as a no-op instead. A lost
|
|
49033
|
+
* answer is a `WriteOutcomeUnknownError`, as for a reaction.
|
|
49034
|
+
*/
|
|
49035
|
+
async setConsumptionHorizon(conversationId, messageId2, at = Date.now()) {
|
|
49036
|
+
this.#requireConfigured();
|
|
49037
|
+
const url2 = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(conversationId)}/properties?name=consumptionhorizon`;
|
|
49038
|
+
const body = { consumptionhorizon: `${messageId2};${at};${messageId2}` };
|
|
49039
|
+
const { status } = await this.#send(url2, "text", void 0, { method: "PUT", body, hint: HORIZON_OUTCOME_HINT });
|
|
49040
|
+
this.#checkWriteStatus("PUT", status, HORIZON_OUTCOME_HINT);
|
|
49041
|
+
}
|
|
48785
49042
|
/**
|
|
48786
49043
|
* Download an inline image (`<img src>` in a message body).
|
|
48787
49044
|
*
|
|
@@ -48805,6 +49062,23 @@ var ChatServiceClient = class {
|
|
|
48805
49062
|
hint: `Only https images on *${IMAGE_HOST_SUFFIX2} (Teams' own image store) are fetched.`
|
|
48806
49063
|
});
|
|
48807
49064
|
}
|
|
49065
|
+
try {
|
|
49066
|
+
return await this.#getImage(target);
|
|
49067
|
+
} catch (e) {
|
|
49068
|
+
if (errorKindOf(e) !== "transport") throw e;
|
|
49069
|
+
const viaGateway = new URL(target.pathname + target.search, `https://${IMAGE_GATEWAY_HOST}`);
|
|
49070
|
+
try {
|
|
49071
|
+
return await this.#getImage(viaGateway);
|
|
49072
|
+
} catch (e2) {
|
|
49073
|
+
if (errorKindOf(e2) !== "transport") throw e2;
|
|
49074
|
+
throw new McpToolError(
|
|
49075
|
+
`${e.message} The Teams gateway was tried too: ${e2.message}`,
|
|
49076
|
+
{ kind: "transport", hint: e.hint, cause: e }
|
|
49077
|
+
);
|
|
49078
|
+
}
|
|
49079
|
+
}
|
|
49080
|
+
}
|
|
49081
|
+
async #getImage(target) {
|
|
48808
49082
|
const { status, headers, body } = await this.#send(target.toString(), "bytes", MAX_IMAGE_BYTES);
|
|
48809
49083
|
this.#checkStatus(status);
|
|
48810
49084
|
const mimeType = (headers.get("content-type") ?? "application/octet-stream").split(";")[0].trim();
|
|
@@ -48888,7 +49162,8 @@ var ChatServiceClient = class {
|
|
|
48888
49162
|
try {
|
|
48889
49163
|
r = await fetchBounded(url2, init, opts);
|
|
48890
49164
|
} catch (e) {
|
|
48891
|
-
|
|
49165
|
+
if (write) throw outcomeUnknown(method, e, write.hint);
|
|
49166
|
+
throw describeTransportFailure(e, url2, serviceFor(url2)) ?? e;
|
|
48892
49167
|
}
|
|
48893
49168
|
body = r.body;
|
|
48894
49169
|
return r.res;
|
|
@@ -49054,6 +49329,13 @@ async function captureSharePointTokenLazily(host) {
|
|
|
49054
49329
|
var UNKNOWN_TOKEN_TTL_MS2 = 10 * 60 * 1e3;
|
|
49055
49330
|
var RECAPTURE_SENTINEL2 = "fetchproxy:recapture";
|
|
49056
49331
|
var REQUEST_TIMEOUT_MS2 = 6e4;
|
|
49332
|
+
async function reachable(url2, run) {
|
|
49333
|
+
try {
|
|
49334
|
+
return await run();
|
|
49335
|
+
} catch (e) {
|
|
49336
|
+
throw describeTransportFailure(e, url2, "SharePoint") ?? e;
|
|
49337
|
+
}
|
|
49338
|
+
}
|
|
49057
49339
|
function toBearerTokens2(accessToken) {
|
|
49058
49340
|
let expiresAt;
|
|
49059
49341
|
try {
|
|
@@ -49165,18 +49447,21 @@ var SharePointClient = class {
|
|
|
49165
49447
|
async #getDriveItem(captureHost, url2) {
|
|
49166
49448
|
let body = "";
|
|
49167
49449
|
const res = await this.#managerFor(captureHost).withAuth(async (token) => {
|
|
49168
|
-
const r = await
|
|
49450
|
+
const r = await reachable(
|
|
49169
49451
|
url2,
|
|
49170
|
-
|
|
49171
|
-
|
|
49172
|
-
|
|
49173
|
-
|
|
49174
|
-
|
|
49175
|
-
|
|
49452
|
+
() => fetchBounded(
|
|
49453
|
+
url2,
|
|
49454
|
+
{
|
|
49455
|
+
method: "GET",
|
|
49456
|
+
headers: {
|
|
49457
|
+
authorization: `Bearer ${token}`,
|
|
49458
|
+
accept: "application/json",
|
|
49459
|
+
behavioroverride: "redirectAs404"
|
|
49460
|
+
},
|
|
49461
|
+
redirect: "error"
|
|
49176
49462
|
},
|
|
49177
|
-
|
|
49178
|
-
|
|
49179
|
-
{ read: "text", service: "SharePoint", timeoutMs: REQUEST_TIMEOUT_MS2, fetchImpl: this.#fetchImpl }
|
|
49463
|
+
{ read: "text", service: "SharePoint", timeoutMs: REQUEST_TIMEOUT_MS2, fetchImpl: this.#fetchImpl }
|
|
49464
|
+
)
|
|
49180
49465
|
);
|
|
49181
49466
|
body = r.body;
|
|
49182
49467
|
return r.res;
|
|
@@ -49216,10 +49501,13 @@ var SharePointClient = class {
|
|
|
49216
49501
|
hint: "SharePoint download links are expected to be https."
|
|
49217
49502
|
});
|
|
49218
49503
|
}
|
|
49219
|
-
const r = await
|
|
49504
|
+
const r = await reachable(
|
|
49220
49505
|
target.toString(),
|
|
49221
|
-
|
|
49222
|
-
|
|
49506
|
+
() => fetchBounded(
|
|
49507
|
+
target.toString(),
|
|
49508
|
+
{ method: "GET", headers: { accept: "*/*" }, redirect: "follow" },
|
|
49509
|
+
{ read: "bytes", maxBytes, service: "SharePoint", timeoutMs: REQUEST_TIMEOUT_MS2, fetchImpl: this.#fetchImpl }
|
|
49510
|
+
)
|
|
49223
49511
|
);
|
|
49224
49512
|
this.#checkStatus(r.status);
|
|
49225
49513
|
const mimeType = (r.headers.get("content-type") ?? "application/octet-stream").split(";")[0].trim();
|
|
@@ -49259,8 +49547,279 @@ var SharePointClient = class {
|
|
|
49259
49547
|
}
|
|
49260
49548
|
};
|
|
49261
49549
|
|
|
49550
|
+
// src/substrate.ts
|
|
49551
|
+
init_dist2();
|
|
49552
|
+
|
|
49553
|
+
// src/substrate-token-cache.ts
|
|
49554
|
+
init_dist2();
|
|
49555
|
+
function substrateTokenCachePath(env = process.env) {
|
|
49556
|
+
return resolveStateFile({
|
|
49557
|
+
env,
|
|
49558
|
+
envVar: "TEAMS_SUBSTRATE_TOKEN_FILE",
|
|
49559
|
+
subdir: ".microsoft-teams-mcp",
|
|
49560
|
+
fileName: "substrate-token.json"
|
|
49561
|
+
});
|
|
49562
|
+
}
|
|
49563
|
+
function isToken3(raw) {
|
|
49564
|
+
if (raw === null || typeof raw !== "object") return false;
|
|
49565
|
+
const t = raw;
|
|
49566
|
+
return typeof t.accessToken === "string" && t.accessToken !== "" && typeof t.expiresAt === "number" && (t.refreshToken === void 0 || typeof t.refreshToken === "string");
|
|
49567
|
+
}
|
|
49568
|
+
function createSubstrateTokenCache(env = process.env) {
|
|
49569
|
+
if (!parseBoolEnv("TEAMS_TOKEN_CACHE", { env, default: true })) return null;
|
|
49570
|
+
if (parseBoolEnv("TEAMS_DISABLE_FETCHPROXY", { env })) return null;
|
|
49571
|
+
const file2 = createFileStatePersistence({
|
|
49572
|
+
filePath: substrateTokenCachePath(env),
|
|
49573
|
+
boundTo: "fetchproxy",
|
|
49574
|
+
validate: (raw) => isToken3(raw) ? raw : null
|
|
49575
|
+
});
|
|
49576
|
+
return {
|
|
49577
|
+
load: () => file2.load(),
|
|
49578
|
+
save(tokens) {
|
|
49579
|
+
try {
|
|
49580
|
+
file2.save(tokens);
|
|
49581
|
+
} catch (err) {
|
|
49582
|
+
reportCacheWriteFailure(err);
|
|
49583
|
+
}
|
|
49584
|
+
},
|
|
49585
|
+
clear() {
|
|
49586
|
+
try {
|
|
49587
|
+
file2.clear();
|
|
49588
|
+
} catch (err) {
|
|
49589
|
+
reportCacheWriteFailure(err);
|
|
49590
|
+
}
|
|
49591
|
+
}
|
|
49592
|
+
};
|
|
49593
|
+
}
|
|
49594
|
+
|
|
49595
|
+
// src/substrate.ts
|
|
49596
|
+
var SUBSTRATE_QUERY_URL = "https://substrate.office.com/searchservice/api/v2/query";
|
|
49597
|
+
var CAPTURE_RETRY_COOLDOWN_MS = 10 * 60 * 1e3;
|
|
49598
|
+
var UNKNOWN_TOKEN_TTL_MS3 = 10 * 60 * 1e3;
|
|
49599
|
+
var RECAPTURE_SENTINEL3 = "fetchproxy:recapture";
|
|
49600
|
+
var REQUEST_TIMEOUT_MS3 = 3e4;
|
|
49601
|
+
var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
49602
|
+
function toBearerTokens3(accessToken) {
|
|
49603
|
+
let expiresAt;
|
|
49604
|
+
try {
|
|
49605
|
+
expiresAt = decodeJwtExp(accessToken) * 1e3;
|
|
49606
|
+
} catch {
|
|
49607
|
+
expiresAt = Date.now() + UNKNOWN_TOKEN_TTL_MS3;
|
|
49608
|
+
}
|
|
49609
|
+
return { accessToken, refreshToken: RECAPTURE_SENTINEL3, expiresAt };
|
|
49610
|
+
}
|
|
49611
|
+
async function captureSubstrateTokenLazily() {
|
|
49612
|
+
const mod = await Promise.resolve().then(() => (init_substrate_auth(), substrate_auth_exports));
|
|
49613
|
+
return mod.captureSubstrateTokenViaFetchproxy();
|
|
49614
|
+
}
|
|
49615
|
+
function sentBound(ms) {
|
|
49616
|
+
return new Date(Math.floor(ms / 1e3) * 1e3).toISOString().replace(/\.000Z$/, "Z");
|
|
49617
|
+
}
|
|
49618
|
+
function buildQueryString(req) {
|
|
49619
|
+
const filters = [];
|
|
49620
|
+
if (req.conversationId !== void 0) {
|
|
49621
|
+
if (/["\s]/.test(req.conversationId)) {
|
|
49622
|
+
throw new McpToolError("That conversation id cannot be expressed as a Substrate filter.", { kind: "unknown" });
|
|
49623
|
+
}
|
|
49624
|
+
filters.push(`ClientThreadId:"${req.conversationId}"`);
|
|
49625
|
+
}
|
|
49626
|
+
if (req.sentAfter !== void 0 && Number.isFinite(req.sentAfter)) filters.push(`sent>=${sentBound(req.sentAfter)}`);
|
|
49627
|
+
return filters.length === 0 ? req.query : [`(${req.query})`, ...filters].join(" ");
|
|
49628
|
+
}
|
|
49629
|
+
function buildQueryBody(req) {
|
|
49630
|
+
const cvid = crypto.randomUUID();
|
|
49631
|
+
return {
|
|
49632
|
+
entityRequests: [
|
|
49633
|
+
{
|
|
49634
|
+
entityType: "Message",
|
|
49635
|
+
contentSources: ["Teams"],
|
|
49636
|
+
query: { queryString: buildQueryString(req), displayQueryString: req.query },
|
|
49637
|
+
from: req.from,
|
|
49638
|
+
size: req.size,
|
|
49639
|
+
sort: [{ Field: "Time", SortDirection: "Desc" }]
|
|
49640
|
+
}
|
|
49641
|
+
],
|
|
49642
|
+
cvid,
|
|
49643
|
+
logicalId: cvid,
|
|
49644
|
+
scenario: {
|
|
49645
|
+
Name: "powerbar",
|
|
49646
|
+
Dimensions: [
|
|
49647
|
+
{ DimensionName: "QueryType", DimensionValue: "Messages" },
|
|
49648
|
+
{ DimensionName: "FormFactor", DimensionValue: "general.web.reactSearch" }
|
|
49649
|
+
]
|
|
49650
|
+
},
|
|
49651
|
+
QueryAlterationOptions: { EnableSuggestion: false, EnableAlteration: false }
|
|
49652
|
+
};
|
|
49653
|
+
}
|
|
49654
|
+
function obj(v) {
|
|
49655
|
+
return v !== null && typeof v === "object" && !Array.isArray(v) ? v : void 0;
|
|
49656
|
+
}
|
|
49657
|
+
function str(v) {
|
|
49658
|
+
return typeof v === "string" && v.trim() !== "" ? v : void 0;
|
|
49659
|
+
}
|
|
49660
|
+
function isoOf(v) {
|
|
49661
|
+
const s = str(v);
|
|
49662
|
+
if (s === void 0) return void 0;
|
|
49663
|
+
const ms = Date.parse(s);
|
|
49664
|
+
return Number.isFinite(ms) ? new Date(ms).toISOString() : void 0;
|
|
49665
|
+
}
|
|
49666
|
+
function mapResult(raw) {
|
|
49667
|
+
const r = obj(raw);
|
|
49668
|
+
const source = obj(r?.Source);
|
|
49669
|
+
if (r === void 0 || source === void 0) return void 0;
|
|
49670
|
+
const clientConv = str(source.ClientConversationId) ?? str(source.ClientThreadId);
|
|
49671
|
+
if (clientConv === void 0) return void 0;
|
|
49672
|
+
const [conversationId, ...params] = clientConv.split(";");
|
|
49673
|
+
if (str(conversationId) === void 0) return void 0;
|
|
49674
|
+
const root = params.map((p) => /^messageid=(.+)$/i.exec(p.trim())?.[1]).find((v) => v !== void 0);
|
|
49675
|
+
const messageId2 = str(source.InternetMessageId);
|
|
49676
|
+
const from = obj(obj(source.Sender)?.EmailAddress) ?? obj(obj(source.From)?.EmailAddress);
|
|
49677
|
+
const text = str(source.Preview) ?? str(r.HitHighlightedSummary) ?? "";
|
|
49678
|
+
const time3 = isoOf(source.DateTimeSent) ?? isoOf(source.DateTimeReceived) ?? isoOf(source.DateTimeCreated);
|
|
49679
|
+
const sender = str(from?.Name);
|
|
49680
|
+
const senderEmail = str(from?.Address);
|
|
49681
|
+
const subject = str(source.Subject);
|
|
49682
|
+
return {
|
|
49683
|
+
conversationId,
|
|
49684
|
+
...messageId2 !== void 0 ? { messageId: messageId2 } : {},
|
|
49685
|
+
...time3 !== void 0 ? { time: time3 } : {},
|
|
49686
|
+
...sender !== void 0 ? { sender } : {},
|
|
49687
|
+
...senderEmail !== void 0 ? { senderEmail } : {},
|
|
49688
|
+
text,
|
|
49689
|
+
...subject !== void 0 ? { subject } : {},
|
|
49690
|
+
...root !== void 0 && root !== messageId2 ? { replyTo: root } : {}
|
|
49691
|
+
};
|
|
49692
|
+
}
|
|
49693
|
+
function parseQueryResponse(body) {
|
|
49694
|
+
const sets = obj(body)?.EntitySets;
|
|
49695
|
+
const firstSet = Array.isArray(sets) ? obj(sets[0]) : void 0;
|
|
49696
|
+
const resultSets = firstSet?.ResultSets;
|
|
49697
|
+
const rs = Array.isArray(resultSets) ? obj(resultSets[0]) : void 0;
|
|
49698
|
+
if (rs === void 0) return { results: [], moreAvailable: false, unmapped: 0 };
|
|
49699
|
+
const raw = Array.isArray(rs.Results) ? rs.Results : [];
|
|
49700
|
+
const results = [];
|
|
49701
|
+
let unmapped = 0;
|
|
49702
|
+
for (const r of raw) {
|
|
49703
|
+
const m = mapResult(r);
|
|
49704
|
+
if (m === void 0) unmapped++;
|
|
49705
|
+
else results.push(m);
|
|
49706
|
+
}
|
|
49707
|
+
return {
|
|
49708
|
+
results,
|
|
49709
|
+
...typeof rs.Total === "number" ? { total: rs.Total } : {},
|
|
49710
|
+
moreAvailable: rs.MoreResultsAvailable === true,
|
|
49711
|
+
unmapped
|
|
49712
|
+
};
|
|
49713
|
+
}
|
|
49714
|
+
var SubstrateClient = class {
|
|
49715
|
+
#fetchImpl;
|
|
49716
|
+
#configError = null;
|
|
49717
|
+
#manager;
|
|
49718
|
+
/**
|
|
49719
|
+
* When the last capture failed, or a freshly captured token was still
|
|
49720
|
+
* refused (401), and how; cleared by a successful capture.
|
|
49721
|
+
*/
|
|
49722
|
+
#captureFailure = null;
|
|
49723
|
+
constructor(opts = {}) {
|
|
49724
|
+
const env = opts.env ?? process.env;
|
|
49725
|
+
const capture = opts.captureToken ?? captureSubstrateTokenLazily;
|
|
49726
|
+
this.#fetchImpl = opts.fetchImpl ?? ((input2, init) => fetch(input2, init));
|
|
49727
|
+
const recapture = async () => {
|
|
49728
|
+
try {
|
|
49729
|
+
const tokens = toBearerTokens3(await capture());
|
|
49730
|
+
this.#captureFailure = null;
|
|
49731
|
+
return tokens;
|
|
49732
|
+
} catch (error62) {
|
|
49733
|
+
this.#captureFailure = { at: Date.now(), error: error62 };
|
|
49734
|
+
throw error62;
|
|
49735
|
+
}
|
|
49736
|
+
};
|
|
49737
|
+
const persistence = createSubstrateTokenCache(env);
|
|
49738
|
+
this.#manager = new TokenManager({
|
|
49739
|
+
initial: recapture,
|
|
49740
|
+
refresh: recapture,
|
|
49741
|
+
...persistence ? { persistence } : {}
|
|
49742
|
+
});
|
|
49743
|
+
if (parseBoolEnv("TEAMS_DISABLE_FETCHPROXY", { env })) {
|
|
49744
|
+
this.#configError = new McpToolError("Substrate search is disabled (no token source).", {
|
|
49745
|
+
kind: "no_credential",
|
|
49746
|
+
hint: "Unset TEAMS_DISABLE_FETCHPROXY so a Substrate token can be captured from a signed-in Teams tab."
|
|
49747
|
+
});
|
|
49748
|
+
}
|
|
49749
|
+
}
|
|
49750
|
+
/** Whether a token could be obtained at all (the bridge is not disabled). */
|
|
49751
|
+
isConfigured() {
|
|
49752
|
+
return this.#configError === null;
|
|
49753
|
+
}
|
|
49754
|
+
async searchMessages(req, opts = {}) {
|
|
49755
|
+
if (this.#configError) throw this.#configError;
|
|
49756
|
+
const failed = this.#captureFailure;
|
|
49757
|
+
if (!opts.force && failed !== null && Date.now() - failed.at < CAPTURE_RETRY_COOLDOWN_MS) throw failed.error;
|
|
49758
|
+
let text = "";
|
|
49759
|
+
const res = await this.#manager.withAuth(async (token) => {
|
|
49760
|
+
let r;
|
|
49761
|
+
try {
|
|
49762
|
+
r = await fetchBounded(
|
|
49763
|
+
SUBSTRATE_QUERY_URL,
|
|
49764
|
+
{
|
|
49765
|
+
method: "POST",
|
|
49766
|
+
headers: {
|
|
49767
|
+
authorization: `Bearer ${token}`,
|
|
49768
|
+
"content-type": "application/json",
|
|
49769
|
+
accept: "application/json"
|
|
49770
|
+
},
|
|
49771
|
+
body: JSON.stringify(buildQueryBody(req)),
|
|
49772
|
+
redirect: "error"
|
|
49773
|
+
},
|
|
49774
|
+
{
|
|
49775
|
+
read: "text",
|
|
49776
|
+
maxBytes: MAX_RESPONSE_BYTES,
|
|
49777
|
+
service: "Substrate",
|
|
49778
|
+
timeoutMs: REQUEST_TIMEOUT_MS3,
|
|
49779
|
+
fetchImpl: this.#fetchImpl
|
|
49780
|
+
}
|
|
49781
|
+
);
|
|
49782
|
+
} catch (e) {
|
|
49783
|
+
throw describeTransportFailure(e, SUBSTRATE_QUERY_URL, "Substrate search") ?? e;
|
|
49784
|
+
}
|
|
49785
|
+
text = r.body;
|
|
49786
|
+
return r.res;
|
|
49787
|
+
});
|
|
49788
|
+
try {
|
|
49789
|
+
checkStatus(res.status);
|
|
49790
|
+
} catch (error62) {
|
|
49791
|
+
if (res.status === 401) this.#captureFailure = { at: Date.now(), error: error62 };
|
|
49792
|
+
throw error62;
|
|
49793
|
+
}
|
|
49794
|
+
try {
|
|
49795
|
+
return parseQueryResponse(JSON.parse(text));
|
|
49796
|
+
} catch {
|
|
49797
|
+
throw new McpToolError("Substrate returned a response that is not JSON.", { status: res.status, kind: "http" });
|
|
49798
|
+
}
|
|
49799
|
+
}
|
|
49800
|
+
};
|
|
49801
|
+
function checkStatus(status) {
|
|
49802
|
+
if (status >= 200 && status < 300) return;
|
|
49803
|
+
if (status === 401) {
|
|
49804
|
+
throw new McpToolError("Substrate rejected the search token (401) even after a fresh capture.", {
|
|
49805
|
+
status,
|
|
49806
|
+
kind: "credential_rejected",
|
|
49807
|
+
hint: "Run a search in a signed-in Teams tab to mint a fresh Substrate token, then retry."
|
|
49808
|
+
});
|
|
49809
|
+
}
|
|
49810
|
+
if (status === 429) {
|
|
49811
|
+
throw new McpToolError("Substrate is rate-limiting searches (429).", { status, kind: "http", hint: "Wait a minute before retrying." });
|
|
49812
|
+
}
|
|
49813
|
+
throw new McpToolError(`Substrate search returned HTTP ${status}.`, {
|
|
49814
|
+
status,
|
|
49815
|
+
kind: "http",
|
|
49816
|
+
...status >= 500 ? { hint: "A Substrate-side failure; retry shortly." } : {}
|
|
49817
|
+
});
|
|
49818
|
+
}
|
|
49819
|
+
|
|
49262
49820
|
// src/tools/chat.ts
|
|
49263
49821
|
init_dist2();
|
|
49822
|
+
init_zod();
|
|
49264
49823
|
|
|
49265
49824
|
// src/tools/errors.ts
|
|
49266
49825
|
init_dist2();
|
|
@@ -49332,6 +49891,44 @@ function makeLimitedStopAt(horizon, wanted, limit) {
|
|
|
49332
49891
|
};
|
|
49333
49892
|
}
|
|
49334
49893
|
|
|
49894
|
+
// src/tools/chat-search.ts
|
|
49895
|
+
init_dist2();
|
|
49896
|
+
var SEARCH_FETCH_MESSAGES = 50;
|
|
49897
|
+
var SEARCH_CONCURRENCY = 4;
|
|
49898
|
+
var SNIPPET_CHARS = 200;
|
|
49899
|
+
var SNIPPET_LEAD = 60;
|
|
49900
|
+
async function searchRecentMessages(chatsvc, me, ids, query) {
|
|
49901
|
+
const q = query.trim().toLowerCase();
|
|
49902
|
+
const hits = /* @__PURE__ */ new Map();
|
|
49903
|
+
let failed = 0;
|
|
49904
|
+
if (q === "") return { hits, failed };
|
|
49905
|
+
await mapWithConcurrency([...new Set(ids)], SEARCH_CONCURRENCY, async (id) => {
|
|
49906
|
+
let messages;
|
|
49907
|
+
try {
|
|
49908
|
+
messages = await chatsvc.getMessages(id, { max: SEARCH_FETCH_MESSAGES, pageSize: SEARCH_FETCH_MESSAGES });
|
|
49909
|
+
} catch {
|
|
49910
|
+
failed++;
|
|
49911
|
+
return;
|
|
49912
|
+
}
|
|
49913
|
+
for (const m of messages) {
|
|
49914
|
+
if (!isUserMessage(m)) continue;
|
|
49915
|
+
const n = normaliseMessage(m, me);
|
|
49916
|
+
if (n.deleted) continue;
|
|
49917
|
+
const at = n.text.toLowerCase().indexOf(q);
|
|
49918
|
+
if (at === -1) continue;
|
|
49919
|
+
hits.set(id, { id: n.id, time: n.time, sender: n.sender, text: snippet(n.text, at) });
|
|
49920
|
+
return;
|
|
49921
|
+
}
|
|
49922
|
+
});
|
|
49923
|
+
return { hits, failed };
|
|
49924
|
+
}
|
|
49925
|
+
function snippet(text, at) {
|
|
49926
|
+
if (text.length <= SNIPPET_CHARS) return text;
|
|
49927
|
+
const start = Math.max(0, Math.min(at - SNIPPET_LEAD, text.length - SNIPPET_CHARS));
|
|
49928
|
+
const end = start + SNIPPET_CHARS;
|
|
49929
|
+
return `${start > 0 ? "\u2026" : ""}${text.slice(start, end)}${end < text.length ? "\u2026" : ""}`;
|
|
49930
|
+
}
|
|
49931
|
+
|
|
49335
49932
|
// src/tools/listing.ts
|
|
49336
49933
|
init_zod();
|
|
49337
49934
|
|
|
@@ -49355,10 +49952,31 @@ function olderUnreadReport(olderSkipped, sinceDays) {
|
|
|
49355
49952
|
return {
|
|
49356
49953
|
older_unread_skipped: olderSkipped,
|
|
49357
49954
|
...olderSkipped > 0 ? {
|
|
49358
|
-
older_unread_hint: `${olderSkipped} conversation${olderSkipped === 1 ? "" : "s"} with unread activity older than ${days} days ${olderSkipped === 1 ? "was" : "were"} left out; pass a larger since_days (max ${MAX_SINCE_DAYS}) to include ${olderSkipped === 1 ? "it" : "them"}.`
|
|
49955
|
+
older_unread_hint: `${olderSkipped} conversation${olderSkipped === 1 ? "" : "s"} with unread activity older than ${days} days ${olderSkipped === 1 ? "was" : "were"} left out; pass a larger since_days (max ${MAX_SINCE_DAYS}) to include ${olderSkipped === 1 ? "it" : "them"}, or older_unread: true to list ${olderSkipped === 1 ? "it" : "them"}.`
|
|
49359
49956
|
} : {}
|
|
49360
49957
|
};
|
|
49361
49958
|
}
|
|
49959
|
+
function olderUnreadArg(scope = "") {
|
|
49960
|
+
return external_exports.boolean().optional().describe(
|
|
49961
|
+
`${scope}Also list the conversations since_days left out, as older_unread_conversations: id, kind, title, team (a channel's), lastActivity and, where its messages were read, unread_count. One never read (nothing at all happened inside the window) carries unread_count_known: false instead and is not read now \u2014 its news may be only system events. Default false.`
|
|
49962
|
+
);
|
|
49963
|
+
}
|
|
49964
|
+
function olderUnreadConversations(older, titled) {
|
|
49965
|
+
if (older.length === 0) return {};
|
|
49966
|
+
const rows = older.map(({ read }, i) => {
|
|
49967
|
+
const s = titled[i];
|
|
49968
|
+
return {
|
|
49969
|
+
id: s.id,
|
|
49970
|
+
kind: s.kind,
|
|
49971
|
+
title: s.title,
|
|
49972
|
+
...s.team !== void 0 ? { team: s.team } : {},
|
|
49973
|
+
...s.lastActivity !== void 0 ? { lastActivity: s.lastActivity } : {},
|
|
49974
|
+
...read === void 0 ? { unread_count_known: false } : { unread_count: read.messages.length, ...read.truncated ? { unread_count_exact: false } : {} }
|
|
49975
|
+
};
|
|
49976
|
+
});
|
|
49977
|
+
rows.sort((a, b) => (b.lastActivity ?? "").localeCompare(a.lastActivity ?? ""));
|
|
49978
|
+
return { older_unread_conversations: rows };
|
|
49979
|
+
}
|
|
49362
49980
|
function isUnreachable(err) {
|
|
49363
49981
|
const status = errorStatusOf(err);
|
|
49364
49982
|
return status === 404 || status === 403;
|
|
@@ -49381,25 +49999,27 @@ async function confirmUnreadCandidates(chatsvc, raw, me, candidates, opts) {
|
|
|
49381
49999
|
const conv = byId.get(summary.id) ?? { id: summary.id };
|
|
49382
50000
|
const newest = newestActivityMs(conv);
|
|
49383
50001
|
if (newest !== void 0 && newest < since) return { kind: "older" };
|
|
49384
|
-
const
|
|
50002
|
+
const cursors = opts.cursors ?? {};
|
|
50003
|
+
const cursor = Object.hasOwn(cursors, summary.id) ? Number(cursors[summary.id]) : 0;
|
|
50004
|
+
const horizon = Math.max(readHorizon(conv), Number.isFinite(cursor) ? cursor : 0);
|
|
49385
50005
|
try {
|
|
49386
50006
|
return { kind: "read", read: await readUnread(chatsvc, summary.id, horizon, me, opts) };
|
|
49387
50007
|
} catch (error62) {
|
|
49388
50008
|
return isUnreachable(error62) ? { kind: "unreachable" } : { kind: "failed", error: error62 };
|
|
49389
50009
|
}
|
|
49390
50010
|
});
|
|
49391
|
-
const outcome = { confirmed: [], skippedUnreachable: 0,
|
|
50011
|
+
const outcome = { confirmed: [], skippedUnreachable: 0, older: [], failed: [] };
|
|
49392
50012
|
let anyRead = false;
|
|
49393
50013
|
results.forEach((r, i) => {
|
|
49394
50014
|
const summary = candidates[i];
|
|
49395
|
-
if (r.kind === "older") outcome.
|
|
50015
|
+
if (r.kind === "older") outcome.older.push({ summary });
|
|
49396
50016
|
else if (r.kind === "unreachable") outcome.skippedUnreachable++;
|
|
49397
50017
|
else if (r.kind === "failed") outcome.failed.push({ summary, error: r.error });
|
|
49398
50018
|
else {
|
|
49399
50019
|
anyRead = true;
|
|
49400
50020
|
const newestUnread = r.read.messages[0];
|
|
49401
50021
|
if (newestUnread === void 0) return;
|
|
49402
|
-
if (Number(newestUnread.id) < since) outcome.
|
|
50022
|
+
if (Number(newestUnread.id) < since) outcome.older.push({ summary, read: r.read });
|
|
49403
50023
|
else outcome.confirmed.push({ summary, read: r.read });
|
|
49404
50024
|
}
|
|
49405
50025
|
});
|
|
@@ -49507,9 +50127,16 @@ async function enrichTitles(chatsvc, raw, me, rows) {
|
|
|
49507
50127
|
}
|
|
49508
50128
|
|
|
49509
50129
|
// src/tools/listing.ts
|
|
50130
|
+
function activeWithin(s, since, until) {
|
|
50131
|
+
if (since === void 0 && until === void 0) return true;
|
|
50132
|
+
const t = s.lastActivity === void 0 ? Number.NaN : Date.parse(s.lastActivity);
|
|
50133
|
+
if (Number.isNaN(t)) return false;
|
|
50134
|
+
return (since === void 0 || t >= since) && (until === void 0 || t <= until);
|
|
50135
|
+
}
|
|
49510
50136
|
var listSinceDaysArg = sinceDaysArg("With unread_only: ");
|
|
50137
|
+
var listOlderUnreadArg = olderUnreadArg("With unread_only: ");
|
|
49511
50138
|
var unreadOnlyArg = external_exports.boolean().optional().describe(
|
|
49512
|
-
"Only return conversations with a real message (not a call recording or other system event) the user has not read yet, each with its unread_count (default false). Exact: every candidate is confirmed by reading its messages past the read marker. Never marks anything read."
|
|
50139
|
+
"Only return conversations with a real message (not a call recording or other system event) the user has not read yet, each with its unread_count (default false). Exact: every candidate is confirmed by reading its messages past the read marker. Never marks anything read (teams_mark_read does)."
|
|
49513
50140
|
);
|
|
49514
50141
|
var UNREAD_HINT_DESCRIPTION = "Without unread_only, unread is only a hint from the listing (unread_confirmed: false): it can flag a conversation whose only news is a call recording or other system event. For an exact answer use unread_only (confirmed rows carry unread_confirmed: true and unread_count) or teams_get_unread.";
|
|
49515
50142
|
var CONFIRM_LIMIT = 50;
|
|
@@ -49523,6 +50150,7 @@ function isUnreadCandidateFor(s, includeHidden) {
|
|
|
49523
50150
|
function queryArg(what) {
|
|
49524
50151
|
return external_exports.string().min(1).optional().describe(`Case-insensitive substring of the ${what}, or an exact conversation id.`);
|
|
49525
50152
|
}
|
|
50153
|
+
var MATCH_REASON_DESCRIPTION = `With a query, each row carries match_reason \u2014 the first of "id" (exact id), "title", "team", "participant" (an untitled chat's participant) or "message" (what was said, not what the conversation is called) that applies.`;
|
|
49526
50154
|
var GROUP_TITLE_DESCRIPTION = 'A group chat with no topic is titled "Group chat: " and up to three of its recent senders other than the user, most recent first ("; " between names, "+N" for more), and carries every such recent sender as participants; it is "(untitled group chat)" when no one else wrote recently. A 1:1 is titled by the other person, who is its one participant; it is "(1:1 chat)" when they wrote nothing recently.';
|
|
49527
50155
|
function favoritesFirst(a, b) {
|
|
49528
50156
|
const rank = (s) => s.favorite ? 0 : s.pinned ? 1 : 2;
|
|
@@ -49531,10 +50159,23 @@ function favoritesFirst(a, b) {
|
|
|
49531
50159
|
var FAVORITES_DESCRIPTION = "Conversations the user marked a favorite or pinned in Teams carry favorite: true / pinned: true and, without unread_only, are listed first (favorites, then pinned); unread_only keeps its usual order.";
|
|
49532
50160
|
async function listSummaries(chatsvc, filter) {
|
|
49533
50161
|
const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
|
|
49534
|
-
let rows = raw.map((c) => conversationSummary(c, me, raw)).filter((s) => filter.kinds.includes(s.kind));
|
|
50162
|
+
let rows = raw.map((c) => conversationSummary(c, me, raw)).filter((s) => filter.kinds.includes(s.kind) && activeWithin(s, filter.activeSince, filter.activeUntil));
|
|
49535
50163
|
if (filter.unread_only) rows = rows.filter((s) => isUnreadCandidateFor(s, filter.include_hidden));
|
|
49536
|
-
|
|
49537
|
-
if (
|
|
50164
|
+
let searched = {};
|
|
50165
|
+
if (filter.query !== void 0) {
|
|
50166
|
+
const titled = await enrichTitles(chatsvc, raw, me, rows);
|
|
50167
|
+
const matched = matchConversations(titled, filter.query, { messages: true });
|
|
50168
|
+
if (filter.searchMessages && !namesOne(matched, filter.query)) {
|
|
50169
|
+
const found = await searchUnmatched(chatsvc, me, titled, matched, filter.query);
|
|
50170
|
+
rows = found.rows;
|
|
50171
|
+
if (found.failed > 0) searched = { messages_not_searched: found.failed };
|
|
50172
|
+
} else {
|
|
50173
|
+
rows = matched;
|
|
50174
|
+
}
|
|
50175
|
+
}
|
|
50176
|
+
if (!filter.unread_only) {
|
|
50177
|
+
return { rows, ...searched, retitle: async (kept) => ({ rows: await enrichTitles(chatsvc, raw, me, kept) }) };
|
|
50178
|
+
}
|
|
49538
50179
|
const outcome = await confirmUnreadCandidates(chatsvc, raw, me, rows, {
|
|
49539
50180
|
limit: CONFIRM_LIMIT,
|
|
49540
50181
|
maxRaw: CONFIRM_MAX_RAW,
|
|
@@ -49554,6 +50195,8 @@ async function listSummaries(chatsvc, filter) {
|
|
|
49554
50195
|
return { rows: rows2, ...errs2 ? { errors: errs2 } : {} };
|
|
49555
50196
|
};
|
|
49556
50197
|
const errs = errors(failedSummaries);
|
|
50198
|
+
const listedOlder = filter.older_unread ? outcome.older : [];
|
|
50199
|
+
const olderTitled = await enrichTitles(chatsvc, raw, me, listedOlder.map((o) => o.summary));
|
|
49557
50200
|
return {
|
|
49558
50201
|
retitle,
|
|
49559
50202
|
rows: outcome.confirmed.map(({ summary, read }) => ({
|
|
@@ -49562,42 +50205,109 @@ async function listSummaries(chatsvc, filter) {
|
|
|
49562
50205
|
...read.truncated ? { unread_count_exact: false } : {}
|
|
49563
50206
|
})),
|
|
49564
50207
|
skipped_unreachable: outcome.skippedUnreachable,
|
|
49565
|
-
...olderUnreadReport(outcome.
|
|
49566
|
-
...
|
|
50208
|
+
...olderUnreadReport(outcome.older.length, filter.since_days),
|
|
50209
|
+
...olderUnreadConversations(listedOlder, olderTitled),
|
|
50210
|
+
...errs ? { errors: errs } : {},
|
|
50211
|
+
...searched
|
|
49567
50212
|
};
|
|
49568
50213
|
}
|
|
50214
|
+
function namesOne(matched, query) {
|
|
50215
|
+
if (matched.length !== 1) return false;
|
|
50216
|
+
const [m] = matched;
|
|
50217
|
+
return m.match_reason === "id" || m.id === SELF_CHAT && SELF_CHAT_ALIASES.has(query.trim().toLowerCase());
|
|
50218
|
+
}
|
|
50219
|
+
async function searchUnmatched(chatsvc, me, all, matched, query) {
|
|
50220
|
+
const byId = new Map(matched.map((m) => [m.id, m]));
|
|
50221
|
+
const rest = all.filter((s) => !byId.has(s.id));
|
|
50222
|
+
const { hits, failed } = await searchRecentMessages(chatsvc, me, rest.map((s) => s.id), query);
|
|
50223
|
+
const rows = all.flatMap((s) => {
|
|
50224
|
+
const named = byId.get(s.id);
|
|
50225
|
+
if (named !== void 0) return [named];
|
|
50226
|
+
const hit = hits.get(s.id);
|
|
50227
|
+
return hit !== void 0 ? [{ ...s, match_reason: "message", matched_message: hit }] : [];
|
|
50228
|
+
});
|
|
50229
|
+
return { rows, failed };
|
|
50230
|
+
}
|
|
49569
50231
|
|
|
49570
50232
|
// src/tools/chat.ts
|
|
49571
50233
|
var MAX_CHATS = 500;
|
|
49572
50234
|
function byLastActivityDesc(a, b) {
|
|
49573
50235
|
return (b.lastActivity ?? "").localeCompare(a.lastActivity ?? "");
|
|
49574
50236
|
}
|
|
50237
|
+
function byTitle(a, b) {
|
|
50238
|
+
return a.title.localeCompare(b.title, void 0, { sensitivity: "base" });
|
|
50239
|
+
}
|
|
50240
|
+
function activityBoundArg(name, side) {
|
|
50241
|
+
return external_exports.string().refine((s) => !Number.isNaN(Date.parse(s)), { message: `${name} must be an ISO 8601 date-time` }).optional().describe(
|
|
50242
|
+
`Only return chats whose last activity is ${side} this ISO 8601 date-time (e.g. 2026-09-21T09:00:00Z). A chat with no last activity is left out whenever since or until is given.`
|
|
50243
|
+
);
|
|
50244
|
+
}
|
|
50245
|
+
var SORTS = ["activity", "activity_only", "title"];
|
|
50246
|
+
var sortArg = external_exports.enum(SORTS).optional().describe(
|
|
50247
|
+
'Order of the result, and so which chats limit keeps: "activity" (default) \u2014 favorites, then pinned, then most recent activity (unread_only: most recent activity); "activity_only" \u2014 most recent activity first, ignoring favorites and pinned; "title" \u2014 alphabetical by title, case-insensitive (titles every untitled chat in the listing first, so it reads more).'
|
|
50248
|
+
);
|
|
50249
|
+
var searchMessagesArg = external_exports.boolean().optional().describe(
|
|
50250
|
+
`With query: also read the last ${SEARCH_FETCH_MESSAGES} messages of every chat no name or last-message preview matched, and return the chats where one of them contains the query (match_reason "message", with the newest such message as matched_message: id, time, sender, text). Reads one page per chat, four at a time, so it is slower on a large listing; narrow it with since / until or unread_only. Default false.`
|
|
50251
|
+
);
|
|
50252
|
+
function sortChats(rows, sort, unreadOnly) {
|
|
50253
|
+
rows.sort(byLastActivityDesc);
|
|
50254
|
+
if (sort === "title") rows.sort(byTitle);
|
|
50255
|
+
else if (sort === "activity" && !unreadOnly) rows.sort(favoritesFirst);
|
|
50256
|
+
}
|
|
49575
50257
|
function registerChatTools(server, { chatsvc }) {
|
|
49576
50258
|
server.registerTool(
|
|
49577
50259
|
"teams_list_chats",
|
|
49578
50260
|
{
|
|
49579
50261
|
title: "List Teams chats",
|
|
49580
|
-
description: "List every chat the signed-in user is in \u2014 1:1s, group chats and meeting chats, not just the ones visible in the Teams sidebar \u2014 favorites and pinned first, then most recent activity. Each has an id, kind (oneOnOne / group / meeting, or self for the user's own 48:notes self-chat), title, unread hint, last-activity time (ISO 8601), and a last-message preview and sender. " + GROUP_TITLE_DESCRIPTION + " query also matches those participant names. " + FAVORITES_DESCRIPTION + " Pass an id (or the title) to teams_read_conversation to read the messages. Use unread_only to find chats with messages the user has not read, exactly as Teams counts them: each candidate is confirmed by reading its messages past the read marker, so a call recording, transcript or other system event never makes a chat unread. By default unread_only keeps only chats whose newest unread message is from the last 14 days (since_days widens it); older ones are counted in older_unread_skipped,
|
|
50262
|
+
description: "List every chat the signed-in user is in \u2014 1:1s, group chats and meeting chats, not just the ones visible in the Teams sidebar \u2014 favorites and pinned first, then most recent activity. Each has an id, kind (oneOnOne / group / meeting, or self for the user's own 48:notes self-chat), title, unread hint, last-activity time (ISO 8601), and a last-message preview and sender. " + GROUP_TITLE_DESCRIPTION + " query also matches those participant names, and the last-message preview. " + MATCH_REASON_DESCRIPTION + " search_messages extends the match to each chat's recent messages. " + FAVORITES_DESCRIPTION + " Pass an id (or the title) to teams_read_conversation to read the messages. Use unread_only to find chats with messages the user has not read, exactly as Teams counts them: each candidate is confirmed by reading its messages past the read marker, so a call recording, transcript or other system event never makes a chat unread. By default unread_only keeps only chats whose newest unread message is from the last 14 days (since_days widens it); older ones are counted in older_unread_skipped, and older_unread: true lists them in older_unread_conversations (unread_count only for those already read). A chat the user muted in Teams carries muted: true. " + UNREAD_HINT_DESCRIPTION + " since / until (ISO 8601 date-times) keep chats whose last activity falls in that window; sort picks the order: activity (default, as above), activity_only (most recent first, ignoring favorites and pinned) or title (alphabetical, case-insensitive). Listing never marks anything read (teams_mark_read does). Channels are listed by teams_list_teams_and_channels instead." + UNTRUSTED_DESCRIPTION_SUFFIX2,
|
|
49581
50263
|
annotations: toolAnnotations({ readOnly: true, openWorld: true }),
|
|
49582
50264
|
inputSchema: {
|
|
49583
50265
|
unread_only: unreadOnlyArg,
|
|
49584
50266
|
since_days: listSinceDaysArg,
|
|
49585
|
-
|
|
49586
|
-
|
|
50267
|
+
older_unread: listOlderUnreadArg,
|
|
50268
|
+
query: queryArg("chat title, an untitled chat's participant names or the last-message preview"),
|
|
50269
|
+
search_messages: searchMessagesArg,
|
|
50270
|
+
since: activityBoundArg("since", "at or after"),
|
|
50271
|
+
until: activityBoundArg("until", "at or before"),
|
|
50272
|
+
sort: sortArg,
|
|
50273
|
+
limit: limitArg(MAX_CHATS, "chats", "the head of the sort order kept")
|
|
49587
50274
|
}
|
|
49588
50275
|
},
|
|
49589
|
-
async ({ unread_only, since_days, query, limit }) => {
|
|
50276
|
+
async ({ unread_only, since_days, older_unread, query, search_messages, since, until, sort = "activity", limit }) => {
|
|
50277
|
+
if (older_unread && !unread_only) {
|
|
50278
|
+
throw new McpToolError("older_unread lists what unread_only left out, so it needs unread_only.", {
|
|
50279
|
+
hint: "Pass unread_only: true with older_unread, or drop older_unread."
|
|
50280
|
+
});
|
|
50281
|
+
}
|
|
50282
|
+
if (search_messages && query === void 0) {
|
|
50283
|
+
throw new McpToolError("search_messages needs a query to search for.", {
|
|
50284
|
+
hint: "Pass the text to find as query, or drop search_messages."
|
|
50285
|
+
});
|
|
50286
|
+
}
|
|
50287
|
+
const activeSince = since !== void 0 ? Date.parse(since) : void 0;
|
|
50288
|
+
const activeUntil = until !== void 0 ? Date.parse(until) : void 0;
|
|
50289
|
+
if (activeSince !== void 0 && activeUntil !== void 0 && activeSince > activeUntil) {
|
|
50290
|
+
throw new McpToolError(`since (${since}) is after until (${until}).`, {
|
|
50291
|
+
hint: "Pass a since at or before until."
|
|
50292
|
+
});
|
|
50293
|
+
}
|
|
49590
50294
|
try {
|
|
49591
50295
|
const { rows, retitle, errors: _untitledErrors, ...unreadInfo } = await listSummaries(chatsvc, {
|
|
49592
50296
|
kinds: ["group", "meeting", "oneOnOne", "self"],
|
|
49593
50297
|
unread_only,
|
|
49594
50298
|
since_days,
|
|
49595
|
-
|
|
50299
|
+
older_unread,
|
|
50300
|
+
query,
|
|
50301
|
+
searchMessages: search_messages,
|
|
50302
|
+
activeSince,
|
|
50303
|
+
activeUntil
|
|
49596
50304
|
});
|
|
49597
|
-
|
|
49598
|
-
|
|
49599
|
-
|
|
49600
|
-
const
|
|
50305
|
+
const titledFirst = sort === "title" ? await retitle(rows) : void 0;
|
|
50306
|
+
const ordered = titledFirst?.rows ?? rows;
|
|
50307
|
+
sortChats(ordered, sort, unread_only);
|
|
50308
|
+
const which = sort === "title" || sort === "activity" && !unread_only ? "first" : "most recent";
|
|
50309
|
+
const { rows: kept, truncated } = trimRows(ordered, limit, "start", MAX_CHATS, which);
|
|
50310
|
+
const { rows: chats, errors } = titledFirst ? { rows: kept, errors: titledFirst.errors } : await retitle(kept);
|
|
49601
50311
|
return untrustedResult2({ chats, ...unreadInfo, ...errors ? { errors } : {}, ...truncated ? { truncated } : {} });
|
|
49602
50312
|
} catch (err) {
|
|
49603
50313
|
throw wrapApiError(err, "list chats");
|
|
@@ -49624,13 +50334,13 @@ function registerChannelTools(server, { chatsvc }) {
|
|
|
49624
50334
|
"teams_list_teams_and_channels",
|
|
49625
50335
|
{
|
|
49626
50336
|
title: "List Teams channels",
|
|
49627
|
-
description: "List every channel the signed-in user is in, across all their teams, sorted by team name then channel title. Each has an id, title, team (when Teams makes it determinable), unread hint, last-activity time (ISO 8601), and a last-message preview and sender. Channels the user has hidden in Teams are listed after the rest with hidden: true. Pass an id (or the channel name) to teams_read_conversation to read its posts and replies. Use unread_only for channels with real posts the user has not read, each confirmed by reading past the read marker (a channel that is gone or no longer readable is skipped and counted in skipped_unreachable); hidden channels are left out of it unless include_hidden is set, as Teams shows them no badge. By default unread_only keeps only channels whose newest unread post is from the last 14 days (since_days widens it); older ones are counted in older_unread_skipped, not listed. " + UNREAD_HINT_DESCRIPTION + " Listing never marks anything read. query matches the channel title or
|
|
50337
|
+
description: "List every channel the signed-in user is in, across all their teams, sorted by team name then channel title. Each has an id, title, team (when Teams makes it determinable), unread hint, last-activity time (ISO 8601), and a last-message preview and sender. Channels the user has hidden in Teams are listed after the rest with hidden: true. Pass an id (or the channel name) to teams_read_conversation to read its posts and replies. Use unread_only for channels with real posts the user has not read, each confirmed by reading past the read marker (a channel that is gone or no longer readable is skipped and counted in skipped_unreachable); hidden channels are left out of it unless include_hidden is set, as Teams shows them no badge. By default unread_only keeps only channels whose newest unread post is from the last 14 days (since_days widens it); older ones are counted in older_unread_skipped, not listed. " + UNREAD_HINT_DESCRIPTION + " Listing never marks anything read (teams_mark_read does). query matches the channel title, team name or last-message preview. " + MATCH_REASON_DESCRIPTION + " " + FAVORITES_DESCRIPTION + UNTRUSTED_DESCRIPTION_SUFFIX2,
|
|
49628
50338
|
annotations: toolAnnotations({ readOnly: true, openWorld: true }),
|
|
49629
50339
|
inputSchema: {
|
|
49630
50340
|
unread_only: unreadOnlyArg,
|
|
49631
50341
|
since_days: listSinceDaysArg,
|
|
49632
50342
|
include_hidden: includeHiddenArg,
|
|
49633
|
-
query: queryArg("channel title or
|
|
50343
|
+
query: queryArg("channel title, team name or last-message preview"),
|
|
49634
50344
|
limit: limitArg(MAX_CHANNELS, "channels", "favorites and pinned first, then by team and title, kept")
|
|
49635
50345
|
}
|
|
49636
50346
|
},
|
|
@@ -49657,21 +50367,62 @@ function registerChannelTools(server, { chatsvc }) {
|
|
|
49657
50367
|
// src/tools/conversation.ts
|
|
49658
50368
|
init_zod();
|
|
49659
50369
|
init_dist2();
|
|
49660
|
-
|
|
49661
|
-
|
|
49662
|
-
|
|
49663
|
-
|
|
49664
|
-
|
|
49665
|
-
|
|
49666
|
-
|
|
50370
|
+
|
|
50371
|
+
// src/tools/timezone.ts
|
|
50372
|
+
init_zod();
|
|
50373
|
+
init_dist2();
|
|
50374
|
+
var TIME_ZONE_ENV = "TEAMS_TIME_ZONE";
|
|
50375
|
+
var TIME_ZONE_DESCRIPTION = "tz (an IANA time zone, e.g. America/New_York; default TEAMS_TIME_ZONE) adds time_local \u2014 ISO 8601 with its offset \u2014 next to each message's UTC time.";
|
|
50376
|
+
var tzArg = external_exports.string().refine(isTimeZone, { message: "tz must be an IANA time zone such as America/New_York" }).optional().describe(
|
|
50377
|
+
`IANA time zone (e.g. America/New_York, Europe/London, UTC) to add each message's time_local in, ISO 8601 with its offset; time stays UTC. Defaults to ${TIME_ZONE_ENV} when set, else no time_local.`
|
|
50378
|
+
);
|
|
50379
|
+
function resolveTimeZone(tz, env = process.env) {
|
|
50380
|
+
if (tz !== void 0) return tz;
|
|
50381
|
+
const fromEnv = readEnvVar(TIME_ZONE_ENV, { env });
|
|
50382
|
+
if (fromEnv === void 0) return void 0;
|
|
50383
|
+
if (!isTimeZone(fromEnv)) {
|
|
50384
|
+
throw new McpToolError(`${TIME_ZONE_ENV} "${fromEnv}" is not an IANA time zone.`, {
|
|
50385
|
+
hint: `Set ${TIME_ZONE_ENV} to a name such as America/New_York, or unset it.`
|
|
50386
|
+
});
|
|
50387
|
+
}
|
|
50388
|
+
return fromEnv;
|
|
50389
|
+
}
|
|
50390
|
+
|
|
50391
|
+
// src/tools/cursor.ts
|
|
50392
|
+
init_zod();
|
|
50393
|
+
var messageId = external_exports.string().regex(/^\d+$/, {
|
|
50394
|
+
message: 'a message id is decimal digits, e.g. "1760000000000" \u2014 a teams_get_changes next_cursor is not one; pass its per-conversation after_message_id instead'
|
|
50395
|
+
});
|
|
50396
|
+
var afterMessageIdArg = messageId.optional().describe(
|
|
50397
|
+
"Only return messages newer than this message id (a previous teams_read_conversation next_cursor, a teams_get_changes row's after_message_id, or any message id); the read stops at the first message at or before it. Not teams_get_changes' next_cursor, which is a time token."
|
|
50398
|
+
);
|
|
50399
|
+
var cursorsArg = external_exports.record(external_exports.string(), messageId).optional().describe(
|
|
50400
|
+
"Per-conversation cursors, { conversationId: messageId } (a previous result's next_cursors): each conversation's read stops at the later of its read marker and its cursor, so only unread messages newer than the cursor come back, and a conversation with none past it is left out."
|
|
50401
|
+
);
|
|
50402
|
+
var CURSOR_NO_CACHE_DESCRIPTION = "fetched_at is when this call read Teams: the server holds no cache, so every call reads live (there is nothing to refresh). ";
|
|
50403
|
+
function newestId(messages) {
|
|
50404
|
+
let newest;
|
|
50405
|
+
for (const m of messages) if (newest === void 0 || Number(m.id) > Number(newest)) newest = m.id;
|
|
50406
|
+
return newest;
|
|
49667
50407
|
}
|
|
49668
|
-
|
|
50408
|
+
|
|
50409
|
+
// src/tools/format.ts
|
|
50410
|
+
init_zod();
|
|
50411
|
+
var READ_FORMATS = ["full", "compact", "summary"];
|
|
50412
|
+
var formatArg = external_exports.enum(READ_FORMATS).optional().describe(
|
|
50413
|
+
"How much to return (default full). full: every message field. compact: each message only id, time, time_local, sender, text (and subject when set) \u2014 no reactions, attachments or edited/deleted flags. summary: no messages, just per conversation its counts, newest message time and, for a channel, each thread's root id, subject, reply count and newest time."
|
|
50414
|
+
);
|
|
50415
|
+
var FORMAT_DESCRIPTION = 'format "compact" trims each message to id, time, sender and text, and the conversation to id, kind and title; format "summary" returns no messages, only message_count, newest_time and, for a channel, threads of { root_id, subject, reply_count, newest_time } \u2014 every format keeps the conversation id. ';
|
|
50416
|
+
var NO_ROOTS = /* @__PURE__ */ new Map();
|
|
50417
|
+
function groupThreads(messages, roots = NO_ROOTS) {
|
|
49669
50418
|
const byRoot = /* @__PURE__ */ new Map();
|
|
49670
50419
|
for (const m of messages) {
|
|
49671
50420
|
const rootId = m.replyTo ?? m.id;
|
|
49672
50421
|
let thread = byRoot.get(rootId);
|
|
49673
50422
|
if (thread === void 0) {
|
|
49674
|
-
|
|
50423
|
+
const outside = roots.get(rootId);
|
|
50424
|
+
const root = outside !== void 0 ? { ...outside, outside_window: true } : { id: rootId, missing: true };
|
|
50425
|
+
thread = { root, replies: [] };
|
|
49675
50426
|
byRoot.set(rootId, thread);
|
|
49676
50427
|
}
|
|
49677
50428
|
if (m.replyTo === void 0) thread.root = m;
|
|
@@ -49679,13 +50430,509 @@ function groupThreads(messages) {
|
|
|
49679
50430
|
}
|
|
49680
50431
|
return [...byRoot.values()];
|
|
49681
50432
|
}
|
|
50433
|
+
function compactMessage(m) {
|
|
50434
|
+
return {
|
|
50435
|
+
id: m.id,
|
|
50436
|
+
time: m.time,
|
|
50437
|
+
...m.time_local !== void 0 ? { time_local: m.time_local } : {},
|
|
50438
|
+
sender: m.sender,
|
|
50439
|
+
text: m.text,
|
|
50440
|
+
...m.subject !== void 0 ? { subject: m.subject } : {}
|
|
50441
|
+
};
|
|
50442
|
+
}
|
|
50443
|
+
var isMissing = (root) => "missing" in root;
|
|
50444
|
+
var isOutside = (root) => "outside_window" in root;
|
|
50445
|
+
function newestTime(messages) {
|
|
50446
|
+
const newest = messages.at(-1);
|
|
50447
|
+
if (newest === void 0) return {};
|
|
50448
|
+
return {
|
|
50449
|
+
newest_time: newest.time,
|
|
50450
|
+
...newest.time_local !== void 0 ? { newest_time_local: newest.time_local } : {}
|
|
50451
|
+
};
|
|
50452
|
+
}
|
|
50453
|
+
function summariseThread({ root, replies }) {
|
|
50454
|
+
const subject = isMissing(root) ? void 0 : root.subject;
|
|
50455
|
+
const inWindow = !isMissing(root) && !isOutside(root);
|
|
50456
|
+
return {
|
|
50457
|
+
root_id: root.id,
|
|
50458
|
+
...isMissing(root) ? { root_missing: true } : {},
|
|
50459
|
+
...isOutside(root) ? { root_outside_window: true } : {},
|
|
50460
|
+
...subject !== void 0 ? { subject } : {},
|
|
50461
|
+
reply_count: replies.length,
|
|
50462
|
+
// Replies are oldest first and newer than their root, so the last reply is the newest.
|
|
50463
|
+
...newestTime(inWindow ? [root, ...replies] : replies)
|
|
50464
|
+
};
|
|
50465
|
+
}
|
|
50466
|
+
function compactRoot(root) {
|
|
50467
|
+
if (isMissing(root)) return root;
|
|
50468
|
+
return { ...compactMessage(root), ...isOutside(root) ? { outside_window: true } : {} };
|
|
50469
|
+
}
|
|
50470
|
+
function formatConversation(summary, format) {
|
|
50471
|
+
if (format === "full") return summary;
|
|
50472
|
+
const { id, kind, title, team } = summary;
|
|
50473
|
+
return { id, kind, title, ...team !== void 0 ? { team } : {} };
|
|
50474
|
+
}
|
|
50475
|
+
function formatBody(kind, messages, format, roots = NO_ROOTS) {
|
|
50476
|
+
const channel = kind === "channel";
|
|
50477
|
+
if (format === "summary") {
|
|
50478
|
+
return {
|
|
50479
|
+
message_count: messages.length,
|
|
50480
|
+
...newestTime(messages),
|
|
50481
|
+
...channel ? { threads: groupThreads(messages, roots).map(summariseThread) } : {}
|
|
50482
|
+
};
|
|
50483
|
+
}
|
|
50484
|
+
if (format === "compact") {
|
|
50485
|
+
if (!channel) return { messages: messages.map(compactMessage) };
|
|
50486
|
+
return {
|
|
50487
|
+
threads: groupThreads(messages, roots).map(({ root, replies }) => ({
|
|
50488
|
+
root: compactRoot(root),
|
|
50489
|
+
replies: replies.map(compactMessage)
|
|
50490
|
+
}))
|
|
50491
|
+
};
|
|
50492
|
+
}
|
|
50493
|
+
return channel ? { threads: groupThreads(messages, roots) } : { messages: [...messages] };
|
|
50494
|
+
}
|
|
50495
|
+
|
|
50496
|
+
// src/tools/roots.ts
|
|
50497
|
+
init_dist2();
|
|
50498
|
+
var MAX_ROOT_FETCHES = 25;
|
|
50499
|
+
var ROOT_FETCH_CONCURRENCY = 5;
|
|
50500
|
+
function rootBudget() {
|
|
50501
|
+
return { remaining: MAX_ROOT_FETCHES };
|
|
50502
|
+
}
|
|
50503
|
+
function outsideRootIds(messages) {
|
|
50504
|
+
const held = new Set(messages.map((m) => m.id));
|
|
50505
|
+
const ids = /* @__PURE__ */ new Set();
|
|
50506
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
50507
|
+
const root = messages[i].replyTo;
|
|
50508
|
+
if (root !== void 0 && !held.has(root)) ids.add(root);
|
|
50509
|
+
}
|
|
50510
|
+
return [...ids];
|
|
50511
|
+
}
|
|
50512
|
+
async function fetchOutsideRoots(chatsvc, conversationId, messages, me, { budget, timeZone }) {
|
|
50513
|
+
const wanted = outsideRootIds(messages);
|
|
50514
|
+
const ids = wanted.slice(0, Math.max(0, budget.remaining));
|
|
50515
|
+
budget.remaining -= ids.length;
|
|
50516
|
+
const roots = /* @__PURE__ */ new Map();
|
|
50517
|
+
if (ids.length === 0) return roots;
|
|
50518
|
+
const fetched = await mapWithConcurrency(ids, ROOT_FETCH_CONCURRENCY, async (id) => {
|
|
50519
|
+
try {
|
|
50520
|
+
return await chatsvc.getMessage(conversationId, id);
|
|
50521
|
+
} catch {
|
|
50522
|
+
return void 0;
|
|
50523
|
+
}
|
|
50524
|
+
});
|
|
50525
|
+
fetched.forEach((raw, i) => {
|
|
50526
|
+
if (raw === void 0 || raw.id !== ids[i]) return;
|
|
50527
|
+
const root = normaliseMessage(raw, me, { timeZone });
|
|
50528
|
+
if (root.replyTo === void 0) roots.set(root.id, root);
|
|
50529
|
+
});
|
|
50530
|
+
return roots;
|
|
50531
|
+
}
|
|
50532
|
+
|
|
50533
|
+
// src/tools/markread.ts
|
|
50534
|
+
init_zod();
|
|
50535
|
+
init_dist2();
|
|
50536
|
+
|
|
50537
|
+
// src/compose.ts
|
|
50538
|
+
init_dist2();
|
|
50539
|
+
import { randomInt } from "node:crypto";
|
|
50540
|
+
var HTML_ESCAPES = {
|
|
50541
|
+
"&": "&",
|
|
50542
|
+
"<": "<",
|
|
50543
|
+
">": ">",
|
|
50544
|
+
'"': """,
|
|
50545
|
+
"'": "'"
|
|
50546
|
+
};
|
|
50547
|
+
function escapeHtml(s) {
|
|
50548
|
+
return s.replace(/[&<>"']/g, (c) => HTML_ESCAPES[c]);
|
|
50549
|
+
}
|
|
50550
|
+
var NAMED_EMOJI = {
|
|
50551
|
+
like: { title: "Like", char: "\u{1F44D}" },
|
|
50552
|
+
heart: { title: "Heart", char: "\u2764\uFE0F" },
|
|
50553
|
+
laugh: { title: "Laugh", char: "\u{1F606}" },
|
|
50554
|
+
surprised: { title: "Surprised", char: "\u{1F62E}" },
|
|
50555
|
+
sad: { title: "Sad", char: "\u{1F622}" },
|
|
50556
|
+
angry: { title: "Angry", char: "\u{1F621}" },
|
|
50557
|
+
smile: { title: "Smile", char: "\u{1F642}" },
|
|
50558
|
+
wink: { title: "Wink", char: "\u{1F609}" },
|
|
50559
|
+
cool: { title: "Cool", char: "\u{1F60E}" },
|
|
50560
|
+
hearteyes: { title: "Heart eyes", char: "\u{1F60D}" },
|
|
50561
|
+
fire: { title: "Fire", char: "\u{1F525}" },
|
|
50562
|
+
party: { title: "Party", char: "\u{1F389}" }
|
|
50563
|
+
};
|
|
50564
|
+
var UNICODE_KEY = /^([0-9a-f]{4,6}(?:-[0-9a-f]{4,6})*)_([a-z0-9]+)$/;
|
|
50565
|
+
function emojiSpan(key) {
|
|
50566
|
+
let title;
|
|
50567
|
+
let char;
|
|
50568
|
+
const named = NAMED_EMOJI[key];
|
|
50569
|
+
if (named !== void 0) {
|
|
50570
|
+
({ title, char } = named);
|
|
50571
|
+
} else {
|
|
50572
|
+
const m = UNICODE_KEY.exec(key);
|
|
50573
|
+
if (m === null) return void 0;
|
|
50574
|
+
const points = m[1].split("-").map((h) => parseInt(h, 16));
|
|
50575
|
+
if (points.some((p) => p > 1114111)) return void 0;
|
|
50576
|
+
char = String.fromCodePoint(...points);
|
|
50577
|
+
title = m[2];
|
|
50578
|
+
}
|
|
50579
|
+
const t = escapeHtml(title);
|
|
50580
|
+
return `<span contenteditable="false" title="${t}" type="(${key})" class="animated-emoticon-20-${key}" itemscope><img itemscope itemtype="http://schema.skype.com/Emoji" itemid="${key}" src="https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons/${key}/default/20_f.png" title="${t}" alt="${escapeHtml(char)}" style="width:20px;height:20px;"></span>`;
|
|
50581
|
+
}
|
|
50582
|
+
function renderPlain(text) {
|
|
50583
|
+
let out = "";
|
|
50584
|
+
let at = 0;
|
|
50585
|
+
const shortcode = /:([a-z0-9_-]+):/g;
|
|
50586
|
+
for (let m = shortcode.exec(text); m !== null; m = shortcode.exec(text)) {
|
|
50587
|
+
const span = emojiSpan(m[1]);
|
|
50588
|
+
if (span === void 0) {
|
|
50589
|
+
shortcode.lastIndex = m.index + m[0].length - 1;
|
|
50590
|
+
continue;
|
|
50591
|
+
}
|
|
50592
|
+
out += escapeLines(text.slice(at, m.index)) + span;
|
|
50593
|
+
at = shortcode.lastIndex;
|
|
50594
|
+
}
|
|
50595
|
+
return out + escapeLines(text.slice(at));
|
|
50596
|
+
}
|
|
50597
|
+
var escapeLines = (s) => escapeHtml(s).replace(/\r?\n/g, "<br>");
|
|
50598
|
+
var isWordChar = (c) => c !== void 0 && /[\p{L}\p{N}_]/u.test(c);
|
|
50599
|
+
function locate(text, name, taken) {
|
|
50600
|
+
const free = (s, e) => taken.every(([ts, te]) => e <= ts || s >= te);
|
|
50601
|
+
const find = (needle, ci, wordStart) => {
|
|
50602
|
+
const hay = ci ? text.toLowerCase() : text;
|
|
50603
|
+
const n = ci ? needle.toLowerCase() : needle;
|
|
50604
|
+
for (let i = hay.indexOf(n); i >= 0; i = hay.indexOf(n, i + 1)) {
|
|
50605
|
+
const end = i + n.length;
|
|
50606
|
+
if (isWordChar(text[end]) || wordStart && isWordChar(text[i - 1])) continue;
|
|
50607
|
+
if (free(i, end)) return [i, end];
|
|
50608
|
+
}
|
|
50609
|
+
return void 0;
|
|
50610
|
+
};
|
|
50611
|
+
return find(`@${name}`, false, false) ?? find(`@${name}`, true, false) ?? find(name, true, true);
|
|
50612
|
+
}
|
|
50613
|
+
function renderMessageHtml(text, mentions) {
|
|
50614
|
+
const placed = [];
|
|
50615
|
+
for (const m of mentions) {
|
|
50616
|
+
const range = locate(
|
|
50617
|
+
text,
|
|
50618
|
+
m.text,
|
|
50619
|
+
placed.map((p) => [p.start, p.end])
|
|
50620
|
+
);
|
|
50621
|
+
if (range === void 0) {
|
|
50622
|
+
throw new McpToolError(`The mention "${m.text}" does not appear in the text.`, {
|
|
50623
|
+
hint: "name_in_text must be written in text (as @name or name) once per mention."
|
|
50624
|
+
});
|
|
50625
|
+
}
|
|
50626
|
+
placed.push({ start: range[0], end: range[1], mri: m.mri });
|
|
50627
|
+
}
|
|
50628
|
+
placed.sort((a, b) => a.start - b.start);
|
|
50629
|
+
let html = "";
|
|
50630
|
+
let at = 0;
|
|
50631
|
+
const out = [];
|
|
50632
|
+
placed.forEach((p, n) => {
|
|
50633
|
+
const shown = text.slice(p.start, p.end).replace(/^@/, "");
|
|
50634
|
+
html += renderPlain(text.slice(at, p.start));
|
|
50635
|
+
html += `<span itemscope itemtype="http://schema.skype.com/Mention" itemid="${n}">${escapeHtml(shown)}</span>`;
|
|
50636
|
+
out.push({ itemid: String(n), mri: p.mri, displayName: shown });
|
|
50637
|
+
at = p.end;
|
|
50638
|
+
});
|
|
50639
|
+
html += renderPlain(text.slice(at));
|
|
50640
|
+
return { html: `<p>${html}</p>`, mentions: out };
|
|
50641
|
+
}
|
|
50642
|
+
function mentionsProperty(mentions) {
|
|
50643
|
+
return JSON.stringify(
|
|
50644
|
+
mentions.map((m) => ({
|
|
50645
|
+
"@type": "http://schema.skype.com/Mention",
|
|
50646
|
+
itemid: m.itemid,
|
|
50647
|
+
mri: m.mri,
|
|
50648
|
+
mentionType: "person",
|
|
50649
|
+
displayName: m.displayName
|
|
50650
|
+
}))
|
|
50651
|
+
);
|
|
50652
|
+
}
|
|
50653
|
+
var QUOTE_PREVIEW_CHARS = 200;
|
|
50654
|
+
function clipText(s, max, ellipsis = "") {
|
|
50655
|
+
if (s.length <= max) return s;
|
|
50656
|
+
let end = Math.max(0, max - ellipsis.length);
|
|
50657
|
+
const last = s.charCodeAt(end - 1);
|
|
50658
|
+
if (last >= 55296 && last <= 56319) end -= 1;
|
|
50659
|
+
return s.slice(0, end) + ellipsis;
|
|
50660
|
+
}
|
|
50661
|
+
function quoteHtml(q) {
|
|
50662
|
+
const preview = clipText(q.text, QUOTE_PREVIEW_CHARS, "\u2026");
|
|
50663
|
+
const id = escapeHtml(q.id);
|
|
50664
|
+
return `<blockquote itemscope itemtype="http://schema.skype.com/Reply" itemid="${id}"><strong itemprop="mri" itemid="${escapeHtml(q.senderMri)}">${escapeHtml(q.senderName)}</strong><span itemprop="time" itemid="${id}"></span><p itemprop="preview">${escapeHtml(preview)}</p></blockquote>`;
|
|
50665
|
+
}
|
|
50666
|
+
function qtdMsgsProperty(q) {
|
|
50667
|
+
return JSON.stringify([{ messageId: q.id, sender: q.senderMri, time: Number(q.id) }]);
|
|
50668
|
+
}
|
|
50669
|
+
function newClientMessageId() {
|
|
50670
|
+
let id = String(randomInt(1, 10));
|
|
50671
|
+
for (let i = 0; i < 18; i++) id += String(randomInt(0, 10));
|
|
50672
|
+
return id;
|
|
50673
|
+
}
|
|
50674
|
+
function buildSendBody(i) {
|
|
50675
|
+
const time3 = i.now.toISOString();
|
|
50676
|
+
return {
|
|
50677
|
+
id: "-1",
|
|
50678
|
+
type: "Message",
|
|
50679
|
+
conversationid: i.conversationId,
|
|
50680
|
+
conversationLink: `blah/${i.conversationId}`,
|
|
50681
|
+
from: i.meMri,
|
|
50682
|
+
fromUserId: i.meMri,
|
|
50683
|
+
composetime: time3,
|
|
50684
|
+
originalarrivaltime: time3,
|
|
50685
|
+
content: i.content,
|
|
50686
|
+
messagetype: "RichText/Html",
|
|
50687
|
+
contenttype: "Text",
|
|
50688
|
+
imdisplayname: i.meName,
|
|
50689
|
+
clientmessageid: i.clientmessageid,
|
|
50690
|
+
callId: "",
|
|
50691
|
+
state: 0,
|
|
50692
|
+
version: "0",
|
|
50693
|
+
amsreferences: [],
|
|
50694
|
+
properties: {
|
|
50695
|
+
importance: "",
|
|
50696
|
+
subject: "",
|
|
50697
|
+
title: "",
|
|
50698
|
+
cards: "[]",
|
|
50699
|
+
links: "[]",
|
|
50700
|
+
mentions: i.mentions ?? "[]",
|
|
50701
|
+
onbehalfof: null,
|
|
50702
|
+
files: "[]",
|
|
50703
|
+
policyViolation: null,
|
|
50704
|
+
formatVariant: "TEAMS",
|
|
50705
|
+
...i.qtdMsgs !== void 0 ? { qtdMsgs: i.qtdMsgs } : {}
|
|
50706
|
+
},
|
|
50707
|
+
crossPostChannels: []
|
|
50708
|
+
};
|
|
50709
|
+
}
|
|
50710
|
+
|
|
50711
|
+
// src/tools/markread.ts
|
|
50712
|
+
var TOOL = "teams_mark_read";
|
|
50713
|
+
var NEWEST_PAGE = 50;
|
|
50714
|
+
var PREVIEW_CHARS2 = 200;
|
|
50715
|
+
var MARK_CONCURRENCY = 4;
|
|
50716
|
+
var markReadArg = external_exports.boolean().optional().describe(
|
|
50717
|
+
'After the read, also mark it read in Teams: move the read marker of each conversation returned up to the newest message returned (default false \u2014 the read leaves the unread badges alone). Never moves a marker backwards, and never past an unread message the caller did not receive: a conversation whose read was cut short is left as it was (marked_read: { skipped, hint }). Not allowed with format "summary", which returns no message text. A write, so it asks the user to confirm first, as teams_mark_read does.'
|
|
50718
|
+
);
|
|
50719
|
+
function assertMarkReadFormat(markRead, format) {
|
|
50720
|
+
if (markRead && format === "summary") {
|
|
50721
|
+
throw new McpToolError('mark_read cannot be combined with format "summary": a summary returns no messages, so nothing would have been read.', {
|
|
50722
|
+
hint: 'Read with format "full" or "compact" to mark what is returned, or use teams_mark_read to mark a conversation read deliberately.'
|
|
50723
|
+
});
|
|
50724
|
+
}
|
|
50725
|
+
}
|
|
50726
|
+
var MARK_READ_DESCRIPTION = `By default this does NOT mark anything read \u2014 the user's Teams unread badges are unaffected; pass mark_read: true (or use teams_mark_read) to clear them. mark_read never marks a message the caller did not receive: it is refused with format "summary" (compact is fine), and a conversation whose read was cut short, leaving unread messages older than those returned, keeps its marker and reports marked_read: { skipped: "truncated" (or "since"), hint }. `;
|
|
50727
|
+
function horizonPath(conversationId) {
|
|
50728
|
+
return `/users/ME/conversations/${encodeURIComponent(conversationId)}/properties?name=consumptionhorizon`;
|
|
50729
|
+
}
|
|
50730
|
+
function newestMessageId(messages) {
|
|
50731
|
+
let best;
|
|
50732
|
+
for (const m of messages) {
|
|
50733
|
+
const n = Number(m.id);
|
|
50734
|
+
if (Number.isFinite(n) && (best === void 0 || n > Number(best))) best = m.id;
|
|
50735
|
+
}
|
|
50736
|
+
return best;
|
|
50737
|
+
}
|
|
50738
|
+
function horizonMessageId(conv) {
|
|
50739
|
+
const h = readHorizon(conv);
|
|
50740
|
+
return h > 0 ? String(h) : null;
|
|
50741
|
+
}
|
|
50742
|
+
function advancesHorizon(conv, target) {
|
|
50743
|
+
if (target === void 0) return false;
|
|
50744
|
+
const n = Number(target);
|
|
50745
|
+
return Number.isFinite(n) && n > readHorizon(conv);
|
|
50746
|
+
}
|
|
50747
|
+
async function confirmMarks(ctx, opts) {
|
|
50748
|
+
const { plans } = opts;
|
|
50749
|
+
const many = plans.length > 1;
|
|
50750
|
+
return confirmWrite(ctx, {
|
|
50751
|
+
tool: opts.tool,
|
|
50752
|
+
action: "chat.mark_read",
|
|
50753
|
+
message: "Review and confirm marking these Teams messages read:",
|
|
50754
|
+
summary: many ? `Mark ${plans.length} conversations read up to their newest returned message` : `Mark a ${plans[0].summary.kind} ${JSON.stringify(plans[0].summary.title)} read up to message ${plans[0].target}`,
|
|
50755
|
+
account: opts.me,
|
|
50756
|
+
...many ? { payload: plans.map((p) => ({ conversation: p.summary.id, up_to_message_id: p.target })) } : { target: `${plans[0].summary.id}/${plans[0].target}`, request: { method: "PUT", path: horizonPath(plans[0].summary.id) } },
|
|
50757
|
+
preview: {
|
|
50758
|
+
conversations: untrustedField(
|
|
50759
|
+
plans.map((p) => ({
|
|
50760
|
+
id: p.summary.id,
|
|
50761
|
+
title: p.summary.title,
|
|
50762
|
+
kind: p.summary.kind,
|
|
50763
|
+
previous_horizon_message_id: p.previous,
|
|
50764
|
+
up_to_message_id: p.target
|
|
50765
|
+
}))
|
|
50766
|
+
),
|
|
50767
|
+
...opts.note !== void 0 ? { note: opts.note } : {}
|
|
50768
|
+
},
|
|
50769
|
+
confirmToken: opts.confirmToken
|
|
50770
|
+
});
|
|
50771
|
+
}
|
|
50772
|
+
function unconfirmedWhy(e) {
|
|
50773
|
+
const status = outcomeUnknownStatus(e);
|
|
50774
|
+
return e.timedOut ? "it did not answer in time" : status !== void 0 ? `it answered HTTP ${status}` : "the connection dropped";
|
|
50775
|
+
}
|
|
50776
|
+
async function applyMarks(chatsvc, plans) {
|
|
50777
|
+
const results = await mapWithConcurrency(plans, MARK_CONCURRENCY, async (p) => {
|
|
50778
|
+
try {
|
|
50779
|
+
await chatsvc.setConsumptionHorizon(p.summary.id, p.target);
|
|
50780
|
+
return { marked_read: true };
|
|
50781
|
+
} catch (e) {
|
|
50782
|
+
if (e instanceof WriteOutcomeUnknownError) {
|
|
50783
|
+
return {
|
|
50784
|
+
marked_read: false,
|
|
50785
|
+
mark_read_warning: `Teams did not confirm moving the read marker (${unconfirmedWhy(e)}); it may have moved \u2014 retrying is harmless.`
|
|
50786
|
+
};
|
|
50787
|
+
}
|
|
50788
|
+
return { marked_read: false, mark_read_warning: wrapApiError(e, "mark this conversation read").message };
|
|
50789
|
+
}
|
|
50790
|
+
});
|
|
50791
|
+
return new Map(plans.map((p, i) => [p.summary.id, results[i]]));
|
|
50792
|
+
}
|
|
50793
|
+
function registerMarkReadTools(server, { chatsvc }) {
|
|
50794
|
+
server.registerTool(
|
|
50795
|
+
TOOL,
|
|
50796
|
+
{
|
|
50797
|
+
title: "Mark a Teams conversation read",
|
|
50798
|
+
description: `Mark a chat or channel read in Teams, clearing its unread badge: moves the signed-in user's read marker up to up_to_message_id (from teams_read_conversation), or by default up to the newest message in the conversation. conversation is an id or name as for teams_read_conversation; "${SELF_CHAT}" (or "notes" / "self") is the user's own notes self-chat \u2014 use it to try this tool. The marker never moves backwards: when it is already at or past the target, nothing is written and status is "already_read". Returns the conversation, previous_horizon_message_id (null if it was never opened) and new_horizon_message_id; status "unknown" means Teams did not confirm the move \u2014 retrying is harmless. teams_read_conversation and teams_get_unread can do the same after a read with mark_read. ` + CONFIRM_FLOW_SENTENCE + " The preview shows the conversation, the message the marker moves to and where it was. " + CONFIRM_INJECTION_RULE + UNTRUSTED_DESCRIPTION_SUFFIX2,
|
|
50799
|
+
annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
|
|
50800
|
+
inputSchema: {
|
|
50801
|
+
conversation: external_exports.string().min(1).describe(
|
|
50802
|
+
`The conversation id (or "${SELF_CHAT}" \u2014 also by the name "notes" or "self" \u2014 for the self-chat), or a case-insensitive substring of the chat title, channel name, team name or an untitled chat's participant names.`
|
|
50803
|
+
),
|
|
50804
|
+
up_to_message_id: external_exports.string().min(1).optional().describe(
|
|
50805
|
+
"Mark read up to and including this message, as teams_read_conversation lists it (default: the newest message in the conversation). Messages after it stay unread."
|
|
50806
|
+
),
|
|
50807
|
+
confirmToken: confirmTokenParam
|
|
50808
|
+
}
|
|
50809
|
+
},
|
|
50810
|
+
async ({ conversation, up_to_message_id, confirmToken }, ctx) => {
|
|
50811
|
+
try {
|
|
50812
|
+
const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
|
|
50813
|
+
const summary = await resolveListed(chatsvc, raw, me, conversation, "mark read");
|
|
50814
|
+
const conv = raw.find((c) => c.id === summary.id) ?? { id: summary.id };
|
|
50815
|
+
const previous = horizonMessageId(conv);
|
|
50816
|
+
const page = await chatsvc.getMessages(summary.id, { max: NEWEST_PAGE, pageSize: NEWEST_PAGE });
|
|
50817
|
+
let target;
|
|
50818
|
+
if (up_to_message_id !== void 0) {
|
|
50819
|
+
target = await chatsvc.getMessage(summary.id, up_to_message_id);
|
|
50820
|
+
if (target === void 0) {
|
|
50821
|
+
throw new McpToolError(`There is no message ${up_to_message_id} in this conversation to mark read up to.`, {
|
|
50822
|
+
hint: "Take message ids from teams_read_conversation, or leave up_to_message_id out to mark it all read."
|
|
50823
|
+
});
|
|
50824
|
+
}
|
|
50825
|
+
} else {
|
|
50826
|
+
const newest = newestMessageId(page);
|
|
50827
|
+
target = page.find((m) => m.id === newest);
|
|
50828
|
+
}
|
|
50829
|
+
if (!advancesHorizon(conv, target?.id)) {
|
|
50830
|
+
return untrustedResult2({
|
|
50831
|
+
status: "already_read",
|
|
50832
|
+
conversation: summary,
|
|
50833
|
+
previous_horizon_message_id: previous,
|
|
50834
|
+
new_horizon_message_id: previous,
|
|
50835
|
+
hint: target === void 0 ? "The conversation has no messages, so there is nothing to mark read." : `The read marker is already at or past message ${target.id}; it never moves backwards, so nothing was changed.`
|
|
50836
|
+
});
|
|
50837
|
+
}
|
|
50838
|
+
const to = target.id;
|
|
50839
|
+
const gate = await confirmWrite(ctx, {
|
|
50840
|
+
tool: TOOL,
|
|
50841
|
+
action: "chat.mark_read",
|
|
50842
|
+
message: "Review and confirm marking this Teams conversation read:",
|
|
50843
|
+
// The title is someone else's text: JSON-quoted so it cannot break out of its quotes.
|
|
50844
|
+
summary: `Mark ${summary.kind} ${JSON.stringify(summary.title)} read up to message ${to}`,
|
|
50845
|
+
// The signed-in user, so an approval minted under one account never marks another's chats.
|
|
50846
|
+
account: me,
|
|
50847
|
+
target: `${summary.id}/${to}`,
|
|
50848
|
+
// The client time in the body is minted when the marker moves, so it is not bound.
|
|
50849
|
+
request: { method: "PUT", path: horizonPath(summary.id) },
|
|
50850
|
+
preview: {
|
|
50851
|
+
conversation: untrustedField({ id: summary.id, title: summary.title, kind: summary.kind }),
|
|
50852
|
+
up_to_message: untrustedField({
|
|
50853
|
+
id: to,
|
|
50854
|
+
sender: target.imdisplayname?.trim() || senderMri(target.from) || "unknown",
|
|
50855
|
+
preview: clipText(htmlToText(target.content ?? ""), PREVIEW_CHARS2)
|
|
50856
|
+
}),
|
|
50857
|
+
previous_horizon_message_id: previous
|
|
50858
|
+
},
|
|
50859
|
+
confirmToken
|
|
50860
|
+
});
|
|
50861
|
+
if (gate) return gate;
|
|
50862
|
+
const stillUnread = page.some((m) => isUnread(m, Number(to), me));
|
|
50863
|
+
const after = confirmedSummary(summary, stillUnread);
|
|
50864
|
+
try {
|
|
50865
|
+
await chatsvc.setConsumptionHorizon(summary.id, to);
|
|
50866
|
+
} catch (e) {
|
|
50867
|
+
if (!(e instanceof WriteOutcomeUnknownError)) throw e;
|
|
50868
|
+
return untrustedResult2({
|
|
50869
|
+
status: "unknown",
|
|
50870
|
+
conversation: summary,
|
|
50871
|
+
previous_horizon_message_id: previous,
|
|
50872
|
+
new_horizon_message_id: to,
|
|
50873
|
+
warning: `Teams did not confirm moving the read marker (${unconfirmedWhy(e)}); it may have moved. Retrying is harmless \u2014 moving it to the same message again is one move.`
|
|
50874
|
+
});
|
|
50875
|
+
}
|
|
50876
|
+
return untrustedResult2({
|
|
50877
|
+
status: "marked_read",
|
|
50878
|
+
conversation: after,
|
|
50879
|
+
previous_horizon_message_id: previous,
|
|
50880
|
+
new_horizon_message_id: to
|
|
50881
|
+
});
|
|
50882
|
+
} catch (err) {
|
|
50883
|
+
throw wrapApiError(err, "mark the conversation read");
|
|
50884
|
+
}
|
|
50885
|
+
}
|
|
50886
|
+
);
|
|
50887
|
+
}
|
|
50888
|
+
|
|
50889
|
+
// src/tools/conversation.ts
|
|
50890
|
+
var MAX_MESSAGES = 500;
|
|
50891
|
+
var MAX_RAW_MESSAGES = 4e3;
|
|
50892
|
+
var MAX_CANDIDATES = 10;
|
|
50893
|
+
function arrivalMs(m) {
|
|
50894
|
+
const n = Number(m.id);
|
|
50895
|
+
if (Number.isFinite(n) && n > 0) return n;
|
|
50896
|
+
return Date.parse(m.originalarrivaltime ?? m.composetime ?? "");
|
|
50897
|
+
}
|
|
49682
50898
|
function confirmUnread(summary, unreadCount, exact) {
|
|
49683
50899
|
if (unreadCount > 0) return confirmedSummary(summary, true);
|
|
49684
50900
|
return exact ? confirmedSummary(summary, false) : summary;
|
|
49685
50901
|
}
|
|
49686
50902
|
function describeCandidate(s) {
|
|
49687
50903
|
const where = s.team !== void 0 ? ` in ${s.team}` : "";
|
|
49688
|
-
|
|
50904
|
+
const how = s.match_reason !== void 0 ? `, matched by ${s.match_reason}` : "";
|
|
50905
|
+
return `"${s.title}"${where} (${s.kind}, id ${s.id}${how})`;
|
|
50906
|
+
}
|
|
50907
|
+
var AmbiguousConversationError = class extends McpToolError {
|
|
50908
|
+
constructor(query, matches, verb) {
|
|
50909
|
+
const named = matches.slice(0, MAX_CANDIDATES).map(describeCandidate).join("; ");
|
|
50910
|
+
const more = matches.length > MAX_CANDIDATES ? ` (first ${MAX_CANDIDATES} shown)` : "";
|
|
50911
|
+
super(`"${query}" matches ${matches.length} conversations${more}: ${named}.`, {
|
|
50912
|
+
hint: `Pass the id of the one to ${verb} as conversation.`
|
|
50913
|
+
});
|
|
50914
|
+
this.query = query;
|
|
50915
|
+
this.matches = matches;
|
|
50916
|
+
this.name = "AmbiguousConversationError";
|
|
50917
|
+
}
|
|
50918
|
+
query;
|
|
50919
|
+
matches;
|
|
50920
|
+
};
|
|
50921
|
+
function ambiguousResult(err) {
|
|
50922
|
+
return {
|
|
50923
|
+
ambiguous: true,
|
|
50924
|
+
query: err.query,
|
|
50925
|
+
match_count: err.matches.length,
|
|
50926
|
+
candidates: err.matches.slice(0, MAX_CANDIDATES).map((s) => ({
|
|
50927
|
+
id: s.id,
|
|
50928
|
+
title: s.title,
|
|
50929
|
+
kind: s.kind,
|
|
50930
|
+
...s.team !== void 0 ? { team: s.team } : {},
|
|
50931
|
+
...s.lastActivity !== void 0 ? { lastActivity: s.lastActivity } : {},
|
|
50932
|
+
...s.match_reason !== void 0 ? { match_reason: s.match_reason } : {}
|
|
50933
|
+
})),
|
|
50934
|
+
hint: "pass one id as conversation"
|
|
50935
|
+
};
|
|
49689
50936
|
}
|
|
49690
50937
|
function resolveConversation(summaries, conversation, verb) {
|
|
49691
50938
|
const matches = matchConversations(summaries, conversation);
|
|
@@ -49694,80 +50941,199 @@ function resolveConversation(summaries, conversation, verb) {
|
|
|
49694
50941
|
hint: "List them with teams_list_chats or teams_list_teams_and_channels and pass an id."
|
|
49695
50942
|
});
|
|
49696
50943
|
}
|
|
49697
|
-
if (matches.length > 1)
|
|
49698
|
-
const named = matches.slice(0, MAX_CANDIDATES).map(describeCandidate).join("; ");
|
|
49699
|
-
const more = matches.length > MAX_CANDIDATES ? ` (first ${MAX_CANDIDATES} shown)` : "";
|
|
49700
|
-
throw new McpToolError(`"${conversation}" matches ${matches.length} conversations${more}: ${named}.`, {
|
|
49701
|
-
hint: `Pass the id of the one to ${verb} as conversation.`
|
|
49702
|
-
});
|
|
49703
|
-
}
|
|
50944
|
+
if (matches.length > 1) throw new AmbiguousConversationError(conversation, matches, verb);
|
|
49704
50945
|
return matches[0];
|
|
49705
50946
|
}
|
|
49706
|
-
|
|
50947
|
+
function listedResolver(chatsvc, raw, me, verb) {
|
|
49707
50948
|
const summaries = summariseAll(raw, me);
|
|
49708
|
-
|
|
49709
|
-
|
|
49710
|
-
|
|
50949
|
+
let titled;
|
|
50950
|
+
return async (conversation) => {
|
|
50951
|
+
if (SELF_CHAT_ALIASES.has(conversation.trim().toLowerCase())) return resolveConversation(summaries, conversation, verb);
|
|
50952
|
+
const exact = summaries.find((s) => s.id === conversation);
|
|
50953
|
+
if (exact) return resolveConversation(await enrichTitles(chatsvc, raw, me, [exact]), conversation, verb);
|
|
50954
|
+
titled ??= enrichTitles(chatsvc, raw, me, summaries);
|
|
50955
|
+
return resolveConversation(await titled, conversation, verb);
|
|
50956
|
+
};
|
|
50957
|
+
}
|
|
50958
|
+
async function resolveListed(chatsvc, raw, me, conversation, verb) {
|
|
50959
|
+
return listedResolver(chatsvc, raw, me, verb)(conversation);
|
|
50960
|
+
}
|
|
50961
|
+
var MAX_CONVERSATIONS = 20;
|
|
50962
|
+
var READ_CONCURRENCY = 4;
|
|
50963
|
+
async function readOne(chatsvc, raw, me, summary, { unreadOnly, since, afterMessageId, limit, timeZone, format, roots }) {
|
|
50964
|
+
const conv = raw.find((c) => c.id === summary.id) ?? { id: summary.id };
|
|
50965
|
+
const horizon = readHorizon(conv);
|
|
50966
|
+
const cutoff = since !== void 0 ? Date.parse(since) : void 0;
|
|
50967
|
+
const cursor = afterMessageId !== void 0 ? Number(afterMessageId) : void 0;
|
|
50968
|
+
const wanted = (m) => isUserMessage(m) && (!unreadOnly || isUnread(m, horizon, me));
|
|
50969
|
+
const limited = makeLimitedStopAt(unreadOnly ? horizon : void 0, wanted, limit);
|
|
50970
|
+
let windowCut = false;
|
|
50971
|
+
let sinceCut = false;
|
|
50972
|
+
let capped = false;
|
|
50973
|
+
let lastSeen;
|
|
50974
|
+
const stopAt = (m) => {
|
|
50975
|
+
lastSeen = Number(m.id);
|
|
50976
|
+
const atHorizon = unreadOnly && Number(m.id) <= horizon;
|
|
50977
|
+
const at = arrivalMs(m);
|
|
50978
|
+
const atCursor = cursor !== void 0 && Number(m.id) <= cursor;
|
|
50979
|
+
const atSince = cutoff !== void 0 && Number.isFinite(at) && at < cutoff;
|
|
50980
|
+
if (!atHorizon && (atCursor || atSince)) {
|
|
50981
|
+
if (Number(m.id) > horizon) {
|
|
50982
|
+
windowCut = true;
|
|
50983
|
+
if (atSince && !atCursor) sinceCut = true;
|
|
50984
|
+
}
|
|
50985
|
+
return true;
|
|
50986
|
+
}
|
|
50987
|
+
return limited.stopAt(m);
|
|
50988
|
+
};
|
|
50989
|
+
const fetched = await chatsvc.getMessages(summary.id, {
|
|
50990
|
+
stopAt,
|
|
50991
|
+
max: MAX_RAW_MESSAGES,
|
|
50992
|
+
onCapped: () => capped = true
|
|
50993
|
+
});
|
|
50994
|
+
const returned = fetched.filter(wanted);
|
|
50995
|
+
const newest = newestId(returned);
|
|
50996
|
+
const next_cursor = newest ?? afterMessageId;
|
|
50997
|
+
const messages = oldestFirst(returned).map((m) => normaliseMessage(m, me, { timeZone }));
|
|
50998
|
+
const unread_count = fetched.filter((m) => wanted(m) && isUnread(m, horizon, me)).length;
|
|
50999
|
+
const outsideRoots = summary.kind === "channel" ? await fetchOutsideRoots(chatsvc, summary.id, messages, me, { budget: roots, timeZone }) : void 0;
|
|
51000
|
+
const truncated = limited.truncated || capped;
|
|
51001
|
+
const exact = !truncated && !windowCut;
|
|
51002
|
+
const limitCut = truncated && (lastSeen === void 0 || !(lastSeen <= horizon));
|
|
51003
|
+
const skip = limitCut ? {
|
|
51004
|
+
skipped: "truncated",
|
|
51005
|
+
hint: `The read marker was left where it was: the limit cut this read, so unread messages older than those returned were not returned. Read again with a larger limit (max ${MAX_MESSAGES}) to mark it read, or use teams_mark_read to mark it all read deliberately.`
|
|
51006
|
+
} : sinceCut ? {
|
|
51007
|
+
skipped: "since",
|
|
51008
|
+
hint: "The read marker was left where it was: the since cutoff left out unread messages older than those returned. Read again with an earlier since (or without it) to mark it read, or use teams_mark_read to mark it all read deliberately."
|
|
51009
|
+
} : void 0;
|
|
51010
|
+
const result = {
|
|
51011
|
+
conversation: formatConversation(confirmUnread(summary, unread_count, exact), format),
|
|
51012
|
+
unread_count,
|
|
51013
|
+
...exact ? {} : { unread_count_scope: "window" },
|
|
51014
|
+
...formatBody(summary.kind, messages, format, outsideRoots),
|
|
51015
|
+
...truncated ? {
|
|
51016
|
+
truncated: {
|
|
51017
|
+
returned: messages.length,
|
|
51018
|
+
hint: `Only the newest ${messages.length} messages were returned; pass a larger limit (max ${MAX_MESSAGES}) or a since time to read further back.`
|
|
51019
|
+
}
|
|
51020
|
+
} : {},
|
|
51021
|
+
...next_cursor !== void 0 ? { next_cursor } : {}
|
|
51022
|
+
};
|
|
51023
|
+
return { summary, conv, newest, ...skip !== void 0 ? { skip } : {}, result };
|
|
51024
|
+
}
|
|
51025
|
+
function readError(conversation, err, id) {
|
|
51026
|
+
const e = wrapApiError(err, "read this conversation");
|
|
51027
|
+
return {
|
|
51028
|
+
conversation,
|
|
51029
|
+
...id !== void 0 ? { id } : {},
|
|
51030
|
+
error: e.message,
|
|
51031
|
+
...e.hint !== void 0 ? { hint: e.hint } : {}
|
|
51032
|
+
};
|
|
51033
|
+
}
|
|
51034
|
+
async function readMany(chatsvc, raw, me, conversations, opts) {
|
|
51035
|
+
const resolve2 = listedResolver(chatsvc, raw, me, "read");
|
|
51036
|
+
const errors = [];
|
|
51037
|
+
const slots = [];
|
|
51038
|
+
const seen = /* @__PURE__ */ new Set();
|
|
51039
|
+
for (const asked of new Set(conversations)) {
|
|
51040
|
+
try {
|
|
51041
|
+
const summary = await resolve2(asked);
|
|
51042
|
+
if (seen.has(summary.id)) continue;
|
|
51043
|
+
seen.add(summary.id);
|
|
51044
|
+
slots.push({ asked, summary });
|
|
51045
|
+
} catch (err) {
|
|
51046
|
+
if (err instanceof AmbiguousConversationError) slots.push({ ambiguous: ambiguousResult(err) });
|
|
51047
|
+
else errors.push(readError(asked, err));
|
|
51048
|
+
}
|
|
51049
|
+
}
|
|
51050
|
+
const reads = await mapWithConcurrency(slots, READ_CONCURRENCY, async (slot) => {
|
|
51051
|
+
if ("ambiguous" in slot) return { ok: true, result: slot };
|
|
51052
|
+
try {
|
|
51053
|
+
return { ok: true, result: await readOne(chatsvc, raw, me, slot.summary, opts) };
|
|
51054
|
+
} catch (err) {
|
|
51055
|
+
return { ok: false, error: readError(slot.asked, err, slot.summary.id) };
|
|
51056
|
+
}
|
|
51057
|
+
});
|
|
51058
|
+
const results = [];
|
|
51059
|
+
for (const r of reads) {
|
|
51060
|
+
if (r.ok) results.push(r.result);
|
|
51061
|
+
else errors.push(r.error);
|
|
51062
|
+
}
|
|
51063
|
+
const order = new Map(conversations.map((c, i) => [c, i]));
|
|
51064
|
+
errors.sort((a, b) => (order.get(a.conversation) ?? 0) - (order.get(b.conversation) ?? 0));
|
|
51065
|
+
return { reads: results, errors };
|
|
49711
51066
|
}
|
|
49712
51067
|
function registerConversationTools(server, { chatsvc }) {
|
|
49713
51068
|
server.registerTool(
|
|
49714
51069
|
"teams_read_conversation",
|
|
49715
51070
|
{
|
|
49716
51071
|
title: "Read a Teams chat or channel",
|
|
49717
|
-
description: `Read the messages of any chat or channel the signed-in user is in, by id (from teams_list_chats / teams_list_teams_and_channels) or by name, without opening it in Teams. "48:notes" (or the name "notes" / "self") is the user's own notes self-chat. Messages come oldest first, each with id, time (ISO 8601), sender, fromMe, text, subject, edited/deleted flags and attachments; a channel is returned as threads, each root post with its replies
|
|
49718
|
-
|
|
51072
|
+
description: `Read the messages of any chat or channel the signed-in user is in, by id (from teams_list_chats / teams_list_teams_and_channels) or by name, without opening it in Teams. "48:notes" (or the name "notes" / "self") is the user's own notes self-chat. Messages come oldest first, each with id, time (UTC, ISO 8601), sender, fromMe, text (never truncated; table cells separated by " | "), subject, edited/deleted flags and attachments; a channel is returned as threads, each root post with its replies. A root older than the window is fetched and marked outside_window: true (it is context, not counted or cursored); up to ${MAX_ROOT_FETCHES} roots are fetched per call, and any beyond that or that cannot be fetched is { id, missing: true }. unread_only returns just the messages the user has not read; since stops at a time; limit keeps the newest (truncated says when more exist; unread_count_scope "window" says unread_count only covers what limit/since/after_message_id let through). after_message_id returns only messages newer than that id; next_cursor is the newest returned message id (or after_message_id when nothing is new) \u2014 pass it back as after_message_id to read only what arrived since. after_message_id takes message-id cursors only: to read what teams_get_changes counted, pass that row's after_message_id, never teams_get_changes' next_cursor (a time token for teams_get_changes). ` + CURSOR_NO_CACHE_DESCRIPTION + FORMAT_DESCRIPTION + `conversation may also be an array of up to ${MAX_CONVERSATIONS} ids/names: the result is then { conversations: [...], errors, fetched_at }, one single-read result per conversation (the other arguments apply to each); an ambiguous name takes its place among them as the same { ambiguous: true, ... } object a single read returns, and one that cannot be resolved or read is listed in errors while the rest still come back. ` + MARK_READ_DESCRIPTION + "With mark_read the read marker of each conversation read moves up to the newest message returned (never backwards; outside_window roots do not count) and its result says marked_read; one whose limit or since cut off unread messages older than those returned is not marked (marked_read: { skipped, hint }), while a limit that cut only already-read messages does not stop it; the user confirms first \u2014 a prompt where the client supports one, otherwise the first call returns only a preview and a confirmToken, and the repeat call with it reads and marks. " + CONFIRM_INJECTION_RULE + " Attachments are listed per message (images by ref, files by name) and fetched with teams_get_attachment. A name that matches several conversations is not an error: the result is {ambiguous: true, query, match_count, candidates (up to 10, each with id, title, kind, team, lastActivity and match_reason), hint} and no messages \u2014 read again with one candidate's id. " + TIME_ZONE_DESCRIPTION + UNTRUSTED_DESCRIPTION_SUFFIX2,
|
|
51073
|
+
// A write only with mark_read, but a write: it moves the user's read marker (never backwards, so a repeat is a no-op).
|
|
51074
|
+
annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
|
|
49719
51075
|
inputSchema: {
|
|
49720
|
-
conversation: external_exports.string().min(1).describe(
|
|
49721
|
-
`The conversation id ("48:notes", "notes" or "self" for the self-chat), or a case-insensitive substring of the chat title, channel name, team name or an untitled chat's participant names.`
|
|
51076
|
+
conversation: external_exports.union([external_exports.string().min(1), external_exports.array(external_exports.string().min(1)).min(1).max(MAX_CONVERSATIONS)]).describe(
|
|
51077
|
+
`The conversation id ("48:notes", "notes" or "self" for the self-chat), or a case-insensitive substring of the chat title, channel name, team name or an untitled chat's participant names; or an array of up to ${MAX_CONVERSATIONS} of them to read several at once.`
|
|
49722
51078
|
),
|
|
49723
|
-
unread_only: external_exports.boolean().optional().describe("Only return messages the user has not read yet (default false).
|
|
51079
|
+
unread_only: external_exports.boolean().optional().describe("Only return messages the user has not read yet (default false). Does not mark them read unless mark_read is set."),
|
|
49724
51080
|
since: sinceArg,
|
|
49725
|
-
|
|
51081
|
+
after_message_id: afterMessageIdArg,
|
|
51082
|
+
limit: limitArg(MAX_MESSAGES, "messages"),
|
|
51083
|
+
tz: tzArg,
|
|
51084
|
+
format: formatArg,
|
|
51085
|
+
mark_read: markReadArg,
|
|
51086
|
+
confirmToken: confirmTokenParam
|
|
49726
51087
|
}
|
|
49727
51088
|
},
|
|
49728
|
-
async ({ conversation, unread_only, since, limit }) => {
|
|
51089
|
+
async ({ conversation, unread_only, since, after_message_id, limit, tz, format, mark_read, confirmToken }, ctx) => {
|
|
49729
51090
|
try {
|
|
51091
|
+
assertMarkReadFormat(mark_read, format);
|
|
51092
|
+
const opts = {
|
|
51093
|
+
unreadOnly: unread_only ?? false,
|
|
51094
|
+
since,
|
|
51095
|
+
afterMessageId: after_message_id,
|
|
51096
|
+
limit: limit ?? DEFAULT_LIMIT,
|
|
51097
|
+
timeZone: resolveTimeZone(tz),
|
|
51098
|
+
format: format ?? "full",
|
|
51099
|
+
roots: rootBudget()
|
|
51100
|
+
};
|
|
51101
|
+
const fetched_at = (/* @__PURE__ */ new Date()).toISOString();
|
|
49730
51102
|
const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
|
|
49731
|
-
const
|
|
49732
|
-
|
|
49733
|
-
|
|
49734
|
-
const cutoff = since !== void 0 ? Date.parse(since) : void 0;
|
|
49735
|
-
const wanted = (m) => isUserMessage(m) && (!unread_only || isUnread(m, horizon, me));
|
|
49736
|
-
const limited = makeLimitedStopAt(unread_only ? horizon : void 0, wanted, limit ?? DEFAULT_LIMIT);
|
|
49737
|
-
let sinceCut = false;
|
|
49738
|
-
let capped = false;
|
|
49739
|
-
const stopAt = (m) => {
|
|
49740
|
-
const atHorizon = unread_only && Number(m.id) <= horizon;
|
|
49741
|
-
const at = arrivalMs(m);
|
|
49742
|
-
if (!atHorizon && cutoff !== void 0 && Number.isFinite(at) && at < cutoff) {
|
|
49743
|
-
if (Number(m.id) > horizon) sinceCut = true;
|
|
49744
|
-
return true;
|
|
49745
|
-
}
|
|
49746
|
-
return limited.stopAt(m);
|
|
51103
|
+
const many = Array.isArray(conversation) ? await readMany(chatsvc, raw, me, conversation, opts) : {
|
|
51104
|
+
reads: [await readOne(chatsvc, raw, me, await resolveListed(chatsvc, raw, me, conversation, "read"), opts)],
|
|
51105
|
+
errors: []
|
|
49747
51106
|
};
|
|
49748
|
-
|
|
49749
|
-
|
|
49750
|
-
|
|
49751
|
-
|
|
49752
|
-
|
|
49753
|
-
|
|
49754
|
-
|
|
49755
|
-
|
|
49756
|
-
|
|
49757
|
-
|
|
49758
|
-
|
|
49759
|
-
|
|
49760
|
-
|
|
49761
|
-
|
|
49762
|
-
|
|
49763
|
-
|
|
49764
|
-
|
|
49765
|
-
|
|
49766
|
-
|
|
49767
|
-
|
|
49768
|
-
|
|
49769
|
-
|
|
51107
|
+
let marks;
|
|
51108
|
+
if (mark_read) {
|
|
51109
|
+
const plans = [];
|
|
51110
|
+
for (const read of many.reads) {
|
|
51111
|
+
if ("ambiguous" in read) continue;
|
|
51112
|
+
const { summary, conv, newest, skip } = read;
|
|
51113
|
+
if (skip === void 0 && advancesHorizon(conv, newest)) plans.push({ summary, previous: horizonMessageId(conv), target: newest });
|
|
51114
|
+
}
|
|
51115
|
+
if (plans.length > 0) {
|
|
51116
|
+
const gate = await confirmMarks(ctx, { tool: "teams_read_conversation", me, plans, confirmToken });
|
|
51117
|
+
if (gate) return gate;
|
|
51118
|
+
}
|
|
51119
|
+
marks = await applyMarks(chatsvc, plans);
|
|
51120
|
+
}
|
|
51121
|
+
const results = many.reads.map(
|
|
51122
|
+
(read) => "ambiguous" in read ? read.ambiguous : {
|
|
51123
|
+
...read.result,
|
|
51124
|
+
...marks !== void 0 ? marks.get(read.summary.id) ?? (read.skip !== void 0 && advancesHorizon(read.conv, read.newest) ? { marked_read: read.skip } : { marked_read: false }) : {}
|
|
51125
|
+
}
|
|
51126
|
+
);
|
|
51127
|
+
if (Array.isArray(conversation)) {
|
|
51128
|
+
return untrustedResult2({
|
|
51129
|
+
conversations: results,
|
|
51130
|
+
...many.errors.length > 0 ? { errors: many.errors } : {},
|
|
51131
|
+
fetched_at
|
|
51132
|
+
});
|
|
51133
|
+
}
|
|
51134
|
+
return untrustedResult2({ ...results[0], fetched_at });
|
|
49770
51135
|
} catch (err) {
|
|
51136
|
+
if (err instanceof AmbiguousConversationError) return untrustedResult2(ambiguousResult(err));
|
|
49771
51137
|
throw wrapApiError(err, "read the conversation");
|
|
49772
51138
|
}
|
|
49773
51139
|
}
|
|
@@ -49779,15 +51145,20 @@ init_zod();
|
|
|
49779
51145
|
init_dist2();
|
|
49780
51146
|
var MAX_PER_CONVERSATION = 200;
|
|
49781
51147
|
var DEFAULT_PER_CONVERSATION = 50;
|
|
49782
|
-
var
|
|
51148
|
+
var MAX_CONVERSATIONS2 = 50;
|
|
49783
51149
|
var DEFAULT_CONVERSATIONS = 20;
|
|
49784
51150
|
var MAX_RAW_MESSAGES2 = 4e3;
|
|
51151
|
+
var ROOT_CONVERSATION_CONCURRENCY = 4;
|
|
49785
51152
|
var KIND_FILTERS = {
|
|
49786
51153
|
chat: ["group", "meeting", "oneOnOne"],
|
|
49787
51154
|
channel: ["channel"],
|
|
49788
51155
|
meeting: ["meeting"],
|
|
49789
51156
|
oneOnOne: ["oneOnOne"]
|
|
49790
51157
|
};
|
|
51158
|
+
var TRUNCATED_SKIP = {
|
|
51159
|
+
skipped: "truncated",
|
|
51160
|
+
hint: `The read marker was left where it was: per_conversation_limit cut this read, so unread messages older than those returned were not returned. Read again with a larger per_conversation_limit (max ${MAX_PER_CONVERSATION}) or with teams_read_conversation (unread_only) to mark it read, or use teams_mark_read to mark it all read deliberately.`
|
|
51161
|
+
};
|
|
49791
51162
|
function byLastActivityDesc2(a, b) {
|
|
49792
51163
|
return (b.lastActivity ?? "").localeCompare(a.lastActivity ?? "");
|
|
49793
51164
|
}
|
|
@@ -49796,31 +51167,62 @@ function registerUnreadTools(server, { chatsvc }) {
|
|
|
49796
51167
|
"teams_get_unread",
|
|
49797
51168
|
{
|
|
49798
51169
|
title: "Get unread Teams messages",
|
|
49799
|
-
description:
|
|
49800
|
-
|
|
51170
|
+
description: `Get every unread message across all the chats and channels the signed-in user is in (or those matching kinds / query), grouped by conversation, most recent activity first. Each conversation comes with its summary (id, kind, title, team) and only the messages the user has not read, oldest first; a channel's are grouped as threads under their root post. A root the user already read is fetched and marked outside_window: true (it is context, not unread or counted); up to ${MAX_ROOT_FETCHES} roots are fetched per call, and any beyond that or that cannot be fetched is { id, missing: true }. Exact, as in Teams: every conversation with activity past its read marker (or never opened) is read past the marker and kept only if it holds a real message from someone else, so a call recording, transcript or other system event never makes a conversation unread. Channels the user has hidden in Teams are left out (include_hidden adds them); one that is gone or no longer readable (404/403) is skipped and counted in skipped_unreachable. Only conversations whose newest unread message is from the last 14 days are returned by default (since_days widens or narrows it); older unread conversations \u2014 typically dormant channels \u2014 are not read past their marker and are counted in older_unread_skipped; older_unread: true also lists them in older_unread_conversations (id, kind, title, team, lastActivity, and unread_count only for those already read \u2014 unread_count_known: false otherwise). Chats the user muted in Teams (muted: true) are left out too and counted in muted_skipped, without being read; include_muted adds them. Unread conversations past max_conversations are listed by id, title and unread_count in more_unread_conversations; read one with teams_read_conversation. A conversation that could not be read is listed in errors and the rest still come back. total_unread covers every unread conversation found; total_unread_exact is false when a per-conversation limit truncated or a read failed. cursors ({ conversationId: messageId }) returns only unread messages newer than each conversation's cursor (one with none is left out, and total_unread counts only those). Each returned conversation carries next_cursor, its newest returned message id; next_cursors is the cursors passed in updated with every returned conversation's next_cursor (not those only in more_unread_conversations) \u2014 pass it back as cursors to get only what is new. ` + CURSOR_NO_CACHE_DESCRIPTION + FORMAT_DESCRIPTION + MARK_READ_DESCRIPTION + 'With mark_read each conversation returned with its messages (not more_unread_conversations) has its read marker moved up to its newest unread message returned (outside_window roots do not count) and carries marked_read (false with mark_read_warning when that move failed); one per_conversation_limit cut is not marked \u2014 marked_read: { skipped: "truncated", hint }; the user confirms first \u2014 a prompt where the client supports one, otherwise the first call returns only a preview and a confirmToken, and the repeat call with it reads and marks. ' + CONFIRM_INJECTION_RULE + " " + GROUP_TITLE_DESCRIPTION + " query also matches those participant names, and the last-message preview. " + MATCH_REASON_DESCRIPTION + "Message times are UTC (ISO 8601); " + TIME_ZONE_DESCRIPTION + UNTRUSTED_DESCRIPTION_SUFFIX2,
|
|
51171
|
+
// A write only with mark_read, but a write: it moves the user's read markers (never backwards, so a repeat is a no-op).
|
|
51172
|
+
annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
|
|
49801
51173
|
inputSchema: {
|
|
49802
51174
|
kinds: external_exports.array(external_exports.enum(Object.keys(KIND_FILTERS))).min(1).optional().describe(
|
|
49803
51175
|
"Only these kinds of conversation (default all): chat = every group, meeting and 1:1 chat; channel; meeting = meeting chats only; oneOnOne = 1:1 chats only."
|
|
49804
51176
|
),
|
|
49805
51177
|
query: external_exports.string().min(1).optional().describe(
|
|
49806
|
-
"Case-insensitive substring of the chat title, channel name, team name
|
|
51178
|
+
"Case-insensitive substring of the chat title, channel name, team name, an untitled chat's participant names or the last-message preview, or an exact conversation id."
|
|
49807
51179
|
),
|
|
49808
51180
|
include_hidden: includeHiddenArg,
|
|
51181
|
+
include_muted: external_exports.boolean().optional().describe(
|
|
51182
|
+
"Also return conversations the user has muted in Teams (default false: they are left out unread and counted in muted_skipped)."
|
|
51183
|
+
),
|
|
49809
51184
|
since_days: sinceDaysArg(),
|
|
51185
|
+
older_unread: olderUnreadArg(),
|
|
49810
51186
|
per_conversation_limit: external_exports.number().int().min(1).max(MAX_PER_CONVERSATION).optional().describe(
|
|
49811
51187
|
`Maximum unread messages per conversation, newest kept (default ${DEFAULT_PER_CONVERSATION}, max ${MAX_PER_CONVERSATION}).`
|
|
49812
51188
|
),
|
|
49813
|
-
max_conversations: external_exports.number().int().min(1).max(
|
|
49814
|
-
`Maximum unread conversations returned with their messages, most recent activity first (default ${DEFAULT_CONVERSATIONS}, max ${
|
|
49815
|
-
)
|
|
51189
|
+
max_conversations: external_exports.number().int().min(1).max(MAX_CONVERSATIONS2).optional().describe(
|
|
51190
|
+
`Maximum unread conversations returned with their messages, most recent activity first (default ${DEFAULT_CONVERSATIONS}, max ${MAX_CONVERSATIONS2}); the rest are listed in more_unread_conversations.`
|
|
51191
|
+
),
|
|
51192
|
+
cursors: cursorsArg,
|
|
51193
|
+
tz: tzArg,
|
|
51194
|
+
format: formatArg,
|
|
51195
|
+
mark_read: markReadArg,
|
|
51196
|
+
confirmToken: confirmTokenParam
|
|
49816
51197
|
}
|
|
49817
51198
|
},
|
|
49818
|
-
async ({
|
|
51199
|
+
async ({
|
|
51200
|
+
kinds,
|
|
51201
|
+
query,
|
|
51202
|
+
include_hidden,
|
|
51203
|
+
include_muted,
|
|
51204
|
+
since_days,
|
|
51205
|
+
older_unread,
|
|
51206
|
+
per_conversation_limit,
|
|
51207
|
+
max_conversations,
|
|
51208
|
+
cursors,
|
|
51209
|
+
tz,
|
|
51210
|
+
format,
|
|
51211
|
+
mark_read,
|
|
51212
|
+
confirmToken
|
|
51213
|
+
}, ctx) => {
|
|
49819
51214
|
try {
|
|
51215
|
+
assertMarkReadFormat(mark_read, format);
|
|
51216
|
+
const timeZone = resolveTimeZone(tz);
|
|
51217
|
+
const fetched_at = (/* @__PURE__ */ new Date()).toISOString();
|
|
49820
51218
|
const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
|
|
49821
51219
|
const allowed = new Set((kinds ?? ["chat", "channel"]).flatMap((k) => KIND_FILTERS[k]));
|
|
49822
51220
|
let candidates = raw.map((c) => conversationSummary(c, me, raw)).filter((s) => allowed.has(s.kind) && isUnreadCandidateFor(s, include_hidden));
|
|
49823
|
-
if (query !== void 0) candidates = matchConversations(await enrichTitles(chatsvc, raw, me, candidates), query
|
|
51221
|
+
if (query !== void 0) candidates = matchConversations(await enrichTitles(chatsvc, raw, me, candidates), query, {
|
|
51222
|
+
messages: true
|
|
51223
|
+
});
|
|
51224
|
+
const mutedSkipped = include_muted ? 0 : candidates.filter((s) => s.muted).length;
|
|
51225
|
+
if (!include_muted) candidates = candidates.filter((s) => !s.muted);
|
|
49824
51226
|
candidates.sort(byLastActivityDesc2);
|
|
49825
51227
|
const perLimit = per_conversation_limit ?? DEFAULT_PER_CONVERSATION;
|
|
49826
51228
|
const outcome = await confirmUnreadCandidates(
|
|
@@ -49828,39 +51230,73 @@ function registerUnreadTools(server, { chatsvc }) {
|
|
|
49828
51230
|
raw,
|
|
49829
51231
|
me,
|
|
49830
51232
|
candidates,
|
|
49831
|
-
{ limit: perLimit, maxRaw: MAX_RAW_MESSAGES2, since: sinceCutoff(since_days) }
|
|
51233
|
+
{ limit: perLimit, maxRaw: MAX_RAW_MESSAGES2, since: sinceCutoff(since_days), cursors }
|
|
49832
51234
|
);
|
|
49833
|
-
const { skippedUnreachable,
|
|
51235
|
+
const { skippedUnreachable, older } = outcome;
|
|
51236
|
+
const listedOlder = older_unread ? older : [];
|
|
49834
51237
|
const retitled = await enrichTitles(chatsvc, raw, me, [
|
|
49835
51238
|
...outcome.confirmed.map((c) => c.summary),
|
|
49836
|
-
...outcome.failed.map((f) => f.summary)
|
|
51239
|
+
...outcome.failed.map((f) => f.summary),
|
|
51240
|
+
...listedOlder.map((o) => o.summary)
|
|
49837
51241
|
]);
|
|
49838
51242
|
const confirmed = outcome.confirmed.map((c, i) => ({ ...c, summary: retitled[i] }));
|
|
49839
51243
|
const failed = outcome.failed.map((f, i) => ({ ...f, summary: retitled[outcome.confirmed.length + i] }));
|
|
51244
|
+
const olderTitled = retitled.slice(outcome.confirmed.length + outcome.failed.length);
|
|
49840
51245
|
const cap = max_conversations ?? DEFAULT_CONVERSATIONS;
|
|
49841
|
-
const
|
|
49842
|
-
|
|
49843
|
-
|
|
49844
|
-
|
|
49845
|
-
|
|
49846
|
-
|
|
49847
|
-
|
|
49848
|
-
|
|
49849
|
-
|
|
49850
|
-
|
|
49851
|
-
|
|
49852
|
-
|
|
49853
|
-
|
|
49854
|
-
|
|
49855
|
-
|
|
51246
|
+
const returned = confirmed.slice(0, cap);
|
|
51247
|
+
let marks;
|
|
51248
|
+
if (mark_read) {
|
|
51249
|
+
const byId = new Map(raw.map((c) => [c.id, c]));
|
|
51250
|
+
const plans = [];
|
|
51251
|
+
for (const { summary, read } of returned) {
|
|
51252
|
+
if (read.truncated) continue;
|
|
51253
|
+
const conv = byId.get(summary.id) ?? { id: summary.id };
|
|
51254
|
+
const target = newestId(read.messages);
|
|
51255
|
+
if (advancesHorizon(conv, target)) plans.push({ summary, previous: horizonMessageId(conv), target });
|
|
51256
|
+
}
|
|
51257
|
+
if (plans.length > 0) {
|
|
51258
|
+
const gate = await confirmMarks(ctx, { tool: "teams_get_unread", me, plans, confirmToken });
|
|
51259
|
+
if (gate) return gate;
|
|
51260
|
+
}
|
|
51261
|
+
marks = await applyMarks(chatsvc, plans);
|
|
51262
|
+
}
|
|
51263
|
+
const budget = rootBudget();
|
|
51264
|
+
const shown = returned.map(({ summary, read }) => ({
|
|
51265
|
+
summary,
|
|
51266
|
+
read,
|
|
51267
|
+
messages: oldestFirst(read.messages).map((m) => normaliseMessage(m, me, { timeZone }))
|
|
51268
|
+
}));
|
|
51269
|
+
const roots = await mapWithConcurrency(
|
|
51270
|
+
shown,
|
|
51271
|
+
ROOT_CONVERSATION_CONCURRENCY,
|
|
51272
|
+
({ summary, messages }) => summary.kind === "channel" ? fetchOutsideRoots(chatsvc, summary.id, messages, me, { budget, timeZone }) : Promise.resolve(void 0)
|
|
51273
|
+
);
|
|
51274
|
+
const conversations = shown.map(({ summary, read, messages }, i) => ({
|
|
51275
|
+
conversation: formatConversation(confirmedSummary(summary, true), format ?? "full"),
|
|
51276
|
+
unread_count: messages.length,
|
|
51277
|
+
...formatBody(summary.kind, messages, format ?? "full", roots[i]),
|
|
51278
|
+
// Every confirmed read holds at least one message, so there is always a newest.
|
|
51279
|
+
next_cursor: newestId(read.messages),
|
|
51280
|
+
...read.truncated ? {
|
|
51281
|
+
truncated: {
|
|
51282
|
+
returned: messages.length,
|
|
51283
|
+
hint: `Only the newest ${messages.length} unread messages were returned; pass a larger per_conversation_limit (max ${MAX_PER_CONVERSATION}) or read the conversation with teams_read_conversation (unread_only).`
|
|
51284
|
+
}
|
|
51285
|
+
} : {},
|
|
51286
|
+
...marks !== void 0 ? marks.get(summary.id) ?? { marked_read: read.truncated ? TRUNCATED_SKIP : false } : {}
|
|
51287
|
+
}));
|
|
49856
51288
|
const rest = confirmed.slice(cap);
|
|
51289
|
+
const next_cursors = { ...cursors };
|
|
51290
|
+
for (const c of conversations) next_cursors[c.conversation.id] = c.next_cursor;
|
|
49857
51291
|
const exact = failed.length === 0 && confirmed.every((c) => !c.read.truncated);
|
|
49858
51292
|
return untrustedResult2({
|
|
49859
51293
|
total_unread: confirmed.reduce((n, c) => n + c.read.messages.length, 0),
|
|
49860
51294
|
total_unread_exact: exact,
|
|
49861
51295
|
conversations,
|
|
49862
51296
|
skipped_unreachable: skippedUnreachable,
|
|
49863
|
-
|
|
51297
|
+
muted_skipped: mutedSkipped,
|
|
51298
|
+
...olderUnreadReport(older.length, since_days),
|
|
51299
|
+
...olderUnreadConversations(listedOlder, olderTitled),
|
|
49864
51300
|
...failed.length > 0 ? {
|
|
49865
51301
|
errors: failed.map((f) => ({
|
|
49866
51302
|
conversation: f.summary,
|
|
@@ -49873,7 +51309,9 @@ function registerUnreadTools(server, { chatsvc }) {
|
|
|
49873
51309
|
title: summary.title,
|
|
49874
51310
|
unread_count: read.messages.length
|
|
49875
51311
|
}))
|
|
49876
|
-
} : {}
|
|
51312
|
+
} : {},
|
|
51313
|
+
next_cursors,
|
|
51314
|
+
fetched_at
|
|
49877
51315
|
});
|
|
49878
51316
|
} catch (err) {
|
|
49879
51317
|
throw wrapApiError(err, "get unread messages");
|
|
@@ -49882,10 +51320,181 @@ function registerUnreadTools(server, { chatsvc }) {
|
|
|
49882
51320
|
);
|
|
49883
51321
|
}
|
|
49884
51322
|
|
|
51323
|
+
// src/tools/changes.ts
|
|
51324
|
+
init_zod();
|
|
51325
|
+
init_dist2();
|
|
51326
|
+
var MAX_CONVERSATIONS3 = 200;
|
|
51327
|
+
var DEFAULT_WINDOW_MS = 864e5;
|
|
51328
|
+
var MAX_RAW_MESSAGES3 = 1e3;
|
|
51329
|
+
var PAGE_SIZE = 50;
|
|
51330
|
+
var READ_CONCURRENCY2 = 4;
|
|
51331
|
+
function encodeChangesCursor(t) {
|
|
51332
|
+
return Buffer.from(JSON.stringify({ t }), "utf8").toString("base64url");
|
|
51333
|
+
}
|
|
51334
|
+
function badCursor(cursor) {
|
|
51335
|
+
return new McpToolError(`"${cursor}" is not a changes cursor.`, {
|
|
51336
|
+
hint: "Pass a previous result's next_cursor unchanged, or an ISO 8601 time such as 2026-10-12T09:00:00Z. A message id (digits) is not a changes cursor: pass it to teams_read_conversation as after_message_id."
|
|
51337
|
+
});
|
|
51338
|
+
}
|
|
51339
|
+
function decodeChangesCursor(cursor) {
|
|
51340
|
+
if (/^[A-Za-z0-9_-]+$/.test(cursor)) {
|
|
51341
|
+
let parsed;
|
|
51342
|
+
try {
|
|
51343
|
+
parsed = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
51344
|
+
} catch {
|
|
51345
|
+
parsed = void 0;
|
|
51346
|
+
}
|
|
51347
|
+
if (parsed !== void 0) {
|
|
51348
|
+
const t2 = parsed?.t;
|
|
51349
|
+
if (typeof t2 === "number" && Number.isFinite(t2) && t2 >= 0) return t2;
|
|
51350
|
+
throw badCursor(cursor);
|
|
51351
|
+
}
|
|
51352
|
+
}
|
|
51353
|
+
const t = /^\d{4}-\d{2}-\d{2}/.test(cursor) ? Date.parse(cursor) : NaN;
|
|
51354
|
+
if (Number.isNaN(t)) throw badCursor(cursor);
|
|
51355
|
+
return t;
|
|
51356
|
+
}
|
|
51357
|
+
function changedMs(m) {
|
|
51358
|
+
const v = Number(m.version);
|
|
51359
|
+
const id = Number(m.id);
|
|
51360
|
+
return Math.max(Number.isFinite(v) ? v : 0, Number.isFinite(id) ? id : 0);
|
|
51361
|
+
}
|
|
51362
|
+
async function readChanges(chatsvc, summary, t, me) {
|
|
51363
|
+
let capped = false;
|
|
51364
|
+
const fetched = await chatsvc.getMessages(summary.id, {
|
|
51365
|
+
stopAt: (m) => changedMs(m) <= t,
|
|
51366
|
+
max: MAX_RAW_MESSAGES3,
|
|
51367
|
+
pageSize: PAGE_SIZE,
|
|
51368
|
+
onCapped: () => capped = true
|
|
51369
|
+
});
|
|
51370
|
+
const arrived = fetched.filter((m) => Number(m.id) > t);
|
|
51371
|
+
const maxSeen = arrived.reduce((n, m) => Math.max(n, Number(m.id)), 0);
|
|
51372
|
+
const fresh = arrived.filter(isUserMessage).map((m) => normaliseMessage(m, me)).filter((m) => m.deleted !== true).sort((a, b) => Number(b.id) - Number(a.id));
|
|
51373
|
+
let threads;
|
|
51374
|
+
if (summary.kind === "channel") {
|
|
51375
|
+
const byRoot = /* @__PURE__ */ new Map();
|
|
51376
|
+
for (const m of fresh) {
|
|
51377
|
+
const rootId = m.replyTo ?? m.id;
|
|
51378
|
+
let thread = byRoot.get(rootId);
|
|
51379
|
+
if (thread === void 0) byRoot.set(rootId, thread = { root_id: rootId, new_root: false, new_reply_count: 0 });
|
|
51380
|
+
if (m.replyTo === void 0) thread.new_root = true;
|
|
51381
|
+
else thread.new_reply_count++;
|
|
51382
|
+
}
|
|
51383
|
+
threads = [...byRoot.values()];
|
|
51384
|
+
}
|
|
51385
|
+
return {
|
|
51386
|
+
count: fresh.length,
|
|
51387
|
+
fromOthers: fresh.filter((m) => !m.fromMe).length,
|
|
51388
|
+
newest: fresh.length > 0 ? Number(fresh[0].id) : 0,
|
|
51389
|
+
...fresh.length > 0 ? { newestTime: fresh[0].time } : {},
|
|
51390
|
+
maxSeen,
|
|
51391
|
+
...threads !== void 0 ? { threads } : {},
|
|
51392
|
+
truncated: capped
|
|
51393
|
+
};
|
|
51394
|
+
}
|
|
51395
|
+
function registerChangesTools(server, { chatsvc }) {
|
|
51396
|
+
server.registerTool(
|
|
51397
|
+
"teams_get_changes",
|
|
51398
|
+
{
|
|
51399
|
+
title: "Get Teams conversations with new messages",
|
|
51400
|
+
description: `List the chats and channels that got new messages since a cursor, most recent first \u2014 counts, not the messages: each with its summary (id, kind, title, team), new_message_count (real messages only \u2014 call recordings and other system events, and deleted messages, are not counted), new_from_others_count, newest_time and, for a channel, threads: one { root_id, new_root, new_reply_count } per thread the new messages landed in, including a thread whose root post is older than the cursor, and after_message_id: read the messages it counted with teams_read_conversation({ conversation: <its id>, after_message_id: <its after_message_id> }). Two cursor kinds, not interchangeable: this tool's cursor/next_cursor is a time token for teams_get_changes only and is not a message id; after_message_id is a message-id cursor (ids are arrival ms, so it is the cursor time as an id) for teams_read_conversation (or teams_get_unread cursors). Without cursor it looks back 24 hours. next_cursor is an opaque token \u2014 pass it back as cursor to get only what arrived since this call (cursor also takes a plain ISO 8601 time). It is at-least-once: a conversation can come back again but none is skipped; it stays at the input time when a read failed. Use the same kinds and include_hidden with a cursor as the call that returned it. Channels hidden in Teams are left out unless include_hidden (then every hidden channel is read, since Teams stops updating their listing); one that is gone or no longer readable (404/403) is skipped and counted in skipped_unreachable; one whose read failed is listed in errors. limit caps the conversations returned; the rest are named, with their new_message_count and after_message_id, in more_conversations, and total_new_messages counts them all. A conversation with more than ${MAX_RAW_MESSAGES3} new messages is marked truncated (its count is a lower bound). ` + CURSOR_NO_CACHE_DESCRIPTION + "This does NOT mark anything read \u2014 the user's Teams unread badges are unaffected. " + UNTRUSTED_DESCRIPTION_SUFFIX2,
|
|
51401
|
+
annotations: toolAnnotations({ readOnly: true, openWorld: true }),
|
|
51402
|
+
inputSchema: {
|
|
51403
|
+
cursor: external_exports.string().min(1).optional().describe(
|
|
51404
|
+
"A previous teams_get_changes result's next_cursor, or an ISO 8601 time (e.g. 2026-10-12T09:00:00Z): only messages that arrived after it count. Default: 24 hours ago. Not a message id, and not teams_read_conversation's next_cursor."
|
|
51405
|
+
),
|
|
51406
|
+
kinds: external_exports.array(external_exports.enum(Object.keys(KIND_FILTERS))).min(1).optional().describe(
|
|
51407
|
+
"Only these kinds of conversation (default all): chat = every group, meeting and 1:1 chat; channel; meeting = meeting chats only; oneOnOne = 1:1 chats only."
|
|
51408
|
+
),
|
|
51409
|
+
include_hidden: includeHiddenArg.describe(
|
|
51410
|
+
"Also include channels the user has hidden in Teams (default false: Teams shows them nowhere)."
|
|
51411
|
+
),
|
|
51412
|
+
limit: limitArg(MAX_CONVERSATIONS3, "conversations", "most recent activity first kept")
|
|
51413
|
+
}
|
|
51414
|
+
},
|
|
51415
|
+
async ({ cursor, kinds, include_hidden, limit }) => {
|
|
51416
|
+
try {
|
|
51417
|
+
const t = cursor !== void 0 ? decodeChangesCursor(cursor) : Date.now() - DEFAULT_WINDOW_MS;
|
|
51418
|
+
const fetched_at = (/* @__PURE__ */ new Date()).toISOString();
|
|
51419
|
+
const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
|
|
51420
|
+
const allowed = new Set((kinds ?? ["chat", "channel"]).flatMap((k) => KIND_FILTERS[k]));
|
|
51421
|
+
const lastChange = new Map(raw.map((c) => [c.id, lastChangeMs(c)]));
|
|
51422
|
+
const candidates = raw.map((c) => conversationSummary(c, me, raw)).filter((s) => allowed.has(s.kind)).filter((s) => s.hidden === true ? include_hidden === true : (lastChange.get(s.id) ?? 0) > t);
|
|
51423
|
+
const results = await mapWithConcurrency(candidates, READ_CONCURRENCY2, async (summary) => {
|
|
51424
|
+
try {
|
|
51425
|
+
return { kind: "read", read: await readChanges(chatsvc, summary, t, me) };
|
|
51426
|
+
} catch (error62) {
|
|
51427
|
+
return isUnreachable(error62) ? { kind: "unreachable" } : { kind: "failed", error: error62 };
|
|
51428
|
+
}
|
|
51429
|
+
});
|
|
51430
|
+
let skipped_unreachable = 0;
|
|
51431
|
+
let maxSeen = t;
|
|
51432
|
+
let anyRead = false;
|
|
51433
|
+
const changed = [];
|
|
51434
|
+
const failed = [];
|
|
51435
|
+
results.forEach((r, i) => {
|
|
51436
|
+
if (r.kind === "unreachable") skipped_unreachable++;
|
|
51437
|
+
else if (r.kind === "failed") failed.push({ summary: candidates[i], error: r.error });
|
|
51438
|
+
else {
|
|
51439
|
+
anyRead = true;
|
|
51440
|
+
maxSeen = Math.max(maxSeen, r.read.maxSeen);
|
|
51441
|
+
if (r.read.count > 0) changed.push({ summary: candidates[i], read: r.read });
|
|
51442
|
+
}
|
|
51443
|
+
});
|
|
51444
|
+
if (failed.length > 0 && !anyRead) throw failed[0].error;
|
|
51445
|
+
changed.sort((a, b) => b.read.newest - a.read.newest);
|
|
51446
|
+
const listed = Math.max(t, ...[...lastChange.values()].map((n) => n ?? 0));
|
|
51447
|
+
const next = failed.length > 0 ? t : Math.min(maxSeen, listed);
|
|
51448
|
+
const cap = limit ?? DEFAULT_LIMIT;
|
|
51449
|
+
const shown = changed.slice(0, cap);
|
|
51450
|
+
const rest = changed.slice(cap);
|
|
51451
|
+
const titled = await enrichTitles(chatsvc, raw, me, [
|
|
51452
|
+
...shown.map((c) => c.summary),
|
|
51453
|
+
...rest.map((c) => c.summary),
|
|
51454
|
+
...failed.map((f) => f.summary)
|
|
51455
|
+
]);
|
|
51456
|
+
const after_message_id = String(Math.floor(t));
|
|
51457
|
+
const conversations = shown.map(({ read }, i) => ({
|
|
51458
|
+
conversation: titled[i],
|
|
51459
|
+
new_message_count: read.count,
|
|
51460
|
+
new_from_others_count: read.fromOthers,
|
|
51461
|
+
...read.newestTime !== void 0 ? { newest_time: read.newestTime } : {},
|
|
51462
|
+
after_message_id,
|
|
51463
|
+
...read.threads !== void 0 ? { threads: read.threads } : {},
|
|
51464
|
+
...read.truncated ? { truncated: true } : {}
|
|
51465
|
+
}));
|
|
51466
|
+
const more = rest.map(({ read }, i) => ({
|
|
51467
|
+
id: titled[shown.length + i].id,
|
|
51468
|
+
title: titled[shown.length + i].title,
|
|
51469
|
+
new_message_count: read.count,
|
|
51470
|
+
after_message_id
|
|
51471
|
+
}));
|
|
51472
|
+
const errors = failed.map((f, i) => ({
|
|
51473
|
+
conversation: titled[changed.length + i],
|
|
51474
|
+
error: wrapApiError(f.error, "read this conversation").message
|
|
51475
|
+
}));
|
|
51476
|
+
return untrustedResult2({
|
|
51477
|
+
since: new Date(t).toISOString(),
|
|
51478
|
+
total_new_messages: changed.reduce((n, c) => n + c.read.count, 0),
|
|
51479
|
+
conversations,
|
|
51480
|
+
...more.length > 0 ? { more_conversations: more } : {},
|
|
51481
|
+
skipped_unreachable,
|
|
51482
|
+
...errors.length > 0 ? { errors } : {},
|
|
51483
|
+
next_cursor: next === t && cursor !== void 0 ? cursor : encodeChangesCursor(next),
|
|
51484
|
+
next_cursor_time: new Date(next).toISOString(),
|
|
51485
|
+
fetched_at
|
|
51486
|
+
});
|
|
51487
|
+
} catch (err) {
|
|
51488
|
+
throw wrapApiError(err, "get changed conversations");
|
|
51489
|
+
}
|
|
51490
|
+
}
|
|
51491
|
+
);
|
|
51492
|
+
}
|
|
51493
|
+
|
|
49885
51494
|
// src/tools/attachment.ts
|
|
49886
51495
|
init_zod();
|
|
49887
51496
|
init_dist2();
|
|
49888
|
-
var
|
|
51497
|
+
var MAX_RAW_MESSAGES4 = 4e3;
|
|
49889
51498
|
var MAX_FILE_BYTES = 25 * 1024 * 1024;
|
|
49890
51499
|
var FILE_HINT = "A shared file is downloaded from SharePoint and returned as its contents (an image as an image, anything else as an embedded resource). The first file from a given SharePoint host may need opening once in Teams to mint a short-lived token; a file your account cannot open comes back as metadata and its link.";
|
|
49891
51500
|
function registerAttachmentTools(server, { chatsvc, sharepoint }) {
|
|
@@ -49905,7 +51514,7 @@ function registerAttachmentTools(server, { chatsvc, sharepoint }) {
|
|
|
49905
51514
|
try {
|
|
49906
51515
|
const target = Number(message_id);
|
|
49907
51516
|
const stopAt = Number.isFinite(target) && target > 0 ? (m) => Number(m.id) < target : void 0;
|
|
49908
|
-
const fetched = await chatsvc.getMessages(conversation, { stopAt, max:
|
|
51517
|
+
const fetched = await chatsvc.getMessages(conversation, { stopAt, max: MAX_RAW_MESSAGES4 });
|
|
49909
51518
|
const raw = fetched.find((m) => m.id === message_id);
|
|
49910
51519
|
if (raw === void 0) {
|
|
49911
51520
|
throw new McpToolError(`Message ${message_id} was not found in conversation ${conversation}.`, {
|
|
@@ -49997,6 +51606,9 @@ function degradeHint(err, host) {
|
|
|
49997
51606
|
if (errorKindOf(err) === "no_credential") {
|
|
49998
51607
|
return "SharePoint file download is disabled here (no token source). Unset TEAMS_DISABLE_FETCHPROXY, then retry.";
|
|
49999
51608
|
}
|
|
51609
|
+
if (errorKindOf(err) === "transport" && err instanceof McpToolError) {
|
|
51610
|
+
return err.hint !== void 0 ? `${err.message} ${err.hint}` : err.message;
|
|
51611
|
+
}
|
|
50000
51612
|
if (err instanceof McpToolError && err.hint !== void 0) return err.hint;
|
|
50001
51613
|
return `Couldn't mint a SharePoint token for ${host} \u2014 open the shared file once in a signed-in Teams tab (that browser request is where the token is captured from), then retry.`;
|
|
50002
51614
|
}
|
|
@@ -50004,187 +51616,11 @@ function degradeHint(err, host) {
|
|
|
50004
51616
|
// src/tools/send.ts
|
|
50005
51617
|
init_zod();
|
|
50006
51618
|
init_dist2();
|
|
50007
|
-
|
|
50008
|
-
// src/compose.ts
|
|
50009
|
-
init_dist2();
|
|
50010
|
-
import { randomInt } from "node:crypto";
|
|
50011
|
-
var HTML_ESCAPES = {
|
|
50012
|
-
"&": "&",
|
|
50013
|
-
"<": "<",
|
|
50014
|
-
">": ">",
|
|
50015
|
-
'"': """,
|
|
50016
|
-
"'": "'"
|
|
50017
|
-
};
|
|
50018
|
-
function escapeHtml(s) {
|
|
50019
|
-
return s.replace(/[&<>"']/g, (c) => HTML_ESCAPES[c]);
|
|
50020
|
-
}
|
|
50021
|
-
var NAMED_EMOJI = {
|
|
50022
|
-
like: { title: "Like", char: "\u{1F44D}" },
|
|
50023
|
-
heart: { title: "Heart", char: "\u2764\uFE0F" },
|
|
50024
|
-
laugh: { title: "Laugh", char: "\u{1F606}" },
|
|
50025
|
-
surprised: { title: "Surprised", char: "\u{1F62E}" },
|
|
50026
|
-
sad: { title: "Sad", char: "\u{1F622}" },
|
|
50027
|
-
angry: { title: "Angry", char: "\u{1F621}" },
|
|
50028
|
-
smile: { title: "Smile", char: "\u{1F642}" },
|
|
50029
|
-
wink: { title: "Wink", char: "\u{1F609}" },
|
|
50030
|
-
cool: { title: "Cool", char: "\u{1F60E}" },
|
|
50031
|
-
hearteyes: { title: "Heart eyes", char: "\u{1F60D}" },
|
|
50032
|
-
fire: { title: "Fire", char: "\u{1F525}" },
|
|
50033
|
-
party: { title: "Party", char: "\u{1F389}" }
|
|
50034
|
-
};
|
|
50035
|
-
var UNICODE_KEY = /^([0-9a-f]{4,6}(?:-[0-9a-f]{4,6})*)_([a-z0-9]+)$/;
|
|
50036
|
-
function emojiSpan(key) {
|
|
50037
|
-
let title;
|
|
50038
|
-
let char;
|
|
50039
|
-
const named = NAMED_EMOJI[key];
|
|
50040
|
-
if (named !== void 0) {
|
|
50041
|
-
({ title, char } = named);
|
|
50042
|
-
} else {
|
|
50043
|
-
const m = UNICODE_KEY.exec(key);
|
|
50044
|
-
if (m === null) return void 0;
|
|
50045
|
-
const points = m[1].split("-").map((h) => parseInt(h, 16));
|
|
50046
|
-
if (points.some((p) => p > 1114111)) return void 0;
|
|
50047
|
-
char = String.fromCodePoint(...points);
|
|
50048
|
-
title = m[2];
|
|
50049
|
-
}
|
|
50050
|
-
const t = escapeHtml(title);
|
|
50051
|
-
return `<span contenteditable="false" title="${t}" type="(${key})" class="animated-emoticon-20-${key}" itemscope><img itemscope itemtype="http://schema.skype.com/Emoji" itemid="${key}" src="https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons/${key}/default/20_f.png" title="${t}" alt="${escapeHtml(char)}" style="width:20px;height:20px;"></span>`;
|
|
50052
|
-
}
|
|
50053
|
-
function renderPlain(text) {
|
|
50054
|
-
let out = "";
|
|
50055
|
-
let at = 0;
|
|
50056
|
-
const shortcode = /:([a-z0-9_-]+):/g;
|
|
50057
|
-
for (let m = shortcode.exec(text); m !== null; m = shortcode.exec(text)) {
|
|
50058
|
-
const span = emojiSpan(m[1]);
|
|
50059
|
-
if (span === void 0) {
|
|
50060
|
-
shortcode.lastIndex = m.index + m[0].length - 1;
|
|
50061
|
-
continue;
|
|
50062
|
-
}
|
|
50063
|
-
out += escapeLines(text.slice(at, m.index)) + span;
|
|
50064
|
-
at = shortcode.lastIndex;
|
|
50065
|
-
}
|
|
50066
|
-
return out + escapeLines(text.slice(at));
|
|
50067
|
-
}
|
|
50068
|
-
var escapeLines = (s) => escapeHtml(s).replace(/\r?\n/g, "<br>");
|
|
50069
|
-
var isWordChar = (c) => c !== void 0 && /[\p{L}\p{N}_]/u.test(c);
|
|
50070
|
-
function locate(text, name, taken) {
|
|
50071
|
-
const free = (s, e) => taken.every(([ts, te]) => e <= ts || s >= te);
|
|
50072
|
-
const find = (needle, ci, wordStart) => {
|
|
50073
|
-
const hay = ci ? text.toLowerCase() : text;
|
|
50074
|
-
const n = ci ? needle.toLowerCase() : needle;
|
|
50075
|
-
for (let i = hay.indexOf(n); i >= 0; i = hay.indexOf(n, i + 1)) {
|
|
50076
|
-
const end = i + n.length;
|
|
50077
|
-
if (isWordChar(text[end]) || wordStart && isWordChar(text[i - 1])) continue;
|
|
50078
|
-
if (free(i, end)) return [i, end];
|
|
50079
|
-
}
|
|
50080
|
-
return void 0;
|
|
50081
|
-
};
|
|
50082
|
-
return find(`@${name}`, false, false) ?? find(`@${name}`, true, false) ?? find(name, true, true);
|
|
50083
|
-
}
|
|
50084
|
-
function renderMessageHtml(text, mentions) {
|
|
50085
|
-
const placed = [];
|
|
50086
|
-
for (const m of mentions) {
|
|
50087
|
-
const range = locate(
|
|
50088
|
-
text,
|
|
50089
|
-
m.text,
|
|
50090
|
-
placed.map((p) => [p.start, p.end])
|
|
50091
|
-
);
|
|
50092
|
-
if (range === void 0) {
|
|
50093
|
-
throw new McpToolError(`The mention "${m.text}" does not appear in the text.`, {
|
|
50094
|
-
hint: "name_in_text must be written in text (as @name or name) once per mention."
|
|
50095
|
-
});
|
|
50096
|
-
}
|
|
50097
|
-
placed.push({ start: range[0], end: range[1], mri: m.mri });
|
|
50098
|
-
}
|
|
50099
|
-
placed.sort((a, b) => a.start - b.start);
|
|
50100
|
-
let html = "";
|
|
50101
|
-
let at = 0;
|
|
50102
|
-
const out = [];
|
|
50103
|
-
placed.forEach((p, n) => {
|
|
50104
|
-
const shown = text.slice(p.start, p.end).replace(/^@/, "");
|
|
50105
|
-
html += renderPlain(text.slice(at, p.start));
|
|
50106
|
-
html += `<span itemscope itemtype="http://schema.skype.com/Mention" itemid="${n}">${escapeHtml(shown)}</span>`;
|
|
50107
|
-
out.push({ itemid: String(n), mri: p.mri, displayName: shown });
|
|
50108
|
-
at = p.end;
|
|
50109
|
-
});
|
|
50110
|
-
html += renderPlain(text.slice(at));
|
|
50111
|
-
return { html: `<p>${html}</p>`, mentions: out };
|
|
50112
|
-
}
|
|
50113
|
-
function mentionsProperty(mentions) {
|
|
50114
|
-
return JSON.stringify(
|
|
50115
|
-
mentions.map((m) => ({
|
|
50116
|
-
"@type": "http://schema.skype.com/Mention",
|
|
50117
|
-
itemid: m.itemid,
|
|
50118
|
-
mri: m.mri,
|
|
50119
|
-
mentionType: "person",
|
|
50120
|
-
displayName: m.displayName
|
|
50121
|
-
}))
|
|
50122
|
-
);
|
|
50123
|
-
}
|
|
50124
|
-
var QUOTE_PREVIEW_CHARS = 200;
|
|
50125
|
-
function clipText(s, max, ellipsis = "") {
|
|
50126
|
-
if (s.length <= max) return s;
|
|
50127
|
-
let end = Math.max(0, max - ellipsis.length);
|
|
50128
|
-
const last = s.charCodeAt(end - 1);
|
|
50129
|
-
if (last >= 55296 && last <= 56319) end -= 1;
|
|
50130
|
-
return s.slice(0, end) + ellipsis;
|
|
50131
|
-
}
|
|
50132
|
-
function quoteHtml(q) {
|
|
50133
|
-
const preview = clipText(q.text, QUOTE_PREVIEW_CHARS, "\u2026");
|
|
50134
|
-
const id = escapeHtml(q.id);
|
|
50135
|
-
return `<blockquote itemscope itemtype="http://schema.skype.com/Reply" itemid="${id}"><strong itemprop="mri" itemid="${escapeHtml(q.senderMri)}">${escapeHtml(q.senderName)}</strong><span itemprop="time" itemid="${id}"></span><p itemprop="preview">${escapeHtml(preview)}</p></blockquote>`;
|
|
50136
|
-
}
|
|
50137
|
-
function qtdMsgsProperty(q) {
|
|
50138
|
-
return JSON.stringify([{ messageId: q.id, sender: q.senderMri, time: Number(q.id) }]);
|
|
50139
|
-
}
|
|
50140
|
-
function newClientMessageId() {
|
|
50141
|
-
let id = String(randomInt(1, 10));
|
|
50142
|
-
for (let i = 0; i < 18; i++) id += String(randomInt(0, 10));
|
|
50143
|
-
return id;
|
|
50144
|
-
}
|
|
50145
|
-
function buildSendBody(i) {
|
|
50146
|
-
const time3 = i.now.toISOString();
|
|
50147
|
-
return {
|
|
50148
|
-
id: "-1",
|
|
50149
|
-
type: "Message",
|
|
50150
|
-
conversationid: i.conversationId,
|
|
50151
|
-
conversationLink: `blah/${i.conversationId}`,
|
|
50152
|
-
from: i.meMri,
|
|
50153
|
-
fromUserId: i.meMri,
|
|
50154
|
-
composetime: time3,
|
|
50155
|
-
originalarrivaltime: time3,
|
|
50156
|
-
content: i.content,
|
|
50157
|
-
messagetype: "RichText/Html",
|
|
50158
|
-
contenttype: "Text",
|
|
50159
|
-
imdisplayname: i.meName,
|
|
50160
|
-
clientmessageid: i.clientmessageid,
|
|
50161
|
-
callId: "",
|
|
50162
|
-
state: 0,
|
|
50163
|
-
version: "0",
|
|
50164
|
-
amsreferences: [],
|
|
50165
|
-
properties: {
|
|
50166
|
-
importance: "",
|
|
50167
|
-
subject: "",
|
|
50168
|
-
title: "",
|
|
50169
|
-
cards: "[]",
|
|
50170
|
-
links: "[]",
|
|
50171
|
-
mentions: i.mentions ?? "[]",
|
|
50172
|
-
onbehalfof: null,
|
|
50173
|
-
files: "[]",
|
|
50174
|
-
policyViolation: null,
|
|
50175
|
-
formatVariant: "TEAMS",
|
|
50176
|
-
...i.qtdMsgs !== void 0 ? { qtdMsgs: i.qtdMsgs } : {}
|
|
50177
|
-
},
|
|
50178
|
-
crossPostChannels: []
|
|
50179
|
-
};
|
|
50180
|
-
}
|
|
50181
|
-
|
|
50182
|
-
// src/tools/send.ts
|
|
50183
|
-
var TOOL = "teams_send_message";
|
|
51619
|
+
var TOOL2 = "teams_send_message";
|
|
50184
51620
|
var RECENT_MESSAGES = 200;
|
|
50185
51621
|
var READBACK_MESSAGES = 50;
|
|
50186
51622
|
var MAX_CANDIDATES2 = 10;
|
|
50187
|
-
var
|
|
51623
|
+
var PREVIEW_CHARS3 = 200;
|
|
50188
51624
|
var MRI = /^\d+:\S+$/;
|
|
50189
51625
|
var mentionArg = external_exports.object({
|
|
50190
51626
|
name_in_text: external_exports.string().min(1).describe('How the person is named in text \u2014 its first "@name" (else "name") becomes the mention.'),
|
|
@@ -50277,7 +51713,7 @@ async function writeOrUnknown(run, conversation) {
|
|
|
50277
51713
|
}
|
|
50278
51714
|
function registerSendTools(server, { chatsvc }) {
|
|
50279
51715
|
server.registerTool(
|
|
50280
|
-
|
|
51716
|
+
TOOL2,
|
|
50281
51717
|
{
|
|
50282
51718
|
title: "Send a Teams message",
|
|
50283
51719
|
description: `Post a message as the signed-in user to any chat or channel, by id (from teams_list_chats / teams_list_teams_and_channels) or by name. text is plain text: it is escaped, newlines are kept, and :key: shortcodes (e.g. :smile:, :1f389_partypopper:) become Teams emoji. reply_to in a channel posts into that root post's thread; in a chat it quote-replies that message. quote quote-replies a message in any conversation. mentions @-mention people: name_in_text must appear in text, and person is an MRI or a display name matched among recent senders (ambiguous names are refused with the candidates). conversation "${SELF_CHAT}" (or "notes" / "self") is the user's own notes self-chat \u2014 use it to try this tool without anyone else seeing; other 48: system conversations are refused. Everyone in the conversation sees the post. The result says whether the post was found again by reading the conversation back (verified); status "unknown" means Teams did not confirm it \u2014 check the conversation before retrying. ` + CONFIRM_FLOW_SENTENCE + " The preview shows the conversation and exactly what would be posted. " + CONFIRM_INJECTION_RULE + UNTRUSTED_DESCRIPTION_SUFFIX2,
|
|
@@ -50324,7 +51760,7 @@ function registerSendTools(server, { chatsvc }) {
|
|
|
50324
51760
|
const { clientmessageid: _id, composetime: _c, originalarrivaltime: _o, ...bound } = draft;
|
|
50325
51761
|
const path = `/users/ME/conversations/${encodeURIComponent(postTo)}/messages`;
|
|
50326
51762
|
const gate = await confirmWrite(ctx, {
|
|
50327
|
-
tool:
|
|
51763
|
+
tool: TOOL2,
|
|
50328
51764
|
action: "chat.send_message",
|
|
50329
51765
|
message: "Review and confirm this Teams message before it is posted:",
|
|
50330
51766
|
// The title is someone else's text: JSON-quoted so it cannot break out of its quotes.
|
|
@@ -50349,7 +51785,7 @@ function registerSendTools(server, { chatsvc }) {
|
|
|
50349
51785
|
}))
|
|
50350
51786
|
)
|
|
50351
51787
|
} : {},
|
|
50352
|
-
...q ? { quoting: untrustedField({ id: q.id, sender: q.senderName, preview: clipText(q.text,
|
|
51788
|
+
...q ? { quoting: untrustedField({ id: q.id, sender: q.senderName, preview: clipText(q.text, PREVIEW_CHARS3) }) } : {},
|
|
50353
51789
|
note: "clientmessageid and the timestamps are filled in when the message is posted."
|
|
50354
51790
|
},
|
|
50355
51791
|
confirmToken
|
|
@@ -50396,7 +51832,7 @@ function registerSendTools(server, { chatsvc }) {
|
|
|
50396
51832
|
// src/tools/react.ts
|
|
50397
51833
|
init_zod();
|
|
50398
51834
|
init_dist2();
|
|
50399
|
-
var
|
|
51835
|
+
var TOOL3 = "teams_react";
|
|
50400
51836
|
var CHECKMARK_KEY = "2705_whiteheavycheckmark";
|
|
50401
51837
|
var ALIASES = {
|
|
50402
51838
|
thumbsup: "like",
|
|
@@ -50417,7 +51853,7 @@ var ALIASES = {
|
|
|
50417
51853
|
};
|
|
50418
51854
|
var RAW_KEY = /^[a-z0-9_]+$/;
|
|
50419
51855
|
var KEY_RULE = 'Unicode-style reaction keys are "<lowercase hex code point>_<the Unicode character name, lowercased, spaces and punctuation removed>" \u2014 e.g. \u{1F4AF} 1f4af_hundredpointssymbol, \u{1F440} 1f440_eyes, \u{1F62C} 1f62c_grimacingface. Teams also keeps short names for common ones: like, heart, laugh, surprised, sad, angry, yes, no, party, fire, smile, cool, wink, hearteyes, manshrug, fistbump, handsinair.';
|
|
50420
|
-
var
|
|
51856
|
+
var PREVIEW_CHARS4 = 200;
|
|
50421
51857
|
function reactionKey(input2) {
|
|
50422
51858
|
const s = input2.trim().replace(/️/g, "").replace(/^:(.+):$/, "$1").toLowerCase();
|
|
50423
51859
|
const alias = ALIASES[s];
|
|
@@ -50433,14 +51869,14 @@ function reactionKey(input2) {
|
|
|
50433
51869
|
hint: KEY_RULE
|
|
50434
51870
|
});
|
|
50435
51871
|
}
|
|
50436
|
-
async function hasMyReaction(chatsvc, conversationId,
|
|
50437
|
-
const m = await chatsvc.getMessage(conversationId,
|
|
51872
|
+
async function hasMyReaction(chatsvc, conversationId, messageId2, key, me) {
|
|
51873
|
+
const m = await chatsvc.getMessage(conversationId, messageId2);
|
|
50438
51874
|
if (m === void 0) return void 0;
|
|
50439
51875
|
return normaliseMessage(m, me).reactions?.some((r) => r.key === key && r.byMe) ?? false;
|
|
50440
51876
|
}
|
|
50441
51877
|
function registerReactTools(server, { chatsvc }) {
|
|
50442
51878
|
server.registerTool(
|
|
50443
|
-
|
|
51879
|
+
TOOL3,
|
|
50444
51880
|
{
|
|
50445
51881
|
title: "React to a Teams message",
|
|
50446
51882
|
description: `Add (or, with remove: true, withdraw) the signed-in user's reaction on a message in any chat or channel. conversation is an id or name as for teams_read_conversation; message_id comes from teams_read_conversation. reaction is an emoji or name \u2014 thumbsup/\u{1F44D}/like, heart/\u2764\uFE0F, laugh/\u{1F606}, surprised/\u{1F62E}, sad/\u{1F622}, angry/\u{1F621}, checkmark/\u2705 \u2014 or any raw Teams reaction key (e.g. fire, 1f389_partypopper); an emoji without a known key is refused with the rule for spelling its key. conversation "${SELF_CHAT}" (or "notes" / "self") is the user's own notes self-chat \u2014 use it to try this tool. Everyone in the conversation sees the reaction. The result says whether reading the message back showed the change (verified; null when the message was not found again); status "unknown" means Teams did not confirm the change and the read-back did not show it \u2014 check the message before retrying. ` + CONFIRM_FLOW_SENTENCE + " The preview shows the conversation, the message and the reaction. " + CONFIRM_INJECTION_RULE + UNTRUSTED_DESCRIPTION_SUFFIX2,
|
|
@@ -50470,7 +51906,7 @@ function registerReactTools(server, { chatsvc }) {
|
|
|
50470
51906
|
const method = remove ? "DELETE" : "PUT";
|
|
50471
51907
|
const path = `/users/ME/conversations/${encodeURIComponent(target.id)}/messages/${encodeURIComponent(message_id)}/properties?name=emotions`;
|
|
50472
51908
|
const gate = await confirmWrite(ctx, {
|
|
50473
|
-
tool:
|
|
51909
|
+
tool: TOOL3,
|
|
50474
51910
|
action: remove ? "chat.remove_reaction" : "chat.react",
|
|
50475
51911
|
message: `Review and confirm this Teams reaction before it is ${remove ? "removed" : "added"}:`,
|
|
50476
51912
|
// The title is someone else's text: JSON-quoted so it cannot break out of its quotes.
|
|
@@ -50487,7 +51923,7 @@ function registerReactTools(server, { chatsvc }) {
|
|
|
50487
51923
|
message: untrustedField({
|
|
50488
51924
|
id: m.id,
|
|
50489
51925
|
sender: m.imdisplayname?.trim() || senderMri(m.from) || "unknown",
|
|
50490
|
-
preview: clipText(htmlToText(m.content ?? ""),
|
|
51926
|
+
preview: clipText(htmlToText(m.content ?? ""), PREVIEW_CHARS4)
|
|
50491
51927
|
}),
|
|
50492
51928
|
reaction: key,
|
|
50493
51929
|
already_reacted: already
|
|
@@ -50584,13 +52020,13 @@ function activityOf(m) {
|
|
|
50584
52020
|
}
|
|
50585
52021
|
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
50586
52022
|
}
|
|
50587
|
-
function
|
|
52023
|
+
function str2(v) {
|
|
50588
52024
|
if (typeof v === "string") return v === "" ? void 0 : v;
|
|
50589
52025
|
if (typeof v === "number" && Number.isFinite(v)) return String(v);
|
|
50590
52026
|
return void 0;
|
|
50591
52027
|
}
|
|
50592
52028
|
function isoOrUndefined(v) {
|
|
50593
|
-
const s =
|
|
52029
|
+
const s = str2(v);
|
|
50594
52030
|
if (s === void 0) return void 0;
|
|
50595
52031
|
const ms = /^\d+$/.test(s) ? Number(s) : Date.parse(s);
|
|
50596
52032
|
return Number.isFinite(ms) ? new Date(ms).toISOString() : void 0;
|
|
@@ -50602,25 +52038,25 @@ function activityRow(m) {
|
|
|
50602
52038
|
if (m.properties?.deletetime) return void 0;
|
|
50603
52039
|
const a = activityOf(m);
|
|
50604
52040
|
if (a === void 0) return void 0;
|
|
50605
|
-
const type =
|
|
50606
|
-
const replyChain =
|
|
52041
|
+
const type = str2(a.activityType) ?? "";
|
|
52042
|
+
const replyChain = str2(a.sourceReplyChainId);
|
|
50607
52043
|
const isread = m.properties?.isread;
|
|
50608
52044
|
return {
|
|
50609
52045
|
id: m.id,
|
|
50610
52046
|
time: isoOrUndefined(a.activityTimestamp) ?? isoOrUndefined(m.originalarrivaltime),
|
|
50611
52047
|
kind: activityKind(type),
|
|
50612
52048
|
type,
|
|
50613
|
-
subtype:
|
|
52049
|
+
subtype: str2(a.activitySubtype) ?? "",
|
|
50614
52050
|
read: isread === true || isread === "true",
|
|
50615
|
-
from:
|
|
52051
|
+
from: str2(a.sourceUserImDisplayName),
|
|
50616
52052
|
where: {
|
|
50617
|
-
conversation_id:
|
|
50618
|
-
title:
|
|
50619
|
-
type:
|
|
52053
|
+
conversation_id: str2(a.sourceThreadId),
|
|
52054
|
+
title: str2(a.sourceThreadTopic),
|
|
52055
|
+
type: str2(a.sourceThreadType)
|
|
50620
52056
|
},
|
|
50621
|
-
message_id:
|
|
52057
|
+
message_id: str2(a.sourceMessageId),
|
|
50622
52058
|
...replyChain !== void 0 ? { reply_chain_id: replyChain } : {},
|
|
50623
|
-
preview: clip(htmlToText(
|
|
52059
|
+
preview: clip(htmlToText(str2(a.messagePreview) ?? ""))
|
|
50624
52060
|
};
|
|
50625
52061
|
}
|
|
50626
52062
|
var newestFirst = (a, b) => (b.time ?? "").localeCompare(a.time ?? "");
|
|
@@ -50672,12 +52108,314 @@ function registerActivityTools(server, { chatsvc }) {
|
|
|
50672
52108
|
);
|
|
50673
52109
|
}
|
|
50674
52110
|
|
|
52111
|
+
// src/tools/search.ts
|
|
52112
|
+
init_zod();
|
|
52113
|
+
init_dist2();
|
|
52114
|
+
var DEFAULT_LIMIT2 = 25;
|
|
52115
|
+
var MAX_LIMIT = 200;
|
|
52116
|
+
var DEFAULT_SINCE_DAYS2 = 30;
|
|
52117
|
+
var DAY_MS2 = 864e5;
|
|
52118
|
+
var DEFAULT_SCANNED_CONVERSATIONS = 100;
|
|
52119
|
+
var MAX_SCANNED_CONVERSATIONS = 500;
|
|
52120
|
+
var MAX_RAW_PER_CONVERSATION = 1e3;
|
|
52121
|
+
var SUBSTRATE_PAGE_SIZE = 50;
|
|
52122
|
+
var MAX_SUBSTRATE_PAGES = 10;
|
|
52123
|
+
var MODES2 = ["auto", "substrate", "scan"];
|
|
52124
|
+
function queryTerms(query) {
|
|
52125
|
+
const terms = [];
|
|
52126
|
+
for (const [, phrase, word] of query.toLowerCase().matchAll(/"([^"]*)"|(\S+)/g)) {
|
|
52127
|
+
const t = (phrase ?? word ?? "").replace(/"/g, "").trim();
|
|
52128
|
+
if (t !== "") terms.push(t);
|
|
52129
|
+
}
|
|
52130
|
+
return terms;
|
|
52131
|
+
}
|
|
52132
|
+
function matchesQuery(text, query) {
|
|
52133
|
+
const terms = queryTerms(query);
|
|
52134
|
+
if (terms.length === 0) return false;
|
|
52135
|
+
const haystack = text.toLowerCase();
|
|
52136
|
+
return terms.every((t) => haystack.includes(t));
|
|
52137
|
+
}
|
|
52138
|
+
function hitMessage(m) {
|
|
52139
|
+
const { attachments: _a3, reactions: _r, deleted: _d, ...rest } = m;
|
|
52140
|
+
return rest;
|
|
52141
|
+
}
|
|
52142
|
+
function hitConversation(s) {
|
|
52143
|
+
return { id: s.id, title: s.title, kind: s.kind, ...s.team !== void 0 ? { team: s.team } : {} };
|
|
52144
|
+
}
|
|
52145
|
+
function registerSearchTools(server, { chatsvc, substrate }) {
|
|
52146
|
+
server.registerTool(
|
|
52147
|
+
"teams_search_messages",
|
|
52148
|
+
{
|
|
52149
|
+
title: "Search Teams messages",
|
|
52150
|
+
description: `Find messages by text across the chats and channels the signed-in user is in. Hits come newest first, each with its conversation (id, title, kind, team) and the message (id, time ISO 8601, sender, fromMe (scan only), text, subject, replyTo for a channel reply); read a hit in context with teams_read_conversation. conversation narrows to one chat or channel (id or name); from keeps messages whose sender display name contains it; since (ISO 8601) sets how far back to look (default the last ${DEFAULT_SINCE_DAYS2} days); limit caps the hits (default ${DEFAULT_LIMIT2}, max ${MAX_LIMIT}; total_hits and truncated say when there were more). source says which path answered. mode "auto" (default) uses Teams' own search (Microsoft Substrate: matched the way the Teams search box matches \u2014 words ANDed with stemming, "quoted phrases", OR \u2014 and fast; conversation and since apply to it too; its text is a plain-text preview of up to ~255 characters, marked excerpt: true, and its hits carry no fromMe) and falls back to a scan, with fallback_reason, when Substrate is unavailable or fails \u2014 its token is captured from a Teams tab the first time, so a first search may need you to run any search in the Teams search box. mode "substrate" uses only Substrate (an error rather than a fallback); mode "scan" only scans. The SCAN requires every word of query to appear in the message text (any order, ignoring case; "quoted words" match as a phrase) and reads the ${DEFAULT_SCANNED_CONVERSATIONS} (max_conversations, up to ${MAX_SCANNED_CONVERSATIONS}) most recently active conversations with activity since the cutoff back to it (channels hidden in Teams are skipped unless named); scan reports what was read and what the bounds left out \u2014 a busy window can take a while, so narrow with conversation or since when you can. Deleted messages and system events never match. This does NOT mark anything read.` + UNTRUSTED_DESCRIPTION_SUFFIX2,
|
|
52151
|
+
annotations: toolAnnotations({ readOnly: true, openWorld: true }),
|
|
52152
|
+
inputSchema: {
|
|
52153
|
+
query: external_exports.string().refine((s) => queryTerms(s).length > 0, { message: "query must contain a word to search for" }).describe(
|
|
52154
|
+
'Words to find in the message text, ignoring case. Substrate (the default) matches the way the Teams search box does (words ANDed with stemming, "quoted phrases", OR). The scan requires every word to appear verbatim, any order; words in double quotes match as one phrase.'
|
|
52155
|
+
),
|
|
52156
|
+
conversation: external_exports.string().min(1).optional().describe(
|
|
52157
|
+
`Search only this chat or channel: its id ("48:notes", "notes" or "self" for the self-chat), or a case-insensitive substring of its title, channel name, team name or an untitled chat's participant names (it must name exactly one).`
|
|
52158
|
+
),
|
|
52159
|
+
from: external_exports.string().min(1).optional().describe("Only messages whose sender's display name contains this, ignoring case."),
|
|
52160
|
+
since: external_exports.string().refine((s) => !Number.isNaN(Date.parse(s)), { message: "since must be an ISO 8601 date-time" }).optional().describe(
|
|
52161
|
+
`Only messages at or after this ISO 8601 date-time (default ${DEFAULT_SINCE_DAYS2} days ago). An older since makes a scan search further back and take longer.`
|
|
52162
|
+
),
|
|
52163
|
+
limit: external_exports.number().int().min(1).max(MAX_LIMIT).optional().describe(`Maximum hits to return, newest kept (default ${DEFAULT_LIMIT2}, max ${MAX_LIMIT}).`),
|
|
52164
|
+
max_conversations: external_exports.number().int().min(1).max(MAX_SCANNED_CONVERSATIONS).optional().describe(
|
|
52165
|
+
`Scan only: most conversations to read, most recently active first (default ${DEFAULT_SCANNED_CONVERSATIONS}, max ${MAX_SCANNED_CONVERSATIONS}). More finds hits in quieter conversations but takes longer (roughly 15s per 100).`
|
|
52166
|
+
),
|
|
52167
|
+
mode: external_exports.enum(MODES2).optional().describe(
|
|
52168
|
+
`"auto" (default): Teams' own search (Substrate), falling back to a scan when it is unavailable or fails. "substrate": Substrate only, failing instead of falling back. "scan": the client-side scan only.`
|
|
52169
|
+
)
|
|
52170
|
+
}
|
|
52171
|
+
},
|
|
52172
|
+
async ({ query, conversation, from, since, limit, max_conversations, mode }) => {
|
|
52173
|
+
try {
|
|
52174
|
+
const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
|
|
52175
|
+
const cutoff = since !== void 0 ? Date.parse(since) : Date.now() - DEFAULT_SINCE_DAYS2 * DAY_MS2;
|
|
52176
|
+
const target = conversation !== void 0 ? await resolveListed(chatsvc, raw, me, conversation, "search") : void 0;
|
|
52177
|
+
const args = {
|
|
52178
|
+
query,
|
|
52179
|
+
...target !== void 0 ? { target } : {},
|
|
52180
|
+
...from !== void 0 ? { fromLc: from.trim().toLowerCase() } : {},
|
|
52181
|
+
cutoff,
|
|
52182
|
+
cap: limit ?? DEFAULT_LIMIT2
|
|
52183
|
+
};
|
|
52184
|
+
const m = mode ?? "auto";
|
|
52185
|
+
let fallbackReason;
|
|
52186
|
+
if (m !== "scan") {
|
|
52187
|
+
const unavailable = substrate === void 0 ? "Substrate search is not available in this server." : !substrate.isConfigured() ? "Substrate search is disabled: TEAMS_DISABLE_FETCHPROXY is set, and the browser bridge is its only token source." : void 0;
|
|
52188
|
+
if (unavailable !== void 0 || substrate === void 0) {
|
|
52189
|
+
const reason = unavailable ?? "Substrate search is not available in this server.";
|
|
52190
|
+
if (m === "substrate") {
|
|
52191
|
+
throw new McpToolError(reason, { kind: "no_credential", hint: 'Use mode "auto" or "scan" to search by scanning instead.' });
|
|
52192
|
+
}
|
|
52193
|
+
fallbackReason = reason;
|
|
52194
|
+
} else {
|
|
52195
|
+
try {
|
|
52196
|
+
return untrustedResult2({
|
|
52197
|
+
query,
|
|
52198
|
+
source: "substrate",
|
|
52199
|
+
...await substrateSearch(substrate, chatsvc, raw, me, args, m === "substrate")
|
|
52200
|
+
});
|
|
52201
|
+
} catch (err) {
|
|
52202
|
+
if (m === "substrate") throw err;
|
|
52203
|
+
fallbackReason = wrapApiError(err, "search with Substrate").message;
|
|
52204
|
+
}
|
|
52205
|
+
}
|
|
52206
|
+
}
|
|
52207
|
+
return untrustedResult2({
|
|
52208
|
+
query,
|
|
52209
|
+
source: "scan",
|
|
52210
|
+
...fallbackReason !== void 0 ? { fallback_reason: fallbackReason } : {},
|
|
52211
|
+
...await scanSearch(chatsvc, raw, me, args, max_conversations)
|
|
52212
|
+
});
|
|
52213
|
+
} catch (err) {
|
|
52214
|
+
throw wrapApiError(err, "search messages");
|
|
52215
|
+
}
|
|
52216
|
+
}
|
|
52217
|
+
);
|
|
52218
|
+
}
|
|
52219
|
+
function summaryFor(id, listed, raw, me) {
|
|
52220
|
+
const c = listed.get(id);
|
|
52221
|
+
if (c !== void 0) return conversationSummary(c, me, raw);
|
|
52222
|
+
return { id, kind: conversationKind({ id }), title: id, unread: false, unread_confirmed: false };
|
|
52223
|
+
}
|
|
52224
|
+
async function substrateSearch(substrate, chatsvc, raw, me, { query, target, fromLc, cutoff, cap }, force) {
|
|
52225
|
+
const found = [];
|
|
52226
|
+
let pages = 0;
|
|
52227
|
+
let resultsRead = 0;
|
|
52228
|
+
let filteredOut = 0;
|
|
52229
|
+
let unmapped = 0;
|
|
52230
|
+
let total;
|
|
52231
|
+
let more = false;
|
|
52232
|
+
for (let offset = 0; pages < MAX_SUBSTRATE_PAGES; offset += SUBSTRATE_PAGE_SIZE) {
|
|
52233
|
+
const page = await substrate.searchMessages(
|
|
52234
|
+
{
|
|
52235
|
+
query,
|
|
52236
|
+
from: offset,
|
|
52237
|
+
size: SUBSTRATE_PAGE_SIZE,
|
|
52238
|
+
// Both restrictions are verified server-side; the checks below stay as a backstop.
|
|
52239
|
+
...target !== void 0 ? { conversationId: target.id } : {},
|
|
52240
|
+
sentAfter: cutoff
|
|
52241
|
+
},
|
|
52242
|
+
force ? { force } : void 0
|
|
52243
|
+
);
|
|
52244
|
+
pages++;
|
|
52245
|
+
resultsRead += page.results.length;
|
|
52246
|
+
unmapped += page.unmapped;
|
|
52247
|
+
total ??= page.total;
|
|
52248
|
+
more = page.moreAvailable;
|
|
52249
|
+
let anyInWindow = false;
|
|
52250
|
+
for (const r of page.results) {
|
|
52251
|
+
const at = r.time !== void 0 ? Date.parse(r.time) : NaN;
|
|
52252
|
+
if (Number.isFinite(at) && at < cutoff) {
|
|
52253
|
+
filteredOut++;
|
|
52254
|
+
continue;
|
|
52255
|
+
}
|
|
52256
|
+
anyInWindow = true;
|
|
52257
|
+
if (target !== void 0 && r.conversationId !== target.id) filteredOut++;
|
|
52258
|
+
else if (fromLc !== void 0 && !(r.sender ?? "").toLowerCase().includes(fromLc)) filteredOut++;
|
|
52259
|
+
else found.push({ hit: r, at });
|
|
52260
|
+
}
|
|
52261
|
+
if (!more || page.results.length === 0 || found.length > cap || !anyInWindow) break;
|
|
52262
|
+
}
|
|
52263
|
+
found.sort((a, b) => (Number.isFinite(b.at) ? b.at : 0) - (Number.isFinite(a.at) ? a.at : 0));
|
|
52264
|
+
const kept = found.slice(0, cap);
|
|
52265
|
+
const listed = new Map(raw.map((c) => [c.id, c]));
|
|
52266
|
+
const summaries = [...new Map(kept.map(({ hit }) => [hit.conversationId, summaryFor(hit.conversationId, listed, raw, me)])).values()];
|
|
52267
|
+
const titled = new Map(
|
|
52268
|
+
(await enrichTitles(chatsvc, raw, me, summaries.filter((s) => listed.has(s.id)))).map((s) => [s.id, s])
|
|
52269
|
+
);
|
|
52270
|
+
const bySummary = new Map(summaries.map((s) => [s.id, titled.get(s.id) ?? s]));
|
|
52271
|
+
const hits = kept.map(({ hit }) => ({
|
|
52272
|
+
conversation: hitConversation(bySummary.get(hit.conversationId) ?? summaryFor(hit.conversationId, listed, raw, me)),
|
|
52273
|
+
message: {
|
|
52274
|
+
...hit.messageId !== void 0 ? { id: hit.messageId } : {},
|
|
52275
|
+
...hit.time !== void 0 ? { time: hit.time } : {},
|
|
52276
|
+
sender: hit.sender ?? "",
|
|
52277
|
+
// No fromMe: a Substrate hit names its sender by display name and SMTP address only.
|
|
52278
|
+
text: hit.text,
|
|
52279
|
+
excerpt: true,
|
|
52280
|
+
...hit.subject !== void 0 ? { subject: hit.subject } : {},
|
|
52281
|
+
...hit.replyTo !== void 0 ? { replyTo: hit.replyTo } : {}
|
|
52282
|
+
}
|
|
52283
|
+
}));
|
|
52284
|
+
const totalHits = more && filteredOut === 0 && total !== void 0 ? Math.max(total, found.length) : found.length;
|
|
52285
|
+
const sinceIso = new Date(cutoff).toISOString();
|
|
52286
|
+
const pageCapped = pages >= MAX_SUBSTRATE_PAGES && more && found.length <= cap;
|
|
52287
|
+
return {
|
|
52288
|
+
total_hits: totalHits,
|
|
52289
|
+
hits,
|
|
52290
|
+
...totalHits > kept.length ? {
|
|
52291
|
+
truncated: {
|
|
52292
|
+
total: totalHits,
|
|
52293
|
+
returned: kept.length,
|
|
52294
|
+
hint: `Only the newest ${kept.length} hits were returned; pass a larger limit (max ${MAX_LIMIT}) or narrow with conversation, from or since.`
|
|
52295
|
+
}
|
|
52296
|
+
} : {},
|
|
52297
|
+
substrate: {
|
|
52298
|
+
since: sinceIso,
|
|
52299
|
+
pages_read: pages,
|
|
52300
|
+
results_read: resultsRead,
|
|
52301
|
+
results_filtered_out: filteredOut,
|
|
52302
|
+
...unmapped > 0 ? { results_unmapped: unmapped } : {},
|
|
52303
|
+
more_available: more,
|
|
52304
|
+
...pageCapped ? {
|
|
52305
|
+
hint: `Read the first ${MAX_SUBSTRATE_PAGES * SUBSTRATE_PAGE_SIZE} Substrate results and stopped; narrow with conversation, from or a later since, or a more specific query.`
|
|
52306
|
+
} : {}
|
|
52307
|
+
}
|
|
52308
|
+
};
|
|
52309
|
+
}
|
|
52310
|
+
async function scanSearch(chatsvc, raw, me, { query, target, fromLc, cutoff, cap }, maxConversations) {
|
|
52311
|
+
let targets;
|
|
52312
|
+
let outsideWindow = 0;
|
|
52313
|
+
if (target !== void 0) {
|
|
52314
|
+
targets = [target];
|
|
52315
|
+
} else {
|
|
52316
|
+
const inWindow = [];
|
|
52317
|
+
for (const c of raw) {
|
|
52318
|
+
const summary = conversationSummary(c, me, raw);
|
|
52319
|
+
if (summary.hidden === true) continue;
|
|
52320
|
+
const newest = newestActivityMs(c);
|
|
52321
|
+
if (newest !== void 0 && newest < cutoff) outsideWindow++;
|
|
52322
|
+
else inWindow.push({ summary, newest: newest ?? 0 });
|
|
52323
|
+
}
|
|
52324
|
+
inWindow.sort((a, b) => b.newest - a.newest);
|
|
52325
|
+
targets = inWindow.map((c) => c.summary);
|
|
52326
|
+
}
|
|
52327
|
+
const maxScanned = maxConversations ?? DEFAULT_SCANNED_CONVERSATIONS;
|
|
52328
|
+
const scanned = targets.slice(0, maxScanned);
|
|
52329
|
+
const notScanned = targets.length - scanned.length;
|
|
52330
|
+
const reads = await mapWithConcurrency(scanned, CONFIRM_CONCURRENCY, async (summary) => {
|
|
52331
|
+
let capped = false;
|
|
52332
|
+
try {
|
|
52333
|
+
const fetched = await chatsvc.getMessages(summary.id, {
|
|
52334
|
+
stopAt: (m) => {
|
|
52335
|
+
const at = arrivalMs(m);
|
|
52336
|
+
return Number.isFinite(at) && at < cutoff;
|
|
52337
|
+
},
|
|
52338
|
+
max: MAX_RAW_PER_CONVERSATION,
|
|
52339
|
+
onCapped: () => capped = true
|
|
52340
|
+
});
|
|
52341
|
+
const hits2 = fetched.filter((m) => {
|
|
52342
|
+
if (!isUserMessage(m)) return false;
|
|
52343
|
+
const n = normaliseMessage(m, me);
|
|
52344
|
+
if (n.deleted) return false;
|
|
52345
|
+
if (fromLc !== void 0 && !n.sender.toLowerCase().includes(fromLc)) return false;
|
|
52346
|
+
return matchesQuery(n.subject !== void 0 ? `${n.subject}
|
|
52347
|
+
${n.text}` : n.text, query);
|
|
52348
|
+
});
|
|
52349
|
+
return { kind: "read", hits: hits2, seen: fetched.length, capped };
|
|
52350
|
+
} catch (error62) {
|
|
52351
|
+
return isUnreachable(error62) ? { kind: "unreachable" } : { kind: "failed", error: error62 };
|
|
52352
|
+
}
|
|
52353
|
+
});
|
|
52354
|
+
const found = [];
|
|
52355
|
+
const failed = [];
|
|
52356
|
+
const partial2 = [];
|
|
52357
|
+
let unreachable = 0;
|
|
52358
|
+
let messagesScanned = 0;
|
|
52359
|
+
let anyRead = false;
|
|
52360
|
+
reads.forEach((r, i) => {
|
|
52361
|
+
const summary = scanned[i];
|
|
52362
|
+
if (r.kind === "unreachable") unreachable++;
|
|
52363
|
+
else if (r.kind === "failed") failed.push({ summary, error: r.error });
|
|
52364
|
+
else {
|
|
52365
|
+
anyRead = true;
|
|
52366
|
+
messagesScanned += r.seen;
|
|
52367
|
+
if (r.capped) partial2.push(summary);
|
|
52368
|
+
for (const m of r.hits) found.push({ summary, message: normaliseMessage(m, me), at: arrivalMs(m) });
|
|
52369
|
+
}
|
|
52370
|
+
});
|
|
52371
|
+
if (failed.length > 0 && !anyRead) throw failed[0].error;
|
|
52372
|
+
found.sort((a, b) => (Number.isFinite(b.at) ? b.at : 0) - (Number.isFinite(a.at) ? a.at : 0));
|
|
52373
|
+
const kept = found.slice(0, cap);
|
|
52374
|
+
const named = [...new Map([...kept.map((h) => h.summary), ...partial2, ...failed.map((f) => f.summary)].map((s) => [s.id, s])).values()];
|
|
52375
|
+
const titled = new Map((await enrichTitles(chatsvc, raw, me, named)).map((s) => [s.id, s]));
|
|
52376
|
+
const final = (s) => titled.get(s.id) ?? s;
|
|
52377
|
+
const hits = kept.map((h) => ({ conversation: hitConversation(final(h.summary)), message: hitMessage(h.message) }));
|
|
52378
|
+
const sinceIso = new Date(cutoff).toISOString();
|
|
52379
|
+
const leftOut = notScanned > 0 || partial2.length > 0;
|
|
52380
|
+
return {
|
|
52381
|
+
total_hits: found.length,
|
|
52382
|
+
hits,
|
|
52383
|
+
...found.length > kept.length ? {
|
|
52384
|
+
truncated: {
|
|
52385
|
+
total: found.length,
|
|
52386
|
+
returned: kept.length,
|
|
52387
|
+
hint: `Only the newest ${kept.length} of ${found.length} hits were returned; pass a larger limit (max ${MAX_LIMIT}) or narrow with conversation, from or since.`
|
|
52388
|
+
}
|
|
52389
|
+
} : {},
|
|
52390
|
+
scan: {
|
|
52391
|
+
method: "client_scan",
|
|
52392
|
+
since: sinceIso,
|
|
52393
|
+
conversations_scanned: scanned.length,
|
|
52394
|
+
conversations_outside_window: outsideWindow,
|
|
52395
|
+
conversations_not_scanned: notScanned,
|
|
52396
|
+
messages_scanned: messagesScanned,
|
|
52397
|
+
skipped_unreachable: unreachable,
|
|
52398
|
+
...partial2.length > 0 ? { partially_scanned: partial2.map((s) => ({ id: s.id, title: final(s).title })) } : {},
|
|
52399
|
+
...leftOut ? {
|
|
52400
|
+
hint: (notScanned > 0 ? `${notScanned} less recently active conversation${notScanned === 1 ? " was" : "s were"} not scanned (max_conversations ${maxScanned}; up to ${MAX_SCANNED_CONVERSATIONS}). ` : "") + (partial2.length > 0 ? `${partial2.length} conversation${partial2.length === 1 ? " was" : "s were"} only read back ${MAX_RAW_PER_CONVERSATION} messages, short of ${sinceIso}. ` : "") + "Raise max_conversations, or narrow with conversation or a later since, to search everything in range."
|
|
52401
|
+
} : {}
|
|
52402
|
+
},
|
|
52403
|
+
...failed.length > 0 ? {
|
|
52404
|
+
errors: failed.map((f) => ({
|
|
52405
|
+
conversation: hitConversation(final(f.summary)),
|
|
52406
|
+
error: wrapApiError(f.error, "search this conversation").message
|
|
52407
|
+
}))
|
|
52408
|
+
} : {}
|
|
52409
|
+
};
|
|
52410
|
+
}
|
|
52411
|
+
|
|
50675
52412
|
// src/tools/healthcheck.ts
|
|
50676
52413
|
init_dist2();
|
|
50677
52414
|
init_healthcheck();
|
|
50678
52415
|
var HOST_LABEL = "teams.cloud.microsoft";
|
|
50679
52416
|
var TITLE = "Verify the Teams chat-service token and API end-to-end";
|
|
50680
52417
|
var SHAREPOINT_NOTE = "Shared-file download (teams_get_attachment) uses a separate SharePoint token, captured on demand per SharePoint host and short-lived (~53 min). None is held until you open a file, and this healthcheck neither mints nor requires one.";
|
|
52418
|
+
var SUBSTRATE_NOTE = "Search (teams_search_messages) uses a separate Microsoft Substrate token for substrate.office.com, captured on demand when you run a search in a Teams tab (the bridge pairing must trust substrate.office.com). Without one, search falls back to a scan of recent conversations; this healthcheck neither mints nor requires one.";
|
|
50681
52419
|
function registerHealthcheckTool(server, { chatsvc }) {
|
|
50682
52420
|
server.registerTool(
|
|
50683
52421
|
"teams_healthcheck",
|
|
@@ -50727,7 +52465,7 @@ function registerHealthcheckTool(server, { chatsvc }) {
|
|
|
50727
52465
|
...result.content,
|
|
50728
52466
|
{
|
|
50729
52467
|
type: "text",
|
|
50730
|
-
text: JSON.stringify({ chat_service: chatService, sharepoint: SHAREPOINT_NOTE }, null, 2)
|
|
52468
|
+
text: JSON.stringify({ chat_service: chatService, sharepoint: SHAREPOINT_NOTE, substrate: SUBSTRATE_NOTE }, null, 2)
|
|
50731
52469
|
}
|
|
50732
52470
|
]
|
|
50733
52471
|
};
|
|
@@ -50736,7 +52474,7 @@ function registerHealthcheckTool(server, { chatsvc }) {
|
|
|
50736
52474
|
content: [
|
|
50737
52475
|
{
|
|
50738
52476
|
type: "text",
|
|
50739
|
-
text: JSON.stringify({ ...body, chat_service: chatService, sharepoint: SHAREPOINT_NOTE }, null, 2)
|
|
52477
|
+
text: JSON.stringify({ ...body, chat_service: chatService, sharepoint: SHAREPOINT_NOTE, substrate: SUBSTRATE_NOTE }, null, 2)
|
|
50740
52478
|
}
|
|
50741
52479
|
]
|
|
50742
52480
|
};
|
|
@@ -50749,7 +52487,8 @@ var TOKEN_CAPTURE_HINT = "No Teams access token could be captured. Open a signed
|
|
|
50749
52487
|
loadDotenvSafely();
|
|
50750
52488
|
var deps = {
|
|
50751
52489
|
chatsvc: new ChatServiceClient(),
|
|
50752
|
-
sharepoint: new SharePointClient()
|
|
52490
|
+
sharepoint: new SharePointClient(),
|
|
52491
|
+
substrate: new SubstrateClient()
|
|
50753
52492
|
};
|
|
50754
52493
|
await runMcp({
|
|
50755
52494
|
name: "microsoft-teams-mcp",
|
|
@@ -50761,10 +52500,13 @@ await runMcp({
|
|
|
50761
52500
|
registerChannelTools,
|
|
50762
52501
|
registerConversationTools,
|
|
50763
52502
|
registerUnreadTools,
|
|
52503
|
+
registerChangesTools,
|
|
50764
52504
|
registerAttachmentTools,
|
|
50765
52505
|
registerSendTools,
|
|
50766
52506
|
registerReactTools,
|
|
52507
|
+
registerMarkReadTools,
|
|
50767
52508
|
registerActivityTools,
|
|
52509
|
+
registerSearchTools,
|
|
50768
52510
|
registerHealthcheckTool
|
|
50769
52511
|
]
|
|
50770
52512
|
});
|