@chrischall/microsoft-teams-mcp 0.6.0 → 0.6.2

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/dist/bundle.js CHANGED
@@ -248,6 +248,7 @@ __export(util_exports, {
248
248
  required: () => required,
249
249
  safeExtend: () => safeExtend,
250
250
  shallowClone: () => shallowClone,
251
+ sizeCaps: () => sizeCaps,
251
252
  slugify: () => slugify,
252
253
  stringifyPrimitive: () => stringifyPrimitive,
253
254
  toZod: () => toZod,
@@ -671,6 +672,18 @@ function prefixIssues(path, issues) {
671
672
  function unwrapMessage(message) {
672
673
  return typeof message === "string" ? message : message?.message;
673
674
  }
675
+ function sizeCaps(defChecks) {
676
+ const caps = [];
677
+ for (const ch of defChecks ?? []) {
678
+ const d = ch._zod.def;
679
+ if (!/_(length|size)$|_equals$/.test(d.check))
680
+ break;
681
+ const max = d.maximum ?? d.length ?? d.size;
682
+ if (max >= 0)
683
+ caps.push([max, ch]);
684
+ }
685
+ return caps;
686
+ }
674
687
  function attachSchema(issues, start, inst) {
675
688
  var _a3;
676
689
  for (let i = start; i < issues.length; i++) {
@@ -2234,7 +2247,7 @@ var init_versions = __esm({
2234
2247
  version = {
2235
2248
  major: 4,
2236
2249
  minor: 6,
2237
- patch: 5
2250
+ patch: 7
2238
2251
  };
2239
2252
  }
2240
2253
  });
@@ -2396,6 +2409,28 @@ function isValidJWT(token, algorithm = null) {
2396
2409
  return false;
2397
2410
  }
2398
2411
  }
2412
+ function capSize(inst, size) {
2413
+ const caps = sizeCaps(inst._zod.def.checks);
2414
+ if (!caps.length)
2415
+ return;
2416
+ const cap = Math.min(...caps.map((c) => c[0]));
2417
+ const parse3 = inst._zod.parse;
2418
+ inst._zod.parse = (payload, ctx) => {
2419
+ const n = size(payload.value);
2420
+ if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") {
2421
+ for (const [max, ch] of sizeCaps(inst._zod.def.checks)) {
2422
+ if (n > max && ch._zod.def.when(payload)) {
2423
+ const start = payload.issues.length;
2424
+ ch._zod.check(payload);
2425
+ payload.issues[start].continue = false;
2426
+ attachSchema(payload.issues, start, inst);
2427
+ return payload;
2428
+ }
2429
+ }
2430
+ }
2431
+ return parse3(payload, ctx);
2432
+ };
2433
+ }
2399
2434
  function handleArrayResult(result, final, index) {
2400
2435
  if (result.issues.length) {
2401
2436
  final.issues.push(...prefixIssues(index, result.issues));
@@ -2896,7 +2931,7 @@ function handleRefineResult(result, payload, input2, inst) {
2896
2931
  payload.issues.push(issue(_iss));
2897
2932
  }
2898
2933
  }
2899
- var $ZodType, toStandardResult, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, URL_BAD_FORMAT, URL_UNPARSEABLE, asciiTabOrNewline, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, ipv6Alphabet, $ZodIPv6, $ZodMAC, $ZodCIDRv4, $ZodCIDRv6, base64Charset, $ZodBase64, base64urlCharset, $ZodBase64URL, $ZodE164, CC_SANITIZE, $ZodCreditCard, $ZodIBAN, $ZodJWT, $ZodCustomStringFormat, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodBigInt, $ZodBigIntFormat, $ZodSymbol, $ZodUndefined, $ZodNull, $ZodAny, $ZodUnknown, $ZodNever, $ZodVoid, $ZodDate, $ZodArray, NO_SYMBOL_KEYS, $ZodObject, $ZodObjectJIT, $ZodUnion, $ZodXor, $ZodDiscriminatedUnion, $ZodIntersection, $ZodTuple, $ZodRecord, $ZodMap, $ZodSet, $ZodEnum, $ZodLiteral, $ZodFile, $ZodTransform, $ZodOptional, $ZodExactOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodSuccess, $ZodCatch, $ZodNaN, $ZodPipe, $ZodCodec, $ZodPreprocess, $ZodReadonly, $ZodTemplateLiteral, $ZodFunction, $ZodPromise, $ZodLazy, $ZodCustom;
2934
+ var $ZodType, toStandardResult, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, URL_BAD_FORMAT, URL_UNPARSEABLE, asciiTabOrNewline, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, ipv6Alphabet, $ZodIPv6, $ZodMAC, $ZodCIDRv4, $ZodCIDRv6, base64Charset, $ZodBase64, base64urlCharset, $ZodBase64URL, $ZodE164, CC_SANITIZE, $ZodCreditCard, $ZodIBAN, $ZodJWT, $ZodCustomStringFormat, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodBigInt, $ZodBigIntFormat, $ZodSymbol, $ZodUndefined, $ZodNull, $ZodAny, $ZodUnknown, $ZodNever, $ZodVoid, $ZodDate, arraySize, mapSize, setSize, $ZodArray, NO_SYMBOL_KEYS, $ZodObject, $ZodObjectJIT, $ZodUnion, $ZodXor, $ZodDiscriminatedUnion, $ZodIntersection, $ZodTuple, $ZodRecord, $ZodMap, $ZodSet, $ZodEnum, $ZodLiteral, $ZodFile, $ZodTransform, $ZodOptional, $ZodExactOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodSuccess, $ZodCatch, $ZodNaN, $ZodPipe, $ZodCodec, $ZodPreprocess, $ZodReadonly, $ZodTemplateLiteral, $ZodFunction, $ZodPromise, $ZodLazy, $ZodCustom;
2900
2935
  var init_schemas = __esm({
2901
2936
  "node_modules/zod/v4/core/schemas.js"() {
2902
2937
  init_checks();
@@ -3503,6 +3538,9 @@ var init_schemas = __esm({
3503
3538
  return payload;
3504
3539
  };
3505
3540
  });
3541
+ arraySize = (input2) => Array.isArray(input2) ? input2.length : -1;
3542
+ mapSize = (input2) => input2 instanceof Map ? input2.size : -1;
3543
+ setSize = (input2) => input2 instanceof Set ? input2.size : -1;
3506
3544
  $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
3507
3545
  $ZodType.init(inst, def);
3508
3546
  const memo3 = globalConfig.memoizer;
@@ -3540,6 +3578,7 @@ var init_schemas = __esm({
3540
3578
  }
3541
3579
  return payload;
3542
3580
  };
3581
+ capSize(inst, arraySize);
3543
3582
  });
3544
3583
  NO_SYMBOL_KEYS = [];
3545
3584
  $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
@@ -4178,6 +4217,7 @@ var init_schemas = __esm({
4178
4217
  return Promise.all(proms).then(() => payload);
4179
4218
  return payload;
4180
4219
  };
4220
+ capSize(inst, mapSize);
4181
4221
  });
4182
4222
  $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => {
4183
4223
  $ZodType.init(inst, def);
@@ -4214,6 +4254,7 @@ var init_schemas = __esm({
4214
4254
  return Promise.all(proms).then(() => payload);
4215
4255
  return payload;
4216
4256
  };
4257
+ capSize(inst, setSize);
4217
4258
  });
4218
4259
  $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
4219
4260
  $ZodType.init(inst, def);
@@ -14003,9 +14044,15 @@ function generateNullableCheck(doc, ctx, schema, accessor, buildsValue = true) {
14003
14044
  doc.write(`}`);
14004
14045
  return outputVar;
14005
14046
  }
14047
+ function generateSizeGate(doc, schema, size) {
14048
+ for (const [max, check2] of sizeCaps(schema._zod.def.checks)) {
14049
+ doc.write(`if (${size} > ${numericOperand(max, check2._zod.def.check)}) return INVALID;`);
14050
+ }
14051
+ }
14006
14052
  function generateArrayCheck(doc, ctx, schema, accessor, buildsValue = true) {
14007
14053
  const def = schema._zod.def;
14008
14054
  doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);
14055
+ generateSizeGate(doc, schema, `${accessor}.length`);
14009
14056
  const outputVar = buildsValue ? newVar(ctx) : null;
14010
14057
  const iVar = newVar(ctx);
14011
14058
  const elemVar = newVar(ctx);
@@ -14405,6 +14452,7 @@ function literalPropertyKey(ctx, key) {
14405
14452
  function generateMapCheck(doc, ctx, schema, accessor) {
14406
14453
  const def = schema._zod.def;
14407
14454
  doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`);
14455
+ generateSizeGate(doc, schema, `${accessor}.size`);
14408
14456
  const outputVar = newVar(ctx);
14409
14457
  const kVar = newVar(ctx);
14410
14458
  const valVar = newVar(ctx);
@@ -14421,6 +14469,7 @@ function generateMapCheck(doc, ctx, schema, accessor) {
14421
14469
  function generateSetCheck(doc, ctx, schema, accessor) {
14422
14470
  const def = schema._zod.def;
14423
14471
  doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`);
14472
+ generateSizeGate(doc, schema, `${accessor}.size`);
14424
14473
  const outputVar = newVar(ctx);
14425
14474
  const valVar = newVar(ctx);
14426
14475
  doc.write(`const ${outputVar} = new Set();`);
@@ -35372,10 +35421,33 @@ function redactJsonCookie(quote) {
35372
35421
  function redactSecrets(text) {
35373
35422
  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
35423
  }
35375
- function truncateErrorMessage(text, max = DEFAULT_ERROR_MESSAGE_MAX) {
35424
+ function redactValues(text, values, opts = {}) {
35425
+ const placeholder = opts.placeholder ?? "[REDACTED]";
35426
+ const minLength = Math.max(1, opts.minLength ?? 1);
35427
+ const needles = /* @__PURE__ */ new Set();
35428
+ for (const value of values) {
35429
+ if (typeof value !== "string" || value.length < minLength)
35430
+ continue;
35431
+ needles.add(value);
35432
+ if (opts.jsonEscaped !== false) {
35433
+ const escaped = JSON.stringify(value).slice(1, -1);
35434
+ if (escaped !== value && escaped.length >= minLength)
35435
+ needles.add(escaped);
35436
+ }
35437
+ }
35438
+ let out = String(text ?? "");
35439
+ for (const needle of [...needles].sort((a, b) => b.length - a.length)) {
35440
+ if (out.includes(needle))
35441
+ out = out.split(needle).join(placeholder);
35442
+ }
35443
+ return out;
35444
+ }
35445
+ function truncateErrorMessage(text, max = DEFAULT_ERROR_MESSAGE_MAX, opts = {}) {
35376
35446
  const str3 = text === null || text === void 0 ? "" : String(text);
35377
35447
  const cap = Math.max(ERROR_REDACTION_INPUT_MAX, max);
35378
- const redacted = redactSecrets(str3.length > cap ? str3.slice(0, cap) : str3);
35448
+ const capped = str3.length > cap ? str3.slice(0, cap) : str3;
35449
+ const scrubbed = opts.values !== void 0 ? redactValues(capped, opts.values, opts.placeholder !== void 0 ? { placeholder: opts.placeholder } : {}) : capped;
35450
+ const redacted = redactSecrets(scrubbed);
35379
35451
  if (redacted.length <= max)
35380
35452
  return redacted;
35381
35453
  return `${redacted.slice(0, max)}\u2026 [truncated]`;
@@ -35442,7 +35514,7 @@ var init_errors3 = __esm({
35442
35514
  // webhook signing secret (Stripe-style)
35443
35515
  ].map((p) => `\\b${p}`).join("|"), "g");
35444
35516
  GOOGLE_OAUTH_TOKEN_RE = /(?<![A-Za-z0-9+/])(?:ya29\.|1\/\/)[A-Za-z0-9._-]{8,}/g;
35445
- QUERY_SECRET_RE = new RegExp(`([?&](?:(?:access|refresh|id|auth|session|csrf|xsrf)[_-]?token|client[_-]?secret|api[_-]?secret|api[_-]?key|password|passwd|signature|token|key|sig|(?:code[_-]?)?verifier|(?:php|j)?sess(?:ion)?[_-]?id|sid|x[-_]${HEADER_NAME_RUN}?(?:api[-_]?key|token|secret|auth)${HEADER_NAME_RUN})=)[^&#\\s"'<>\`]+`, "gi");
35517
+ QUERY_SECRET_RE = new RegExp(`([?&#;](?:(?:access|refresh|id|auth|session|csrf|xsrf|api)[_-]?token|client[_-]?secret|api[_-]?secret|api[_-]?key|password|passwd|signature|secret|token|auth|key|sig|(?:code[_-]?)?verifier|(?:php|j)?sess(?:ion)?[_-]?id|sid|x[-_]${HEADER_NAME_RUN}?(?:api[-_]?key|token|secret|auth)${HEADER_NAME_RUN})=)[^&#\\s"'<>\`]+`, "gi");
35446
35518
  OAUTH_CODE_RE = /([?&]code=)(?=[^&#\s"'<>`]{16,})[^&#\s"'<>`]+/gi;
35447
35519
  FORM_PASSWORD_RE = /((?:^|[\s,;:"'(\[{])(?:password|passwd)=)[^&#\s"'<>`]+/gim;
35448
35520
  HEADER_SECRET_RE = new RegExp(`(\\b(?:x[-_]${HEADER_NAME_RUN}?(?:api[-_]?key|token|secret|auth)${HEADER_NAME_RUN}|api[-_]?key)\\s*:\\s*)[^\\s,;"'<>\`]+`, "gi");
@@ -35453,6 +35525,8 @@ var init_errors3 = __esm({
35453
35525
  "api[_-]?secret",
35454
35526
  "(?:x[_-])?api[_-]?key",
35455
35527
  "private[_-]?key",
35528
+ "aws[_-]?secret[_-]?access[_-]?key",
35529
+ // fleet-audit#1297
35456
35530
  "code[_-]?verifier",
35457
35531
  // PKCE; a bare `verifier` key is too generic for JSON
35458
35532
  `x[_-]${HEADER_NAME_RUN}?(?:api[_-]?key|token|secret|auth)${HEADER_NAME_RUN}`,
@@ -35482,15 +35556,6 @@ var init_zod = __esm({
35482
35556
  }
35483
35557
  });
35484
35558
 
35485
- // node_modules/@chrischall/mcp-utils/dist/response/view.js
35486
- function minifiedResult(data) {
35487
- return { content: [{ type: "text", text: JSON.stringify(data) }] };
35488
- }
35489
- var init_view = __esm({
35490
- "node_modules/@chrischall/mcp-utils/dist/response/view.js"() {
35491
- }
35492
- });
35493
-
35494
35559
  // node_modules/@chrischall/mcp-utils/dist/response/media.js
35495
35560
  var MEDIA_NOUN, MEDIA_QUALIFIER, MEDIA_KEY;
35496
35561
  var init_media = __esm({
@@ -35501,6 +35566,16 @@ var init_media = __esm({
35501
35566
  }
35502
35567
  });
35503
35568
 
35569
+ // node_modules/@chrischall/mcp-utils/dist/response/view.js
35570
+ function minifiedResult(data) {
35571
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
35572
+ }
35573
+ var init_view = __esm({
35574
+ "node_modules/@chrischall/mcp-utils/dist/response/view.js"() {
35575
+ init_media();
35576
+ }
35577
+ });
35578
+
35504
35579
  // node_modules/@chrischall/mcp-utils/dist/response/untrusted.js
35505
35580
  function isPlainObject3(value) {
35506
35581
  if (value === null || typeof value !== "object" || Array.isArray(value))
@@ -36552,12 +36627,24 @@ var init_fs = __esm({
36552
36627
  });
36553
36628
 
36554
36629
  // node_modules/@chrischall/mcp-utils/dist/internal/headers.js
36630
+ function responseHeader(res, name) {
36631
+ return getHeader(res?.headers, name);
36632
+ }
36633
+ function getHeader(headers, name) {
36634
+ if (!headers || typeof headers.get !== "function")
36635
+ return null;
36636
+ const value = headers.get.call(headers, name);
36637
+ return typeof value === "string" ? value : null;
36638
+ }
36555
36639
  var init_headers = __esm({
36556
36640
  "node_modules/@chrischall/mcp-utils/dist/internal/headers.js"() {
36557
36641
  }
36558
36642
  });
36559
36643
 
36560
36644
  // node_modules/@chrischall/mcp-utils/dist/internal/ascii.js
36645
+ function asciiLower(s) {
36646
+ return s.replace(/[A-Z]+/g, (m) => m.toLowerCase());
36647
+ }
36561
36648
  var init_ascii = __esm({
36562
36649
  "node_modules/@chrischall/mcp-utils/dist/internal/ascii.js"() {
36563
36650
  }
@@ -36569,16 +36656,42 @@ var init_code_point = __esm({
36569
36656
  }
36570
36657
  });
36571
36658
 
36659
+ // node_modules/@chrischall/mcp-utils/dist/internal/tags.js
36660
+ var init_tags = __esm({
36661
+ "node_modules/@chrischall/mcp-utils/dist/internal/tags.js"() {
36662
+ }
36663
+ });
36664
+
36572
36665
  // node_modules/@chrischall/mcp-utils/dist/scrape/index.js
36573
36666
  function isCloudflareChallenge(html) {
36574
- return /_cf_chl_opt/.test(html) || /<title[^>]*>\s*Just a moment/i.test(html);
36667
+ return html.includes("_cf_chl_opt") || hasJustAMomentTitle(html);
36668
+ }
36669
+ function hasJustAMomentTitle(html) {
36670
+ const lower = asciiLower(html);
36671
+ let i = 0;
36672
+ for (; ; ) {
36673
+ const open2 = lower.indexOf("<title", i);
36674
+ if (open2 < 0)
36675
+ return false;
36676
+ const gt = lower.indexOf(">", open2 + 6);
36677
+ if (gt < 0)
36678
+ return false;
36679
+ let j = gt + 1;
36680
+ while (j < lower.length && /\s/.test(lower[j]))
36681
+ j++;
36682
+ if (lower.startsWith(JUST_A_MOMENT, j))
36683
+ return true;
36684
+ i = gt + 1;
36685
+ }
36575
36686
  }
36576
- var NEXT_DATA_MAX_CHARS;
36687
+ var NEXT_DATA_MAX_CHARS, JUST_A_MOMENT;
36577
36688
  var init_scrape = __esm({
36578
36689
  "node_modules/@chrischall/mcp-utils/dist/scrape/index.js"() {
36579
36690
  init_ascii();
36580
36691
  init_code_point();
36692
+ init_tags();
36581
36693
  NEXT_DATA_MAX_CHARS = 16 * 1024 * 1024;
36694
+ JUST_A_MOMENT = "just a moment";
36582
36695
  }
36583
36696
  });
36584
36697
 
@@ -36604,7 +36717,7 @@ var init_net_atoms = __esm({
36604
36717
  // node_modules/@chrischall/mcp-utils/dist/http/body-limit.js
36605
36718
  async function readBytesCapped(res, maxBytes, service, bounded) {
36606
36719
  if (maxBytes !== void 0) {
36607
- const declared = Number(res.headers.get("content-length") ?? NaN);
36720
+ const declared = Number(responseHeader(res, "content-length") ?? NaN);
36608
36721
  if (Number.isFinite(declared) && declared > maxBytes) {
36609
36722
  cancelStream(res.body);
36610
36723
  throw new ResponseTooLargeError(service, maxBytes);
@@ -36649,6 +36762,7 @@ var ResponseTooLargeError;
36649
36762
  var init_body_limit = __esm({
36650
36763
  "node_modules/@chrischall/mcp-utils/dist/http/body-limit.js"() {
36651
36764
  init_errors3();
36765
+ init_headers();
36652
36766
  ResponseTooLargeError = class extends McpToolError {
36653
36767
  maxBytes;
36654
36768
  constructor(service, maxBytes) {
@@ -36761,6 +36875,126 @@ var init_url_safety = __esm({
36761
36875
  }
36762
36876
  });
36763
36877
 
36878
+ // node_modules/@chrischall/mcp-utils/dist/http/transport-failure.js
36879
+ function codeOf(e) {
36880
+ if (e === null || typeof e !== "object")
36881
+ return void 0;
36882
+ const code2 = e.code;
36883
+ return typeof code2 === "string" && code2 !== "" ? code2 : void 0;
36884
+ }
36885
+ function causes(err) {
36886
+ const out = [];
36887
+ let at = err;
36888
+ for (let depth = 0; depth < MAX_CAUSE_DEPTH && at !== void 0 && at !== null; depth++) {
36889
+ out.push(at);
36890
+ if (at instanceof AggregateError)
36891
+ out.push(...at.errors);
36892
+ at = at.cause;
36893
+ }
36894
+ return out;
36895
+ }
36896
+ function transportCauseCode(err) {
36897
+ for (const e of causes(err)) {
36898
+ const code2 = codeOf(e);
36899
+ if (code2 !== void 0)
36900
+ return code2;
36901
+ }
36902
+ return void 0;
36903
+ }
36904
+ function causeMessage(err) {
36905
+ const chain = causes(err).slice(1);
36906
+ for (let i = chain.length - 1; i >= 0; i--) {
36907
+ const e = chain[i];
36908
+ if (e instanceof Error && e.message !== "")
36909
+ return e.message;
36910
+ }
36911
+ return void 0;
36912
+ }
36913
+ function isFetchFailedError(err) {
36914
+ return err instanceof TypeError && err.message === "fetch failed";
36915
+ }
36916
+ function proxyRefusalStatus(err) {
36917
+ for (const e of causes(err)) {
36918
+ if (codeOf(e) === "ERR_PROXY_TUNNEL") {
36919
+ const m = /\b(\d{3})\b/.exec(e instanceof Error ? e.message.slice(0, 500) : "");
36920
+ return m ? Number(m[1]) : "unknown";
36921
+ }
36922
+ if (e instanceof Error) {
36923
+ const m = /^Proxy response \((\d{3})\) !== 200 when HTTP Tunneling/.exec(e.message);
36924
+ if (m)
36925
+ return Number(m[1]);
36926
+ }
36927
+ }
36928
+ return void 0;
36929
+ }
36930
+ function classify(err, code2) {
36931
+ const refused = proxyRefusalStatus(err);
36932
+ if (refused !== void 0) {
36933
+ return { cls: refused === 403 || refused === 407 || refused === "unknown" ? "egress" : "proxy", proxyStatus: refused };
36934
+ }
36935
+ if (code2 !== void 0 && DNS_CODES.has(code2))
36936
+ return { cls: "dns" };
36937
+ if (code2 !== void 0 && CERT_CODES.has(code2))
36938
+ return { cls: "tls" };
36939
+ if (code2 !== void 0 && CONNECT_CODES.has(code2))
36940
+ return { cls: "connect" };
36941
+ return { cls: "other" };
36942
+ }
36943
+ function describeTransportFailure(err, url2, service, opts = {}) {
36944
+ if (!isFetchFailedError(err))
36945
+ return void 0;
36946
+ let host;
36947
+ try {
36948
+ host = new URL(url2).hostname;
36949
+ } catch {
36950
+ host = "(unknown host)";
36951
+ }
36952
+ const code2 = transportCauseCode(err);
36953
+ const detail = [code2, causeMessage(err)].filter((s) => s !== void 0);
36954
+ const why = detail.length > 0 ? ` (${[...new Set(detail)].join(": ")})` : "";
36955
+ const { cls, proxyStatus } = classify(err, code2);
36956
+ const ctx = { host, service, code: code2, ...proxyStatus !== void 0 ? { proxyStatus } : {} };
36957
+ const hint = (opts.hints?.[cls] ?? DEFAULT_HINTS[cls])(host, ctx);
36958
+ return new McpToolError(`Could not reach ${service} at ${host}${why}.`, { kind: "transport", hint, cause: err });
36959
+ }
36960
+ var MAX_CAUSE_DEPTH, DNS_CODES, CONNECT_CODES, CERT_CODES, DEFAULT_HINTS;
36961
+ var init_transport_failure = __esm({
36962
+ "node_modules/@chrischall/mcp-utils/dist/http/transport-failure.js"() {
36963
+ init_errors3();
36964
+ MAX_CAUSE_DEPTH = 5;
36965
+ DNS_CODES = /* @__PURE__ */ new Set(["ENOTFOUND", "EAI_AGAIN", "EAI_FAIL", "EAI_NONAME"]);
36966
+ CONNECT_CODES = /* @__PURE__ */ new Set([
36967
+ "ECONNREFUSED",
36968
+ "ECONNRESET",
36969
+ "ETIMEDOUT",
36970
+ "ENETUNREACH",
36971
+ "EHOSTUNREACH",
36972
+ "EPIPE",
36973
+ "UND_ERR_CONNECT_TIMEOUT",
36974
+ "UND_ERR_SOCKET",
36975
+ "UND_ERR_HEADERS_TIMEOUT"
36976
+ ]);
36977
+ CERT_CODES = /* @__PURE__ */ new Set([
36978
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
36979
+ "UNABLE_TO_GET_ISSUER_CERT",
36980
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
36981
+ "SELF_SIGNED_CERT_IN_CHAIN",
36982
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
36983
+ "CERT_HAS_EXPIRED",
36984
+ "CERT_NOT_YET_VALID",
36985
+ "ERR_TLS_CERT_ALTNAME_INVALID"
36986
+ ]);
36987
+ DEFAULT_HINTS = {
36988
+ egress: (host) => `The outbound proxy this server runs behind refused the connection to ${host}: its egress policy does not allow that host. On a hosted (mcp-host) registration, the host must be on the registration's egress allow-list \u2014 the owner accepts the manifest's egress proposal (or adds the host) on the registration, then retries. Elsewhere, ask whoever runs the proxy to allow it.`,
36989
+ proxy: (host, ctx) => `The outbound proxy this server runs behind could not open a connection to ${host} (it answered ${String(ctx.proxyStatus)}). Retry; if it persists, check the proxy can reach the host.`,
36990
+ dns: (host) => `This machine could not resolve ${host}. Check DNS and VPN: a split-tunnel VPN that resolves some of a service's hosts but not others fails exactly like this. \`nslookup ${host}\` on the machine running this server tells you which.`,
36991
+ tls: (host) => `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.`,
36992
+ connect: (host, ctx) => `The connection to ${host} was refused, reset or timed out before ${ctx.service} 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.`,
36993
+ other: (host) => `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.`
36994
+ };
36995
+ }
36996
+ });
36997
+
36764
36998
  // node_modules/@chrischall/mcp-utils/dist/internal/retry-after.js
36765
36999
  var init_retry_after = __esm({
36766
37000
  "node_modules/@chrischall/mcp-utils/dist/internal/retry-after.js"() {
@@ -36768,6 +37002,27 @@ var init_retry_after = __esm({
36768
37002
  });
36769
37003
 
36770
37004
  // node_modules/@chrischall/mcp-utils/dist/http/index.js
37005
+ function writeOutcomeStatus(err) {
37006
+ const status = err.cause?.status;
37007
+ return typeof status === "number" ? status : void 0;
37008
+ }
37009
+ function unknownOutcomeReason(err, opts = {}) {
37010
+ if (err.timedOut)
37011
+ return "it did not answer in time";
37012
+ const status = writeOutcomeStatus(err);
37013
+ if (status !== void 0)
37014
+ return `it answered HTTP ${status} after ${opts.sent ?? "the request"} was sent`;
37015
+ return "the connection dropped";
37016
+ }
37017
+ async function writeOrUnknown(run, onUnknown) {
37018
+ try {
37019
+ return { ok: true, value: await run() };
37020
+ } catch (err) {
37021
+ if (!(err instanceof WriteOutcomeUnknownError))
37022
+ throw err;
37023
+ return { ok: false, result: await onUnknown(err, unknownOutcomeReason(err)) };
37024
+ }
37025
+ }
36771
37026
  function headerOf(headers, name) {
36772
37027
  if (headers === void 0)
36773
37028
  return void 0;
@@ -36838,6 +37093,7 @@ var init_http = __esm({
36838
37093
  init_net_atoms();
36839
37094
  init_fetch_bounded();
36840
37095
  init_url_safety();
37096
+ init_transport_failure();
36841
37097
  init_body_limit();
36842
37098
  init_net_atoms();
36843
37099
  init_url_safety();
@@ -37080,7 +37336,7 @@ var init_version = __esm({
37080
37336
  "src/version.ts"() {
37081
37337
  "use strict";
37082
37338
  PACKAGE_NAME = "microsoft-teams-mcp";
37083
- VERSION = "0.6.0";
37339
+ VERSION = "0.6.2";
37084
37340
  }
37085
37341
  });
37086
37342
 
@@ -37635,6 +37891,21 @@ var init_public_suffix = __esm({
37635
37891
  }
37636
37892
  });
37637
37893
 
37894
+ // node_modules/@fetchproxy/protocol/dist/ip-literal.js
37895
+ function isIpLiteralHost(host) {
37896
+ if (host.includes(":") || host.startsWith("["))
37897
+ return true;
37898
+ const labels = host.split(".");
37899
+ if (labels.length > 1 && labels[labels.length - 1] === "")
37900
+ labels.pop();
37901
+ const last = labels[labels.length - 1] ?? "";
37902
+ return /^[0-9]+$/.test(last) || /^0x[0-9a-f]*$/i.test(last);
37903
+ }
37904
+ var init_ip_literal = __esm({
37905
+ "node_modules/@fetchproxy/protocol/dist/ip-literal.js"() {
37906
+ }
37907
+ });
37908
+
37638
37909
  // node_modules/@fetchproxy/protocol/dist/validate.js
37639
37910
  function assertObject(x, label) {
37640
37911
  if (typeof x !== "object" || x === null || Array.isArray(x)) {
@@ -38084,6 +38355,9 @@ function validateHello(raw) {
38084
38355
  if (!HOSTNAME_RE.test(d)) {
38085
38356
  throw new ProtocolError3(`hello.domains: invalid hostname ${JSON.stringify(d)}`);
38086
38357
  }
38358
+ if (isIpLiteralHost(d)) {
38359
+ throw new ProtocolError3(`hello.domains: ${JSON.stringify(d)} is an IP address \u2014 declare the site's DNS hostname; IP-literal origins (LAN, loopback, link-local) are not reachable through the bridge`);
38360
+ }
38087
38361
  if (isPublicSuffix(d)) {
38088
38362
  throw new ProtocolError3(`hello.domains: ${JSON.stringify(d)} is a public suffix \u2014 declare a registrable domain (e.g. "example.${d}"), not the suffix every site under it shares`);
38089
38363
  }
@@ -38857,6 +39131,7 @@ var init_validate = __esm({
38857
39131
  init_account_attest();
38858
39132
  init_json_pointer();
38859
39133
  init_public_suffix();
39134
+ init_ip_literal();
38860
39135
  ProtocolError3 = class extends Error {
38861
39136
  constructor(message) {
38862
39137
  super(message);
@@ -39036,6 +39311,7 @@ var init_dist3 = __esm({
39036
39311
  init_seal();
39037
39312
  init_encoding();
39038
39313
  init_public_suffix();
39314
+ init_ip_literal();
39039
39315
  init_json_pointer();
39040
39316
  }
39041
39317
  });
@@ -44006,7 +44282,7 @@ async function startHost(opts) {
44006
44282
  if (ownRetryableRefusal)
44007
44283
  resetSessionPromise();
44008
44284
  resolveOwnSession(ownSession);
44009
- } else {
44285
+ } else if (identified === "extension" && extensionWs === ws) {
44010
44286
  const slot = peers.get(frame.mcpId);
44011
44287
  if (slot)
44012
44288
  slot.ws.send(JSON.stringify(frame));
@@ -45094,6 +45370,9 @@ var init_ws_server = __esm({
45094
45370
  throw new Error("FetchproxyServer: opts.domains must be a non-empty array of hostnames");
45095
45371
  }
45096
45372
  for (const d of opts.domains) {
45373
+ if (typeof d === "string" && isIpLiteralHost(d)) {
45374
+ throw new Error(`FetchproxyServer: opts.domains entry ${JSON.stringify(d)} is an IP address \u2014 declare the site's DNS hostname; IP-literal origins (LAN, loopback, link-local) are not reachable through the bridge`);
45375
+ }
45097
45376
  if (typeof d === "string" && isPublicSuffix(d)) {
45098
45377
  throw new Error(`FetchproxyServer: opts.domains entry ${JSON.stringify(d)} is a public suffix \u2014 declare a registrable domain (e.g. "example.${d}"), not the suffix every site under it shares`);
45099
45378
  }
@@ -47039,8 +47318,10 @@ var init_bulk = __esm({
47039
47318
  });
47040
47319
 
47041
47320
  // node_modules/@fetchproxy/server/dist/bot-wall.js
47321
+ var CLOUDFLARE_TITLE_SCAN_MAX;
47042
47322
  var init_bot_wall = __esm({
47043
47323
  "node_modules/@fetchproxy/server/dist/bot-wall.js"() {
47324
+ CLOUDFLARE_TITLE_SCAN_MAX = 64 * 1024;
47044
47325
  }
47045
47326
  });
47046
47327
 
@@ -47387,6 +47668,71 @@ function createBootstrapOpts(args) {
47387
47668
  ...nonEmpty2(b.domSelectors) ? { domSelectors: b.domSelectors } : {}
47388
47669
  };
47389
47670
  }
47671
+ function stripBearer(raw) {
47672
+ const m = /^\s*Bearer\s+(.+)$/i.exec(raw);
47673
+ return (m?.[1] ?? raw).trim();
47674
+ }
47675
+ async function raceCaptures(attempts, windowMs) {
47676
+ for (const a of attempts)
47677
+ a.catch(() => {
47678
+ });
47679
+ let timer;
47680
+ const expiry = new Promise((_resolve, reject) => {
47681
+ timer = setTimeout(() => reject(new Error(`timed out after ${Math.round(windowMs / 1e3)}s waiting for the page to make a request we could read`)), windowMs);
47682
+ });
47683
+ try {
47684
+ return await Promise.race([
47685
+ Promise.any(attempts).catch((e) => {
47686
+ throw new Error(e instanceof AggregateError ? e.errors.map((x) => messageOf(x)).join("; ") : messageOf(e));
47687
+ }),
47688
+ expiry
47689
+ ]);
47690
+ } finally {
47691
+ clearTimeout(timer);
47692
+ }
47693
+ }
47694
+ async function captureBearerHeader(opts) {
47695
+ if (opts.captures.length === 0)
47696
+ throw new Error("captureBearerHeader: at least one capture declaration is required.");
47697
+ const minLength = opts.minLength ?? 100;
47698
+ const normalise = opts.normalise ?? stripBearer;
47699
+ const domains = opts.domains ?? [...new Set(opts.captures.map((c) => c.host))];
47700
+ const build2 = opts.createTransport ?? ((o) => createFetchproxyTransport(o));
47701
+ const transport = build2({
47702
+ ...opts.transportOptions,
47703
+ ...createBootstrapOpts({ domains: [...domains], bootstrap: { captureHeaders: opts.captures.map((c) => ({ ...c })) } }),
47704
+ ...opts.port !== void 0 ? { port: opts.port } : {},
47705
+ // Both: the explicit deadline for every bridge version, and the declared
47706
+ // window so the transport's own derivation agrees with it.
47707
+ fetchTimeoutMs: deadlineForCaptureWindow(void 0, opts.windowMs) ?? SERVER_DEFAULT_FETCH_TIMEOUT_MS,
47708
+ captureWindowMs: opts.windowMs,
47709
+ serverName: opts.serverName,
47710
+ version: opts.version
47711
+ });
47712
+ const one = async (decl) => {
47713
+ const raw = await transport.server.captureRequestHeader({ ...decl, timeoutMs: opts.windowMs });
47714
+ if (typeof raw !== "string")
47715
+ throw new Error(`${decl.host}: capture returned no header`);
47716
+ const token = normalise(raw);
47717
+ if (token.length < minLength) {
47718
+ throw new Error(`${decl.host}: ${decl.headerName} header was present but too short to be a token (${token.length} chars)`);
47719
+ }
47720
+ return token;
47721
+ };
47722
+ try {
47723
+ await transport.start();
47724
+ try {
47725
+ return opts.captures.length === 1 ? await one(opts.captures[0]) : await raceCaptures(opts.captures.map(one), opts.windowMs);
47726
+ } catch (e) {
47727
+ throw new Error(`could not capture ${opts.what} from the browser (${messageOf(e)}). ${opts.guidance}`);
47728
+ }
47729
+ } finally {
47730
+ try {
47731
+ await transport.close();
47732
+ } catch {
47733
+ }
47734
+ }
47735
+ }
47390
47736
  var PLACEHOLDER_RE2, SERVER_DEFAULT_FETCH_TIMEOUT_MS, CAPTURE_DEADLINE_MARGIN_MS;
47391
47737
  var init_fetchproxy = __esm({
47392
47738
  "node_modules/@chrischall/mcp-utils/dist/fetchproxy/index.js"() {
@@ -47407,17 +47753,12 @@ function captureWindowMs(env = process.env) {
47407
47753
  const ms = readTtlMsEnv("TEAMS_CAPTURE_TIMEOUT", DEFAULT_CAPTURE_WINDOW_MS, { env });
47408
47754
  return ms > 0 ? ms : DEFAULT_CAPTURE_WINDOW_MS;
47409
47755
  }
47410
- function bridgeDeadlineMs(windowMs) {
47411
- return Math.max(windowMs + DEADLINE_MARGIN_MS, MIN_DEADLINE_MS);
47412
- }
47413
- var DEFAULT_CAPTURE_WINDOW_MS, DEADLINE_MARGIN_MS, MIN_DEADLINE_MS;
47756
+ var DEFAULT_CAPTURE_WINDOW_MS;
47414
47757
  var init_capture_window = __esm({
47415
47758
  "src/capture-window.ts"() {
47416
47759
  "use strict";
47417
47760
  init_dist2();
47418
47761
  DEFAULT_CAPTURE_WINDOW_MS = 3e4;
47419
- DEADLINE_MARGIN_MS = 15e3;
47420
- MIN_DEADLINE_MS = 3e4;
47421
47762
  }
47422
47763
  });
47423
47764
 
@@ -47427,67 +47768,28 @@ __export(auth_fetchproxy_exports, {
47427
47768
  CAPTURE_DECL: () => CAPTURE_DECL,
47428
47769
  TRUST_DOMAINS: () => TRUST_DOMAINS,
47429
47770
  captureTokenViaFetchproxy: () => captureTokenViaFetchproxy,
47771
+ createCaptureTransport: () => createCaptureTransport,
47430
47772
  getWsPort: () => getWsPort,
47431
47773
  stripBearer: () => stripBearer
47432
47774
  });
47433
47775
  function getWsPort() {
47434
47776
  return readPortEnv("TEAMS_WS_PORT", DEFAULT_WS_PORT);
47435
47777
  }
47436
- function stripBearer(raw) {
47437
- const m = /^\s*Bearer\s+(.+)$/i.exec(raw);
47438
- return (m ? m[1] : raw).trim();
47439
- }
47440
47778
  async function captureTokenViaFetchproxy(env = process.env) {
47441
- const windowMs = captureWindowMs(env);
47442
- const transport = createFetchproxyTransport({
47443
- // `createBootstrapOpts` derives the capability set from the declarations:
47444
- // `capture_request_header`, the only verb this MCP uses, beside the `fetch`
47445
- // base verb mcp-utils always keeps (the field replaces the server default).
47446
- // This is the same set as before the Activity feed left the page, so an
47447
- // existing pairing needs no re-approval.
47448
- ...createBootstrapOpts({
47449
- domains: [...TRUST_DOMAINS],
47450
- bootstrap: { captureHeaders: [{ ...CAPTURE_DECL }] }
47451
- }),
47779
+ return captureBearerHeader({
47780
+ captures: [CAPTURE_DECL],
47781
+ domains: TRUST_DOMAINS,
47782
+ // Read per capture, not at import: see `capture-window.ts`.
47783
+ windowMs: captureWindowMs(env),
47452
47784
  port: getWsPort(),
47453
- // Both: the explicit deadline for every bridge version, and the declared
47454
- // window so mcp-utils' own derivation agrees with it.
47455
- fetchTimeoutMs: bridgeDeadlineMs(windowMs),
47456
- captureWindowMs: windowMs,
47457
47785
  serverName: PACKAGE_NAME,
47458
- version: VERSION
47786
+ version: VERSION,
47787
+ what: "a Teams token",
47788
+ guidance: "Open a signed-in teams.cloud.microsoft tab and click into any chat \u2014 that is what makes the page call the chat service; an idle tab never does \u2014 then retry.",
47789
+ createTransport: createCaptureTransport
47459
47790
  });
47460
- try {
47461
- await transport.start();
47462
- try {
47463
- const raw = await transport.server.captureRequestHeader({
47464
- ...CAPTURE_DECL,
47465
- timeoutMs: windowMs
47466
- });
47467
- if (typeof raw !== "string") {
47468
- throw new Error(`${CAPTURE_DECL.host}: capture returned no header`);
47469
- }
47470
- const token = stripBearer(raw);
47471
- if (token.length < MIN_TOKEN_LENGTH) {
47472
- throw new Error(
47473
- `${CAPTURE_DECL.host}: authorization header was present but too short to be a token (${token.length} chars)`
47474
- );
47475
- }
47476
- return token;
47477
- } catch (e) {
47478
- const detail = e.message;
47479
- throw new Error(
47480
- `could not capture a Teams token from the browser (${detail}). Open a signed-in teams.cloud.microsoft tab and click into any chat \u2014 that is what makes the page call the chat service; an idle tab never does \u2014 then retry.`
47481
- );
47482
- }
47483
- } finally {
47484
- try {
47485
- await transport.close();
47486
- } catch {
47487
- }
47488
- }
47489
47791
  }
47490
- var DEFAULT_WS_PORT, CAPTURE_DECL, TRUST_DOMAINS, MIN_TOKEN_LENGTH;
47792
+ var DEFAULT_WS_PORT, CAPTURE_DECL, TRUST_DOMAINS, createCaptureTransport;
47491
47793
  var init_auth_fetchproxy = __esm({
47492
47794
  "src/auth-fetchproxy.ts"() {
47493
47795
  "use strict";
@@ -47495,6 +47797,7 @@ var init_auth_fetchproxy = __esm({
47495
47797
  init_dist2();
47496
47798
  init_capture_window();
47497
47799
  init_version();
47800
+ init_fetchproxy();
47498
47801
  DEFAULT_WS_PORT = 37149;
47499
47802
  CAPTURE_DECL = {
47500
47803
  host: "teams.cloud.microsoft",
@@ -47502,7 +47805,7 @@ var init_auth_fetchproxy = __esm({
47502
47805
  headerName: "authorization"
47503
47806
  };
47504
47807
  TRUST_DOMAINS = [CAPTURE_DECL.host];
47505
- MIN_TOKEN_LENGTH = 100;
47808
+ createCaptureTransport = (opts) => createFetchproxyTransport(opts);
47506
47809
  }
47507
47810
  });
47508
47811
 
@@ -47529,56 +47832,26 @@ async function captureSharePointTokenViaFetchproxy(host, env = process.env) {
47529
47832
  `refusing to capture a SharePoint token for ${JSON.stringify(host)}: not a *.sharepoint.com host`
47530
47833
  );
47531
47834
  }
47532
- const captureDecl = { host, path: "/*", headerName: "authorization" };
47533
- const windowMs = captureWindowMs(env);
47534
- const transport = createFetchproxyTransport({
47535
- // `createBootstrapOpts` derives the capability set from the declarations:
47536
- // `capture_request_header` beside mcp-utils' always-on `fetch` base verb.
47537
- // Same verb set as the chatsvc capture, so an existing pairing that already
47538
- // trusts `sharepoint.com` needs no re-approval.
47539
- ...createBootstrapOpts({
47540
- domains: [...SHAREPOINT_TRUST_DOMAINS],
47541
- bootstrap: { captureHeaders: [{ ...captureDecl }] }
47542
- }),
47835
+ return captureBearerHeader({
47836
+ // The one request we capture from: any call the browser makes to this
47837
+ // OneDrive host (the caller resolves it from the file's host via
47838
+ // `captureHostFor`). A concrete host, never a wildcard — see the module note.
47839
+ captures: [{ host, path: "/*", headerName: "authorization" }],
47840
+ // The broad family domain as the trust scope. Same verb set as the chatsvc
47841
+ // capture, so an existing pairing that already trusts `sharepoint.com`
47842
+ // needs no re-approval.
47843
+ domains: SHAREPOINT_TRUST_DOMAINS,
47844
+ // Read per capture, not at import: see `capture-window.ts`.
47845
+ windowMs: captureWindowMs(env),
47543
47846
  port: getWsPort(),
47544
- // Both: the explicit deadline for every bridge version, and the declared
47545
- // window so mcp-utils' own derivation agrees with it.
47546
- fetchTimeoutMs: bridgeDeadlineMs(windowMs),
47547
- captureWindowMs: windowMs,
47548
47847
  serverName: PACKAGE_NAME,
47549
- version: VERSION
47848
+ version: VERSION,
47849
+ what: `a SharePoint token for ${host}`,
47850
+ guidance: `Click around Teams or open one of your own OneDrive files \u2014 that makes the browser request ${host}, which is where the SharePoint token is captured from \u2014 then retry.`,
47851
+ createTransport: createCaptureTransport
47550
47852
  });
47551
- try {
47552
- await transport.start();
47553
- try {
47554
- const raw = await transport.server.captureRequestHeader({
47555
- ...captureDecl,
47556
- timeoutMs: windowMs
47557
- });
47558
- if (typeof raw !== "string") {
47559
- throw new Error(`${host}: capture returned no header`);
47560
- }
47561
- const token = stripBearer(raw);
47562
- if (token.length < MIN_TOKEN_LENGTH2) {
47563
- throw new Error(
47564
- `${host}: authorization header was present but too short to be a token (${token.length} chars)`
47565
- );
47566
- }
47567
- return token;
47568
- } catch (e) {
47569
- const detail = e.message;
47570
- throw new Error(
47571
- `could not capture a SharePoint token for ${host} (${detail}). Click around Teams or open one of your own OneDrive files \u2014 that makes the browser request ${host}, which is where the SharePoint token is captured from \u2014 then retry.`
47572
- );
47573
- }
47574
- } finally {
47575
- try {
47576
- await transport.close();
47577
- } catch {
47578
- }
47579
- }
47580
47853
  }
47581
- var SHAREPOINT_TRUST_DOMAINS, MIN_TOKEN_LENGTH2;
47854
+ var SHAREPOINT_TRUST_DOMAINS;
47582
47855
  var init_sharepoint_auth = __esm({
47583
47856
  "src/sharepoint-auth.ts"() {
47584
47857
  "use strict";
@@ -47587,7 +47860,6 @@ var init_sharepoint_auth = __esm({
47587
47860
  init_auth_fetchproxy();
47588
47861
  init_version();
47589
47862
  SHAREPOINT_TRUST_DOMAINS = ["sharepoint.com"];
47590
- MIN_TOKEN_LENGTH2 = 100;
47591
47863
  }
47592
47864
  });
47593
47865
 
@@ -47599,48 +47871,22 @@ __export(substrate_auth_exports, {
47599
47871
  captureSubstrateTokenViaFetchproxy: () => captureSubstrateTokenViaFetchproxy
47600
47872
  });
47601
47873
  async function captureSubstrateTokenViaFetchproxy(env = process.env) {
47602
- const windowMs = captureWindowMs(env);
47603
- const transport = createFetchproxyTransport({
47874
+ return captureBearerHeader({
47604
47875
  // Same verb set as the other two captures (`capture_request_header` beside
47605
47876
  // the always-on `fetch`); only the trusted domain differs.
47606
- ...createBootstrapOpts({
47607
- domains: [...SUBSTRATE_TRUST_DOMAINS],
47608
- bootstrap: { captureHeaders: [{ ...SUBSTRATE_CAPTURE_DECL }] }
47609
- }),
47877
+ captures: [SUBSTRATE_CAPTURE_DECL],
47878
+ domains: SUBSTRATE_TRUST_DOMAINS,
47879
+ // Read per capture, not at import: see `capture-window.ts`.
47880
+ windowMs: captureWindowMs(env),
47610
47881
  port: getWsPort(),
47611
- fetchTimeoutMs: bridgeDeadlineMs(windowMs),
47612
- captureWindowMs: windowMs,
47613
47882
  serverName: PACKAGE_NAME,
47614
- version: VERSION
47883
+ version: VERSION,
47884
+ what: "a Substrate search token",
47885
+ guidance: '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.',
47886
+ createTransport: createCaptureTransport
47615
47887
  });
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
47888
  }
47643
- var SUBSTRATE_CAPTURE_DECL, SUBSTRATE_TRUST_DOMAINS, MIN_TOKEN_LENGTH3;
47889
+ var SUBSTRATE_CAPTURE_DECL, SUBSTRATE_TRUST_DOMAINS;
47644
47890
  var init_substrate_auth = __esm({
47645
47891
  "src/substrate-auth.ts"() {
47646
47892
  "use strict";
@@ -47654,7 +47900,6 @@ var init_substrate_auth = __esm({
47654
47900
  headerName: "authorization"
47655
47901
  };
47656
47902
  SUBSTRATE_TRUST_DOMAINS = [SUBSTRATE_CAPTURE_DECL.host];
47657
- MIN_TOKEN_LENGTH3 = 100;
47658
47903
  }
47659
47904
  });
47660
47905
 
@@ -48236,6 +48481,46 @@ var TokenManager = class {
48236
48481
  return res;
48237
48482
  }
48238
48483
  };
48484
+ var RECAPTURE_SENTINEL = "fetchproxy:recapture";
48485
+ var UNKNOWN_CAPTURED_TOKEN_TTL_MS = 10 * 60 * 1e3;
48486
+ function capturedBearerTokens(accessToken, opts = {}) {
48487
+ const now = opts.now ?? Date.now;
48488
+ let expiresAt;
48489
+ try {
48490
+ expiresAt = decodeJwtExp(accessToken) * 1e3;
48491
+ } catch {
48492
+ expiresAt = now() + (opts.unknownTtlMs ?? UNKNOWN_CAPTURED_TOKEN_TTL_MS);
48493
+ }
48494
+ return { accessToken, refreshToken: RECAPTURE_SENTINEL, expiresAt };
48495
+ }
48496
+ function createCapturedTokenManager(opts) {
48497
+ const { direct } = opts;
48498
+ const wrap = (token) => capturedBearerTokens(token, {
48499
+ ...opts.unknownTtlMs !== void 0 ? { unknownTtlMs: opts.unknownTtlMs } : {},
48500
+ ...opts.now !== void 0 ? { now: opts.now } : {}
48501
+ });
48502
+ const persistence = direct === void 0 ? opts.persistence ?? void 0 : void 0;
48503
+ return new TokenManager({
48504
+ initial: async () => wrap(direct ?? await opts.capture()),
48505
+ refresh: async () => {
48506
+ if (direct !== void 0) {
48507
+ throw opts.onDirectRejected ? opts.onDirectRejected() : new McpToolError("The directly supplied access token was rejected (401).", {
48508
+ status: 401,
48509
+ kind: "credential_rejected",
48510
+ hint: "A directly supplied token cannot be refreshed automatically. Replace it with a current one, or unset it to capture from a signed-in browser tab instead."
48511
+ });
48512
+ }
48513
+ return wrap(await opts.capture());
48514
+ },
48515
+ ...persistence !== void 0 ? { persistence } : {},
48516
+ // Never fatal: the token is in hand and re-capturable.
48517
+ onPersistError: (err) => {
48518
+ opts.onPersistError?.(err);
48519
+ },
48520
+ ...opts.skewMs !== void 0 ? { skewMs: opts.skewMs } : {},
48521
+ ...opts.now !== void 0 ? { now: opts.now } : {}
48522
+ });
48523
+ }
48239
48524
 
48240
48525
  // src/token-cache.ts
48241
48526
  init_dist2();
@@ -48247,11 +48532,6 @@ function tokenCachePath(env = process.env) {
48247
48532
  fileName: "token.json"
48248
48533
  });
48249
48534
  }
48250
- function isToken(raw) {
48251
- if (raw === null || typeof raw !== "object") return false;
48252
- const t = raw;
48253
- return typeof t.accessToken === "string" && t.accessToken !== "" && typeof t.expiresAt === "number" && (t.refreshToken === void 0 || typeof t.refreshToken === "string");
48254
- }
48255
48535
  function bindingFor(env) {
48256
48536
  if (readEnvVar("TEAMS_ACCESS_TOKEN", { env }) !== void 0) return null;
48257
48537
  if (parseBoolEnv("TEAMS_DISABLE_FETCHPROXY", { env })) return null;
@@ -48264,7 +48544,7 @@ function createTokenCache(env = process.env) {
48264
48544
  return createFileStatePersistence({
48265
48545
  filePath: tokenCachePath(env),
48266
48546
  boundTo,
48267
- validate: (raw) => isToken(raw) ? raw : null
48547
+ validate: (raw) => isBearerTokens(raw) ? raw : null
48268
48548
  });
48269
48549
  }
48270
48550
  function reportCacheWriteFailure(err) {
@@ -48683,90 +48963,15 @@ function hasRealTitle(s) {
48683
48963
 
48684
48964
  // src/network-error.ts
48685
48965
  init_dist2();
48686
- var MAX_CAUSE_DEPTH = 5;
48687
- var DNS_CODES = /* @__PURE__ */ new Set(["ENOTFOUND", "EAI_AGAIN", "EAI_FAIL", "EAI_NONAME"]);
48688
- var CONNECT_CODES = /* @__PURE__ */ new Set([
48689
- "ECONNREFUSED",
48690
- "ECONNRESET",
48691
- "ETIMEDOUT",
48692
- "ENETUNREACH",
48693
- "EHOSTUNREACH",
48694
- "EPIPE",
48695
- "UND_ERR_CONNECT_TIMEOUT",
48696
- "UND_ERR_SOCKET",
48697
- "UND_ERR_HEADERS_TIMEOUT"
48698
- ]);
48699
- var CERT_CODES = /* @__PURE__ */ new Set([
48700
- "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
48701
- "UNABLE_TO_GET_ISSUER_CERT",
48702
- "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
48703
- "SELF_SIGNED_CERT_IN_CHAIN",
48704
- "DEPTH_ZERO_SELF_SIGNED_CERT",
48705
- "CERT_HAS_EXPIRED",
48706
- "CERT_NOT_YET_VALID",
48707
- "ERR_TLS_CERT_ALTNAME_INVALID"
48708
- ]);
48709
- function codeOf(e) {
48710
- if (e === null || typeof e !== "object") return void 0;
48711
- const code2 = e.code;
48712
- return typeof code2 === "string" && code2 !== "" ? code2 : void 0;
48713
- }
48714
- function causes(err) {
48715
- const out = [];
48716
- let at = err;
48717
- for (let depth = 0; depth < MAX_CAUSE_DEPTH && at !== void 0 && at !== null; depth++) {
48718
- out.push(at);
48719
- if (at instanceof AggregateError) out.push(...at.errors);
48720
- at = at.cause;
48721
- }
48722
- return out;
48723
- }
48724
- function transportCauseCode(err) {
48725
- for (const e of causes(err)) {
48726
- const code2 = codeOf(e);
48727
- if (code2 !== void 0) return code2;
48728
- }
48729
- return void 0;
48730
- }
48731
- function causeMessage(err) {
48732
- const chain = causes(err).slice(1);
48733
- for (let i = chain.length - 1; i >= 0; i--) {
48734
- const e = chain[i];
48735
- if (e instanceof Error && e.message !== "") return e.message;
48736
- }
48737
- return void 0;
48738
- }
48739
- function isFetchFailed(err) {
48740
- return err instanceof TypeError && err.message === "fetch failed";
48741
- }
48742
- function hintFor(code2, host) {
48743
- if (code2 !== void 0 && DNS_CODES.has(code2)) {
48744
- 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.`;
48745
- }
48746
- if (code2 !== void 0 && CERT_CODES.has(code2)) {
48747
- 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.`;
48748
- }
48749
- if (code2 !== void 0 && CONNECT_CODES.has(code2)) {
48750
- 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.`;
48751
- }
48752
- 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.`;
48753
- }
48754
- function describeTransportFailure(err, url2, service) {
48755
- if (!isFetchFailed(err)) return void 0;
48756
- let host;
48757
- try {
48758
- host = new URL(url2).hostname;
48759
- } catch {
48760
- host = "(unknown host)";
48761
- }
48762
- const code2 = transportCauseCode(err);
48763
- const detail = [code2, causeMessage(err)].filter((s) => s !== void 0);
48764
- const why = detail.length > 0 ? ` (${[...new Set(detail)].join(": ")})` : "";
48765
- return new McpToolError(`Could not reach ${service} at ${host}${why}.`, {
48766
- kind: "transport",
48767
- hint: hintFor(code2, host),
48768
- cause: err
48769
- });
48966
+ init_dist2();
48967
+ var TEAMS_HINTS = {
48968
+ // Name the hosts a split-tunnel VPN actually fails on for Teams.
48969
+ dns: (host) => `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.`,
48970
+ // "before Teams answered", whichever Teams host (image store, gateway, SharePoint) it was.
48971
+ connect: (host) => `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.`
48972
+ };
48973
+ function describeTransportFailure2(err, url2, service) {
48974
+ return describeTransportFailure(err, url2, service, { hints: TEAMS_HINTS });
48770
48975
  }
48771
48976
 
48772
48977
  // src/chatsvc.ts
@@ -48781,8 +48986,6 @@ function chatServiceBase(env = process.env) {
48781
48986
  const region = readEnvVar("TEAMS_CHATSVC_REGION", { env }) ?? DEFAULT_REGION;
48782
48987
  return `https://teams.cloud.microsoft/api/chatsvc/${encodeURIComponent(region)}/v1`;
48783
48988
  }
48784
- var UNKNOWN_TOKEN_TTL_MS = 10 * 60 * 1e3;
48785
- var RECAPTURE_SENTINEL = "fetchproxy:recapture";
48786
48989
  var REQUEST_TIMEOUT_MS = 6e4;
48787
48990
  var MAX_CONVERSATION_PAGES = 10;
48788
48991
  var MAX_MESSAGE_PAGES = 20;
@@ -48809,19 +49012,6 @@ function outcomeUnknown(method, e, hint) {
48809
49012
  var SEND_OUTCOME_HINT = "The message may already have been posted \u2014 check the conversation (teams_read_conversation) before retrying; do not resend blindly.";
48810
49013
  var REACTION_OUTCOME_HINT = "The reaction change may already have been applied \u2014 check the message (teams_read_conversation) before retrying.";
48811
49014
  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.";
48812
- function outcomeUnknownStatus(e) {
48813
- const status = e.cause?.status;
48814
- return typeof status === "number" ? status : void 0;
48815
- }
48816
- function toBearerTokens(accessToken) {
48817
- let expiresAt;
48818
- try {
48819
- expiresAt = decodeJwtExp(accessToken) * 1e3;
48820
- } catch {
48821
- expiresAt = Date.now() + UNKNOWN_TOKEN_TTL_MS;
48822
- }
48823
- return { accessToken, refreshToken: RECAPTURE_SENTINEL, expiresAt };
48824
- }
48825
49015
  var ChatServiceClient = class {
48826
49016
  #baseUrl;
48827
49017
  /**
@@ -49096,39 +49286,12 @@ var ChatServiceClient = class {
49096
49286
  if (this.#configError) throw this.#configError;
49097
49287
  }
49098
49288
  #tokenManager() {
49099
- if (this.#tokens) return this.#tokens;
49100
- const direct = this.#direct;
49101
- const persistence = direct === void 0 ? createTokenCache(this.#env) : null;
49102
- const mint = async () => toBearerTokens(direct ?? await this.#capture());
49103
- this.#tokens = new TokenManager({
49104
- initial: mint,
49105
- // There is no refresh grant — re-capture instead. But a token supplied as
49106
- // TEAMS_ACCESS_TOKEN must NOT be "refreshed" from the browser: that would
49107
- // silently swap the operator's chosen credential for whichever account a
49108
- // tab is signed into.
49109
- refresh: async () => {
49110
- if (direct !== void 0) throw this.#directRejected();
49111
- return toBearerTokens(await this.#capture());
49112
- },
49113
- // A failed cache write must not fail the call that triggered it.
49114
- ...persistence ? {
49115
- persistence: {
49116
- load: () => persistence.load(),
49117
- save: (t) => {
49118
- try {
49119
- persistence.save(t);
49120
- } catch (e) {
49121
- reportCacheWriteFailure(e);
49122
- }
49123
- },
49124
- clear: () => {
49125
- try {
49126
- persistence.clear();
49127
- } catch {
49128
- }
49129
- }
49130
- }
49131
- } : {}
49289
+ this.#tokens ??= createCapturedTokenManager({
49290
+ capture: () => this.#capture(),
49291
+ direct: this.#direct,
49292
+ onDirectRejected: () => this.#directRejected(),
49293
+ persistence: this.#direct === void 0 ? createTokenCache(this.#env) : null,
49294
+ onPersistError: reportCacheWriteFailure
49132
49295
  });
49133
49296
  return this.#tokens;
49134
49297
  }
@@ -49171,7 +49334,7 @@ var ChatServiceClient = class {
49171
49334
  r = await fetchBounded(url2, init, opts);
49172
49335
  } catch (e) {
49173
49336
  if (write) throw outcomeUnknown(method, e, write.hint);
49174
- throw describeTransportFailure(e, url2, serviceFor(url2)) ?? e;
49337
+ throw describeTransportFailure2(e, url2, serviceFor(url2)) ?? e;
49175
49338
  }
49176
49339
  body = r.body;
49177
49340
  return r.res;
@@ -49278,16 +49441,11 @@ function sharePointTokenCachePath(env = process.env) {
49278
49441
  fileName: "sharepoint-tokens.json"
49279
49442
  });
49280
49443
  }
49281
- function isToken2(raw) {
49282
- if (raw === null || typeof raw !== "object") return false;
49283
- const t = raw;
49284
- return typeof t.accessToken === "string" && t.accessToken !== "" && typeof t.expiresAt === "number" && (t.refreshToken === void 0 || typeof t.refreshToken === "string");
49285
- }
49286
49444
  function validateMap(raw) {
49287
49445
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
49288
49446
  const out = {};
49289
49447
  for (const [host, value] of Object.entries(raw)) {
49290
- if (isToken2(value)) out[host] = value;
49448
+ if (isBearerTokens(value)) out[host] = value;
49291
49449
  }
49292
49450
  return out;
49293
49451
  }
@@ -49334,25 +49492,14 @@ async function captureSharePointTokenLazily(host) {
49334
49492
  const mod = await Promise.resolve().then(() => (init_sharepoint_auth(), sharepoint_auth_exports));
49335
49493
  return mod.captureSharePointTokenViaFetchproxy(host);
49336
49494
  }
49337
- var UNKNOWN_TOKEN_TTL_MS2 = 10 * 60 * 1e3;
49338
- var RECAPTURE_SENTINEL2 = "fetchproxy:recapture";
49339
49495
  var REQUEST_TIMEOUT_MS2 = 6e4;
49340
49496
  async function reachable(url2, run) {
49341
49497
  try {
49342
49498
  return await run();
49343
49499
  } catch (e) {
49344
- throw describeTransportFailure(e, url2, "SharePoint") ?? e;
49500
+ throw describeTransportFailure2(e, url2, "SharePoint") ?? e;
49345
49501
  }
49346
49502
  }
49347
- function toBearerTokens2(accessToken) {
49348
- let expiresAt;
49349
- try {
49350
- expiresAt = decodeJwtExp(accessToken) * 1e3;
49351
- } catch {
49352
- expiresAt = Date.now() + UNKNOWN_TOKEN_TTL_MS2;
49353
- }
49354
- return { accessToken, refreshToken: RECAPTURE_SENTINEL2, expiresAt };
49355
- }
49356
49503
  var SharePointClient = class {
49357
49504
  #env;
49358
49505
  #capture;
@@ -49435,12 +49582,9 @@ var SharePointClient = class {
49435
49582
  #managerFor(host) {
49436
49583
  const existing = this.#managers.get(host);
49437
49584
  if (existing) return existing;
49438
- const persistence = this.#cache?.forHost(host);
49439
- const mgr = new TokenManager({
49440
- initial: async () => toBearerTokens2(await this.#capture(host)),
49441
- // No refresh grant — re-capture instead.
49442
- refresh: async () => toBearerTokens2(await this.#capture(host)),
49443
- ...persistence ? { persistence } : {}
49585
+ const mgr = createCapturedTokenManager({
49586
+ capture: () => this.#capture(host),
49587
+ persistence: this.#cache?.forHost(host) ?? null
49444
49588
  });
49445
49589
  this.#managers.set(host, mgr);
49446
49590
  return mgr;
@@ -49568,18 +49712,13 @@ function substrateTokenCachePath(env = process.env) {
49568
49712
  fileName: "substrate-token.json"
49569
49713
  });
49570
49714
  }
49571
- function isToken3(raw) {
49572
- if (raw === null || typeof raw !== "object") return false;
49573
- const t = raw;
49574
- return typeof t.accessToken === "string" && t.accessToken !== "" && typeof t.expiresAt === "number" && (t.refreshToken === void 0 || typeof t.refreshToken === "string");
49575
- }
49576
49715
  function createSubstrateTokenCache(env = process.env) {
49577
49716
  if (!parseBoolEnv("TEAMS_TOKEN_CACHE", { env, default: true })) return null;
49578
49717
  if (parseBoolEnv("TEAMS_DISABLE_FETCHPROXY", { env })) return null;
49579
49718
  const file2 = createFileStatePersistence({
49580
49719
  filePath: substrateTokenCachePath(env),
49581
49720
  boundTo: "fetchproxy",
49582
- validate: (raw) => isToken3(raw) ? raw : null
49721
+ validate: (raw) => isBearerTokens(raw) ? raw : null
49583
49722
  });
49584
49723
  return {
49585
49724
  load: () => file2.load(),
@@ -49603,19 +49742,8 @@ function createSubstrateTokenCache(env = process.env) {
49603
49742
  // src/substrate.ts
49604
49743
  var SUBSTRATE_QUERY_URL = "https://substrate.office.com/searchservice/api/v2/query";
49605
49744
  var CAPTURE_RETRY_COOLDOWN_MS = 10 * 60 * 1e3;
49606
- var UNKNOWN_TOKEN_TTL_MS3 = 10 * 60 * 1e3;
49607
- var RECAPTURE_SENTINEL3 = "fetchproxy:recapture";
49608
49745
  var REQUEST_TIMEOUT_MS3 = 3e4;
49609
49746
  var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
49610
- function toBearerTokens3(accessToken) {
49611
- let expiresAt;
49612
- try {
49613
- expiresAt = decodeJwtExp(accessToken) * 1e3;
49614
- } catch {
49615
- expiresAt = Date.now() + UNKNOWN_TOKEN_TTL_MS3;
49616
- }
49617
- return { accessToken, refreshToken: RECAPTURE_SENTINEL3, expiresAt };
49618
- }
49619
49747
  async function captureSubstrateTokenLazily() {
49620
49748
  const mod = await Promise.resolve().then(() => (init_substrate_auth(), substrate_auth_exports));
49621
49749
  return mod.captureSubstrateTokenViaFetchproxy();
@@ -49734,19 +49862,17 @@ var SubstrateClient = class {
49734
49862
  this.#fetchImpl = opts.fetchImpl ?? ((input2, init) => fetch(input2, init));
49735
49863
  const recapture = async () => {
49736
49864
  try {
49737
- const tokens = toBearerTokens3(await capture());
49865
+ const token = await capture();
49738
49866
  this.#captureFailure = null;
49739
- return tokens;
49867
+ return token;
49740
49868
  } catch (error62) {
49741
49869
  this.#captureFailure = { at: Date.now(), error: error62 };
49742
49870
  throw error62;
49743
49871
  }
49744
49872
  };
49745
- const persistence = createSubstrateTokenCache(env);
49746
- this.#manager = new TokenManager({
49747
- initial: recapture,
49748
- refresh: recapture,
49749
- ...persistence ? { persistence } : {}
49873
+ this.#manager = createCapturedTokenManager({
49874
+ capture: recapture,
49875
+ persistence: createSubstrateTokenCache(env)
49750
49876
  });
49751
49877
  if (parseBoolEnv("TEAMS_DISABLE_FETCHPROXY", { env })) {
49752
49878
  this.#configError = new McpToolError("Substrate search is disabled (no token source).", {
@@ -49788,7 +49914,7 @@ var SubstrateClient = class {
49788
49914
  }
49789
49915
  );
49790
49916
  } catch (e) {
49791
- throw describeTransportFailure(e, SUBSTRATE_QUERY_URL, "Substrate search") ?? e;
49917
+ throw describeTransportFailure2(e, SUBSTRATE_QUERY_URL, "Substrate search") ?? e;
49792
49918
  }
49793
49919
  text = r.body;
49794
49920
  return r.res;
@@ -50861,7 +50987,7 @@ async function confirmMarks(ctx, opts) {
50861
50987
  });
50862
50988
  }
50863
50989
  function unconfirmedWhy(e) {
50864
- const status = outcomeUnknownStatus(e);
50990
+ const status = writeOutcomeStatus(e);
50865
50991
  return e.timedOut ? "it did not answer in time" : status !== void 0 ? `it answered HTTP ${status}` : "the connection dropped";
50866
50992
  }
50867
50993
  async function applyMarks(chatsvc, plans) {
@@ -51915,22 +52041,12 @@ async function threadRoot(chatsvc, channelId, id, me) {
51915
52041
  });
51916
52042
  }
51917
52043
  }
51918
- async function writeOrUnknown(run, conversation) {
51919
- try {
51920
- return { ok: true, value: await run() };
51921
- } catch (e) {
51922
- if (!(e instanceof WriteOutcomeUnknownError)) throw e;
51923
- const status = outcomeUnknownStatus(e);
51924
- const why = e.timedOut ? "it did not answer in time" : status !== void 0 ? `it answered HTTP ${status} after the post was sent` : "the connection dropped";
51925
- return {
51926
- ok: false,
51927
- result: untrustedResult2({
51928
- status: "unknown",
51929
- conversation,
51930
- warning: `Teams did not confirm this post (${why}), so it may already be in the conversation. Check the conversation before retrying (teams_read_conversation); do not resend blindly.`
51931
- })
51932
- };
51933
- }
52044
+ function unconfirmedPost(conversation) {
52045
+ return (e) => untrustedResult2({
52046
+ status: "unknown",
52047
+ conversation,
52048
+ warning: `Teams did not confirm this post (${unknownOutcomeReason(e, { sent: "the post" })}), so it may already be in the conversation. Check the conversation before retrying (teams_read_conversation); do not resend blindly.`
52049
+ });
51934
52050
  }
51935
52051
  function registerSendTools(server, { chatsvc }) {
51936
52052
  server.registerTool(
@@ -52022,7 +52138,7 @@ function registerSendTools(server, { chatsvc }) {
52022
52138
  now: /* @__PURE__ */ new Date(),
52023
52139
  ...properties
52024
52140
  });
52025
- const sent = await writeOrUnknown(() => chatsvc.sendMessage(postTo, body), target);
52141
+ const sent = await writeOrUnknown(() => chatsvc.sendMessage(postTo, body), unconfirmedPost(target));
52026
52142
  if (!sent.ok) return sent.result;
52027
52143
  let found;
52028
52144
  let readBackFailed = false;
@@ -52170,7 +52286,7 @@ function registerReactTools(server, { chatsvc }) {
52170
52286
  }
52171
52287
  const shown = remove ? "gone" : "present";
52172
52288
  if (unconfirmed !== void 0 && verified !== true) {
52173
- const status = outcomeUnknownStatus(unconfirmed);
52289
+ const status = writeOutcomeStatus(unconfirmed);
52174
52290
  const why = unconfirmed.timedOut ? "it did not answer in time" : status !== void 0 ? `it answered HTTP ${status}` : "the connection dropped";
52175
52291
  return untrustedResult2({
52176
52292
  status: "unknown",