gogcli-mcp-contacts 4.2.4 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2092,8 +2092,8 @@ function emoji() {
2092
2092
  }
2093
2093
  var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
2094
2094
  var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
2095
- var mac = (delimiter2) => {
2096
- const escapedDelim = escapeRegex(delimiter2 ?? ":");
2095
+ var mac = (delimiter3) => {
2096
+ const escapedDelim = escapeRegex(delimiter3 ?? ":");
2097
2097
  return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);
2098
2098
  };
2099
2099
  var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
@@ -5121,7 +5121,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
5121
5121
  var NONE = 0;
5122
5122
  var ASSUMED = 1;
5123
5123
  var PROVEN = 2;
5124
- function isRecursive(inst, stack, resolve) {
5124
+ function isRecursive(inst, stack, resolve4) {
5125
5125
  const cached2 = recursive.get(inst);
5126
5126
  if (cached2 !== void 0)
5127
5127
  return cached2 ? PROVEN : NONE;
@@ -5131,7 +5131,7 @@ function isRecursive(inst, stack, resolve) {
5131
5131
  let result = NONE;
5132
5132
  const check2 = (child) => {
5133
5133
  if (result !== PROVEN && child?._zod) {
5134
- const answer = isRecursive(child, stack, resolve);
5134
+ const answer = isRecursive(child, stack, resolve4);
5135
5135
  if (answer > result)
5136
5136
  result = answer;
5137
5137
  }
@@ -5142,7 +5142,7 @@ function isRecursive(inst, stack, resolve) {
5142
5142
  const desc = Object.getOwnPropertyDescriptor(sh, key);
5143
5143
  if (spread && !desc.enumerable)
5144
5144
  continue;
5145
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE;
5145
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve4) : NONE;
5146
5146
  if (child > answer)
5147
5147
  answer = child;
5148
5148
  }
@@ -5206,7 +5206,7 @@ function isRecursive(inst, stack, resolve) {
5206
5206
  break;
5207
5207
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
5208
5208
  case "lazy": {
5209
- const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : void 0);
5209
+ const inner = def._cachedInner ?? (resolve4 ? inst._zod.innerType : void 0);
5210
5210
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
5211
5211
  break;
5212
5212
  }
@@ -24106,14 +24106,14 @@ function inputRequiredRoundsExceededMessage(method, maxRounds) {
24106
24106
  return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`;
24107
24107
  }
24108
24108
  function sleep(ms, signal) {
24109
- return new Promise((resolve, reject) => {
24109
+ return new Promise((resolve4, reject) => {
24110
24110
  if (signal?.aborted) {
24111
24111
  reject(signal.reason instanceof SdkError ? signal.reason : new SdkError(SdkErrorCode.RequestTimeout, String(signal.reason)));
24112
24112
  return;
24113
24113
  }
24114
24114
  const timer = setTimeout(() => {
24115
24115
  signal?.removeEventListener("abort", onAbort);
24116
- resolve();
24116
+ resolve4();
24117
24117
  }, ms);
24118
24118
  const onAbort = () => {
24119
24119
  clearTimeout(timer);
@@ -24907,7 +24907,7 @@ var Protocol = class {
24907
24907
  const flowStartedAt = Date.now();
24908
24908
  let onAbort;
24909
24909
  let cleanupMessageId;
24910
- return new Promise((resolve, reject) => {
24910
+ return new Promise((resolve4, reject) => {
24911
24911
  const earlyReject = (error62) => {
24912
24912
  reject(error62);
24913
24913
  };
@@ -24975,7 +24975,7 @@ var Protocol = class {
24975
24975
  }
24976
24976
  if (decoded.kind === "invalid") return reject(decoded.error);
24977
24977
  if (decoded.kind === "input_required") {
24978
- if (options?.allowInputRequired === true) return resolve(manualInputRequiredValue(decoded));
24978
+ if (options?.allowInputRequired === true) return resolve4(manualInputRequiredValue(decoded));
24979
24979
  const flow = {
24980
24980
  codec: codec2,
24981
24981
  request,
@@ -24987,11 +24987,11 @@ var Protocol = class {
24987
24987
  params
24988
24988
  }, resultSchema, legOptions)
24989
24989
  };
24990
- return resolve(this._resolveNonCompleteResult(decoded, flow));
24990
+ return resolve4(this._resolveNonCompleteResult(decoded, flow));
24991
24991
  }
24992
24992
  const result = decoded.result;
24993
24993
  validateStandardSchema(resultSchema, result).then((parseResult) => {
24994
- if (parseResult.success) resolve(parseResult.data);
24994
+ if (parseResult.success) resolve4(parseResult.data);
24995
24995
  else reject(new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`));
24996
24996
  }, reject);
24997
24997
  });
@@ -27903,7 +27903,7 @@ var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => {
27903
27903
  ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
27904
27904
  const schOrFunc = root.refs[ref];
27905
27905
  if (schOrFunc) return schOrFunc;
27906
- let _sch = resolve.call(this, root, ref);
27906
+ let _sch = resolve4.call(this, root, ref);
27907
27907
  if (_sch === void 0) {
27908
27908
  const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref];
27909
27909
  const { schemaId } = this.opts;
@@ -27929,7 +27929,7 @@ var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => {
27929
27929
  function sameSchemaEnv(s1, s2) {
27930
27930
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
27931
27931
  }
27932
- function resolve(root, ref) {
27932
+ function resolve4(root, ref) {
27933
27933
  let sch;
27934
27934
  while (typeof (sch = this.refs[ref]) == "string") ref = sch;
27935
27935
  return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
@@ -28379,47 +28379,47 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
28379
28379
  else if (typeof uri === "object") uri = parse3(serialize(uri, options), options);
28380
28380
  return uri;
28381
28381
  }
28382
- function resolve(baseURI, relativeURI, options) {
28382
+ function resolve4(baseURI, relativeURI, options) {
28383
28383
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
28384
28384
  const resolved = resolveComponent(parse3(baseURI, schemelessOptions), parse3(relativeURI, schemelessOptions), schemelessOptions, true);
28385
28385
  schemelessOptions.skipEscape = true;
28386
28386
  return serialize(resolved, schemelessOptions);
28387
28387
  }
28388
- function resolveComponent(base, relative, options, skipNormalization) {
28388
+ function resolveComponent(base, relative3, options, skipNormalization) {
28389
28389
  const target = {};
28390
28390
  if (!skipNormalization) {
28391
28391
  base = parse3(serialize(base, options), options);
28392
- relative = parse3(serialize(relative, options), options);
28392
+ relative3 = parse3(serialize(relative3, options), options);
28393
28393
  }
28394
28394
  options = options || {};
28395
- if (!options.tolerant && relative.scheme) {
28396
- target.scheme = relative.scheme;
28397
- target.userinfo = relative.userinfo;
28398
- target.host = relative.host;
28399
- target.port = relative.port;
28400
- target.path = removeDotSegments(relative.path || "");
28401
- target.query = relative.query;
28395
+ if (!options.tolerant && relative3.scheme) {
28396
+ target.scheme = relative3.scheme;
28397
+ target.userinfo = relative3.userinfo;
28398
+ target.host = relative3.host;
28399
+ target.port = relative3.port;
28400
+ target.path = removeDotSegments(relative3.path || "");
28401
+ target.query = relative3.query;
28402
28402
  } else {
28403
- if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) {
28404
- target.userinfo = relative.userinfo;
28405
- target.host = relative.host;
28406
- target.port = relative.port;
28407
- target.path = removeDotSegments(relative.path || "");
28408
- target.query = relative.query;
28403
+ if (relative3.userinfo !== void 0 || relative3.host !== void 0 || relative3.port !== void 0) {
28404
+ target.userinfo = relative3.userinfo;
28405
+ target.host = relative3.host;
28406
+ target.port = relative3.port;
28407
+ target.path = removeDotSegments(relative3.path || "");
28408
+ target.query = relative3.query;
28409
28409
  } else {
28410
- if (!relative.path) {
28410
+ if (!relative3.path) {
28411
28411
  target.path = base.path;
28412
- if (relative.query !== void 0) target.query = relative.query;
28412
+ if (relative3.query !== void 0) target.query = relative3.query;
28413
28413
  else target.query = base.query;
28414
28414
  } else {
28415
- if (relative.path[0] === "/") target.path = removeDotSegments(relative.path);
28415
+ if (relative3.path[0] === "/") target.path = removeDotSegments(relative3.path);
28416
28416
  else {
28417
- if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) target.path = "/" + relative.path;
28418
- else if (!base.path) target.path = relative.path;
28419
- else target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;
28417
+ if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) target.path = "/" + relative3.path;
28418
+ else if (!base.path) target.path = relative3.path;
28419
+ else target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative3.path;
28420
28420
  target.path = removeDotSegments(target.path);
28421
28421
  }
28422
- target.query = relative.query;
28422
+ target.query = relative3.query;
28423
28423
  }
28424
28424
  target.userinfo = base.userinfo;
28425
28425
  target.host = base.host;
@@ -28427,7 +28427,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
28427
28427
  }
28428
28428
  target.scheme = base.scheme;
28429
28429
  }
28430
- target.fragment = relative.fragment;
28430
+ target.fragment = relative3.fragment;
28431
28431
  return target;
28432
28432
  }
28433
28433
  function equal(uriA, uriB, options) {
@@ -28553,7 +28553,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
28553
28553
  const fastUri = {
28554
28554
  SCHEMES,
28555
28555
  normalize,
28556
- resolve,
28556
+ resolve: resolve4,
28557
28557
  resolveComponent,
28558
28558
  equal,
28559
28559
  serialize,
@@ -29335,14 +29335,14 @@ var require_ucs2length = /* @__PURE__ */ __commonJSMin(((exports) => {
29335
29335
  function ucs2length(str) {
29336
29336
  const len = str.length;
29337
29337
  let length = 0;
29338
- let pos = 0;
29338
+ let pos2 = 0;
29339
29339
  let value;
29340
- while (pos < len) {
29340
+ while (pos2 < len) {
29341
29341
  length++;
29342
- value = str.charCodeAt(pos++);
29343
- if (value >= 55296 && value <= 56319 && pos < len) {
29344
- value = str.charCodeAt(pos);
29345
- if ((value & 64512) === 56320) pos++;
29342
+ value = str.charCodeAt(pos2++);
29343
+ if (value >= 55296 && value <= 56319 && pos2 < len) {
29344
+ value = str.charCodeAt(pos2);
29345
+ if ((value & 64512) === 56320) pos2++;
29346
29346
  }
29347
29347
  }
29348
29348
  return length;
@@ -33926,7 +33926,7 @@ var StdioServerTransport = class {
33926
33926
  }
33927
33927
  send(message) {
33928
33928
  if (this._closed) return Promise.reject(/* @__PURE__ */ new Error("StdioServerTransport is closed"));
33929
- return new Promise((resolve, reject) => {
33929
+ return new Promise((resolve4, reject) => {
33930
33930
  const json2 = serializeMessage(message);
33931
33931
  let settled = false;
33932
33932
  const onError = (error62) => {
@@ -33941,14 +33941,14 @@ var StdioServerTransport = class {
33941
33941
  settled = true;
33942
33942
  this._stdout.off("error", onError);
33943
33943
  this._stdout.off("drain", onDrain);
33944
- resolve();
33944
+ resolve4();
33945
33945
  };
33946
33946
  this._stdout.once("error", onError);
33947
33947
  if (this._stdout.write(json2)) {
33948
33948
  if (settled) return;
33949
33949
  settled = true;
33950
33950
  this._stdout.off("error", onError);
33951
- resolve();
33951
+ resolve4();
33952
33952
  } else if (!settled) this._stdout.once("drain", onDrain);
33953
33953
  });
33954
33954
  }
@@ -34002,14 +34002,14 @@ var StdioConnectionChannel = class {
34002
34002
  */
34003
34003
  async whenRequestsAnswered(timeoutMs) {
34004
34004
  if (this._closed || this._pendingRequests.size === 0) return true;
34005
- return await new Promise((resolve) => {
34005
+ return await new Promise((resolve4) => {
34006
34006
  const waiter = () => {
34007
34007
  clearTimeout(timer);
34008
- resolve(true);
34008
+ resolve4(true);
34009
34009
  };
34010
34010
  const timer = setTimeout(() => {
34011
34011
  this._drainWaiters = this._drainWaiters.filter((pending) => pending !== waiter);
34012
- resolve(false);
34012
+ resolve4(false);
34013
34013
  }, timeoutMs);
34014
34014
  this._drainWaiters.push(waiter);
34015
34015
  });
@@ -34379,13 +34379,28 @@ var API_KEY_RE = new RegExp([
34379
34379
  "whsec_[A-Za-z0-9]{16,}\\b"
34380
34380
  // webhook signing secret (Stripe-style)
34381
34381
  ].map((p) => `\\b${p}`).join("|"), "g");
34382
- var QUERY_SECRET_RE = /([?&](?:access_token|refresh_token|client_secret|api_?key|signature|token|key|sig)=)[^&#\s"'<>`]+/gi;
34382
+ var QUERY_SECRET_RE = /([?&](?:(?:access|refresh|id|auth|session|csrf|xsrf)[_-]?token|client[_-]?secret|api[_-]?secret|api[_-]?key|password|passwd|signature|token|key|sig)=)[^&#\s"'<>`]+/gi;
34383
+ var OAUTH_CODE_RE = /([?&]code=)(?=[^&#\s"'<>`]{16,})[^&#\s"'<>`]+/gi;
34384
+ var FORM_PASSWORD_RE = /((?:^|[\s,;:"'(\[{])(?:password|passwd)=)[^&#\s"'<>`]+/gim;
34385
+ var HEADER_SECRET_RE = /(\b(?:x[-_][a-z0-9_-]*?(?:api[-_]?key|token|secret|auth)[a-z0-9_-]*|api[-_]?key)\s*:\s*)[^\s,;"'<>`]+/gi;
34383
34386
  var AWS_SIGV4_RE = /([?&]X-Amz-(?:Signature|Security-Token|Credential)=)[^&#\s"'<>`]+/gi;
34384
- var JSON_SECRET_KEYS = "access_token|refresh_token|client_secret|api_?key|password|passwd|secret|token";
34385
- var JSON_SECRET_DQ_RE = new RegExp(`("(?:${JSON_SECRET_KEYS})"\\s*:\\s*")[^"]*(")`, "gi");
34386
- var JSON_SECRET_SQ_RE = new RegExp(`('(?:${JSON_SECRET_KEYS})'\\s*:\\s*')[^']*(')`, "gi");
34387
+ var JSON_SECRET_KEYS = [
34388
+ "(?:access|refresh|id|auth|session|bearer|csrf|xsrf)[_-]?token",
34389
+ "client[_-]?secret",
34390
+ "api[_-]?secret",
34391
+ "(?:x[_-])?api[_-]?key",
34392
+ "private[_-]?key",
34393
+ "x[_-][a-z0-9_-]*?(?:api[_-]?key|token|secret|auth)[a-z0-9_-]*",
34394
+ "(?:proxy-)?authorization",
34395
+ "password",
34396
+ "passwd",
34397
+ "secret",
34398
+ "token"
34399
+ ].join("|");
34400
+ var JSON_SECRET_DQ_RE = new RegExp(`("(?:${JSON_SECRET_KEYS})"\\s*:\\s*")(?:[^"\\\\]|\\\\.)*(")`, "gi");
34401
+ var JSON_SECRET_SQ_RE = new RegExp(`('(?:${JSON_SECRET_KEYS})'\\s*:\\s*')(?:[^'\\\\]|\\\\.)*(')`, "gi");
34387
34402
  function redactSecrets(text) {
34388
- 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(QUERY_SECRET_RE, "$1[REDACTED]").replace(AWS_SIGV4_RE, "$1[REDACTED]").replace(JSON_SECRET_DQ_RE, "$1[REDACTED]$2").replace(JSON_SECRET_SQ_RE, "$1[REDACTED]$2").replace(JWT_RE, "[REDACTED]");
34403
+ 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(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_SECRET_DQ_RE, "$1[REDACTED]$2").replace(JSON_SECRET_SQ_RE, "$1[REDACTED]$2").replace(JWT_RE, "[REDACTED]");
34389
34404
  }
34390
34405
 
34391
34406
  // ../../node_modules/@chrischall/mcp-utils/dist/response/view.js
@@ -34547,13 +34562,47 @@ async function createMcpServer(opts) {
34547
34562
  }
34548
34563
  return server;
34549
34564
  }
34565
+ var DEFAULT_SHUTDOWN_TIMEOUT_MS = 5e3;
34566
+ var DEFAULT_REPEAT_SIGNAL_GRACE_MS = 500;
34550
34567
  function withGracefulShutdown(target, opts = {}) {
34551
34568
  const shouldExit = opts.exit ?? true;
34569
+ if (opts.timeoutMs !== void 0 && !(Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0)) {
34570
+ throw new RangeError("withGracefulShutdown: timeoutMs must be a finite number greater than 0.");
34571
+ }
34572
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;
34573
+ if (opts.repeatSignalGraceMs !== void 0 && !(Number.isFinite(opts.repeatSignalGraceMs) && opts.repeatSignalGraceMs >= 0)) {
34574
+ throw new RangeError("withGracefulShutdown: repeatSignalGraceMs must be a finite number >= 0.");
34575
+ }
34576
+ const repeatGraceMs = opts.repeatSignalGraceMs ?? DEFAULT_REPEAT_SIGNAL_GRACE_MS;
34552
34577
  let shuttingDown = false;
34578
+ let firstSignalAt = 0;
34579
+ let exited = false;
34580
+ const exitOnce = () => {
34581
+ if (exited)
34582
+ return;
34583
+ exited = true;
34584
+ process.exit(0);
34585
+ };
34553
34586
  const handler = (signal) => {
34554
- if (shuttingDown)
34587
+ if (shuttingDown) {
34588
+ if (Date.now() - firstSignalAt < repeatGraceMs)
34589
+ return;
34590
+ if (shouldExit) {
34591
+ console.error(`[mcp-utils] second ${signal} during shutdown \u2014 exiting now`);
34592
+ exitOnce();
34593
+ }
34555
34594
  return;
34595
+ }
34556
34596
  shuttingDown = true;
34597
+ firstSignalAt = Date.now();
34598
+ let timer;
34599
+ if (shouldExit) {
34600
+ timer = setTimeout(() => {
34601
+ console.error(`[mcp-utils] graceful shutdown on ${signal} did not finish in ${timeoutMs}ms \u2014 exiting`);
34602
+ exitOnce();
34603
+ }, timeoutMs);
34604
+ timer.unref?.();
34605
+ }
34557
34606
  void (async () => {
34558
34607
  try {
34559
34608
  if (opts.onSignal)
@@ -34562,8 +34611,10 @@ function withGracefulShutdown(target, opts = {}) {
34562
34611
  } catch (err) {
34563
34612
  console.error(`[mcp-utils] error during graceful shutdown on ${signal}: ${err instanceof Error ? err.message : String(err)}`);
34564
34613
  } finally {
34614
+ if (timer !== void 0)
34615
+ clearTimeout(timer);
34565
34616
  if (shouldExit)
34566
- process.exit(0);
34617
+ exitOnce();
34567
34618
  }
34568
34619
  })();
34569
34620
  };
@@ -34593,6 +34644,8 @@ function runMcp(opts) {
34593
34644
  }
34594
34645
 
34595
34646
  // ../../node_modules/@chrischall/mcp-utils/dist/config/index.js
34647
+ import { homedir } from "node:os";
34648
+ import { isAbsolute, join, resolve } from "node:path";
34596
34649
  var PLACEHOLDER_RE = /^\$\{[^}]*\}$/;
34597
34650
  function readEnvVar(key, opts = {}) {
34598
34651
  const env = opts.env ?? process.env;
@@ -34619,6 +34672,50 @@ function parseBoolEnv(key, opts = {}) {
34619
34672
  return false;
34620
34673
  return fallback;
34621
34674
  }
34675
+ function expandPath(p) {
34676
+ let expanded = p;
34677
+ if (p === "~") {
34678
+ expanded = homedir();
34679
+ } else if (p.startsWith("~/")) {
34680
+ expanded = join(homedir(), p.slice(2));
34681
+ }
34682
+ return isAbsolute(expanded) ? expanded : resolve(expanded);
34683
+ }
34684
+
34685
+ // ../../node_modules/@chrischall/mcp-utils/dist/fs/confine.js
34686
+ import { existsSync, realpathSync } from "node:fs";
34687
+ import { dirname, isAbsolute as isAbsolute2, relative, resolve as resolve2, sep } from "node:path";
34688
+ function isInside(root, target) {
34689
+ const rel = relative(root, target);
34690
+ return rel === "" || !rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute2(rel);
34691
+ }
34692
+ function realPathAllowingMissing(p) {
34693
+ const abs = resolve2(p);
34694
+ let existing = abs;
34695
+ const tail = [];
34696
+ while (!existsSync(existing)) {
34697
+ const parent = dirname(existing);
34698
+ if (parent === existing)
34699
+ break;
34700
+ tail.unshift(existing.slice(parent.length).replace(/^[/\\]+/, ""));
34701
+ existing = parent;
34702
+ }
34703
+ let real;
34704
+ try {
34705
+ real = realpathSync(existing);
34706
+ } catch {
34707
+ real = existing;
34708
+ }
34709
+ return tail.length > 0 ? resolve2(real, ...tail) : real;
34710
+ }
34711
+ function assertPathWithinRoots(path, roots) {
34712
+ const target = realPathAllowingMissing(expandPath(path));
34713
+ for (const root of roots) {
34714
+ if (isInside(realPathAllowingMissing(expandPath(root)), target))
34715
+ return target;
34716
+ }
34717
+ throw new Error(`Path is outside the allowed directories: ${path}`);
34718
+ }
34622
34719
 
34623
34720
  // ../../node_modules/@chrischall/mcp-utils/dist/zod/index.js
34624
34721
  var PositiveInt = external_exports.number().int().positive();
@@ -34640,7 +34737,7 @@ var pageSchema = {
34640
34737
  };
34641
34738
 
34642
34739
  // ../gogcli-mcp/src/runner.ts
34643
- import { delimiter, join } from "node:path";
34740
+ import { delimiter, join as join2 } from "node:path";
34644
34741
 
34645
34742
  // ../gogcli-mcp/src/timestamps.ts
34646
34743
  var DEFAULT_DISPLAY_TZ = "America/New_York";
@@ -34841,9 +34938,48 @@ function normalizeTimestamps(text, tz = displayTimeZone(), naiveTz = naiveSource
34841
34938
  return JSON.stringify(parsed, null, detectIndent(text));
34842
34939
  }
34843
34940
 
34941
+ // ../gogcli-mcp/src/arg-guard.ts
34942
+ var FORBIDDEN_LONG_FLAG = /^--(readonly|enable-commands|enable-commands-exact|disable-commands|access-token|home|account|acct|client|gmail-no-send|no-input|non-interactive|noninteractive)(=|$)/i;
34943
+ var SHORT_ACCOUNT_CLUSTER = /^-(?!-)[A-Za-z]*a/;
34944
+ function forbiddenArgReason(arg) {
34945
+ if (arg === "--") {
34946
+ return 'The argument "--" is not allowed: it ends flag parsing and would disable safety flags appended after it.';
34947
+ }
34948
+ const match = FORBIDDEN_LONG_FLAG.exec(arg);
34949
+ if (match) {
34950
+ return `The flag ${arg} is not allowed here: --${match[1].toLowerCase()} is a safety/credential control set by the server operator, not a per-call option.`;
34951
+ }
34952
+ if (SHORT_ACCOUNT_CLUSTER.test(arg)) {
34953
+ return `The flag ${arg} is not allowed here: -a selects the account. Use the tool's account parameter instead.`;
34954
+ }
34955
+ return void 0;
34956
+ }
34957
+ function assertSafeForwardedArgs(args) {
34958
+ for (const arg of args) {
34959
+ const reason = forbiddenArgReason(arg);
34960
+ if (reason) throw new Error(reason);
34961
+ }
34962
+ }
34963
+ var SUBCOMMAND_SHAPE = /^[a-z][a-z0-9-]*$/;
34964
+ function assertSafeSubcommand(subcommand) {
34965
+ if (!SUBCOMMAND_SHAPE.test(subcommand)) {
34966
+ throw new Error(
34967
+ `Invalid subcommand ${JSON.stringify(subcommand)}: pass a single gog subcommand name such as "list" or "mark-read", and put its arguments in args.`
34968
+ );
34969
+ }
34970
+ }
34971
+
34972
+ // ../gogcli-mcp/src/argv.ts
34973
+ function pos(value) {
34974
+ return { kind: "positional", value };
34975
+ }
34976
+ function isGogPositional(arg) {
34977
+ return typeof arg === "object" && arg !== null && arg.kind === "positional";
34978
+ }
34979
+
34844
34980
  // ../gogcli-mcp/src/runner.ts
34845
34981
  function isGogFileArg(arg) {
34846
- return typeof arg !== "string";
34982
+ return typeof arg !== "string" && arg.kind === "file";
34847
34983
  }
34848
34984
  var TIMEOUT_MS = 3e4;
34849
34985
  function readonlyEnvEnabled() {
@@ -34927,8 +35063,8 @@ function formatTimeout(ms) {
34927
35063
  }
34928
35064
  async function spawnWithTempFiles(args, opts) {
34929
35065
  const { mkdtemp, mkdir, writeFile, rm } = await import("node:fs/promises");
34930
- const { tmpdir } = await import("node:os");
34931
- const dir = await mkdtemp(join(tmpdir(), "gogcli-mcp-"));
35066
+ const { tmpdir: tmpdir2 } = await import("node:os");
35067
+ const dir = await mkdtemp(join2(tmpdir2(), "gogcli-mcp-"));
34932
35068
  try {
34933
35069
  const argv = [];
34934
35070
  let seq = 0;
@@ -34937,10 +35073,10 @@ async function spawnWithTempFiles(args, opts) {
34937
35073
  argv.push(arg);
34938
35074
  continue;
34939
35075
  }
34940
- const sub = join(dir, String(seq));
35076
+ const sub = join2(dir, String(seq));
34941
35077
  seq += 1;
34942
35078
  await mkdir(sub, { recursive: true, mode: 448 });
34943
- const path = join(sub, arg.filename ?? `${arg.flag}.${arg.ext ?? "txt"}`);
35079
+ const path = join2(sub, arg.filename ?? `${arg.flag}.${arg.ext ?? "txt"}`);
34944
35080
  const data = arg.encoding === "base64" ? Buffer.from(arg.contents, "base64") : Buffer.from(arg.contents, "utf8");
34945
35081
  await writeFile(path, data, { mode: 384 });
34946
35082
  argv.push(arg.positional ? path : `--${arg.flag}=${path}`);
@@ -34958,10 +35094,10 @@ function spawnExecutor(args, opts) {
34958
35094
  return spawnGog(args, opts);
34959
35095
  }
34960
35096
  async function spawnGog(fullArgs, opts) {
34961
- const { timeout, interactive = false, spawner, binary = false } = opts;
35097
+ const { timeout, interactive = false, spawner, binary = false, maxOutputBytes } = opts;
34962
35098
  const spawn = spawner ?? (await import("node:child_process")).spawn;
34963
35099
  const effectiveTimeout = timeout ?? TIMEOUT_MS;
34964
- return new Promise((resolve, reject) => {
35100
+ return new Promise((resolve4, reject) => {
34965
35101
  const childEnv = { ...sanitizedEnv(), GOG_TIMEZONE: naiveSourceTimeZone(), PATH: augmentedPath() };
34966
35102
  const child = spawn(readEnvVar("GOG_PATH") ?? "gog", fullArgs, { env: childEnv });
34967
35103
  const stdoutChunks = [];
@@ -34979,7 +35115,17 @@ async function spawnGog(fullArgs, opts) {
34979
35115
  child.kill();
34980
35116
  reject(new Error(`gog timed out after ${formatTimeout(effectiveTimeout)}`));
34981
35117
  }, effectiveTimeout);
35118
+ let stdoutBytes = 0;
34982
35119
  child.stdout.on("data", (chunk) => {
35120
+ if (settled) return;
35121
+ stdoutBytes += chunk.length;
35122
+ if (maxOutputBytes !== void 0 && stdoutBytes > maxOutputBytes) {
35123
+ settled = true;
35124
+ stopWatching();
35125
+ child.kill();
35126
+ reject(new Error(`gog output exceeded the limit: more than ${maxOutputBytes} bytes`));
35127
+ return;
35128
+ }
34983
35129
  stdoutChunks.push(chunk);
34984
35130
  });
34985
35131
  child.stderr.on("data", (chunk) => {
@@ -34996,14 +35142,14 @@ async function spawnGog(fullArgs, opts) {
34996
35142
  const stderr = Buffer.concat(stderrChunks).toString().trim();
34997
35143
  if (code === 0) {
34998
35144
  if (binary) {
34999
- resolve(Buffer.concat(stdoutChunks).toString("base64"));
35145
+ resolve4(Buffer.concat(stdoutChunks).toString("base64"));
35000
35146
  return;
35001
35147
  }
35002
35148
  const stdout = Buffer.concat(stdoutChunks).toString();
35003
35149
  if (interactive && stderr) {
35004
- resolve(stdout + "\n" + stderr);
35150
+ resolve4(stdout + "\n" + stderr);
35005
35151
  } else {
35006
- resolve(stdout);
35152
+ resolve4(stdout);
35007
35153
  }
35008
35154
  } else {
35009
35155
  reject(new Error(stderr || `gog exited with code ${code}`));
@@ -35023,7 +35169,33 @@ async function spawnGog(fullArgs, opts) {
35023
35169
  });
35024
35170
  });
35025
35171
  }
35172
+ function placePositionals(args) {
35173
+ const flags = [];
35174
+ const positionals = [];
35175
+ let afterSeparator = false;
35176
+ for (const arg of args) {
35177
+ if (arg === "--") {
35178
+ afterSeparator = true;
35179
+ } else if (isGogPositional(arg)) {
35180
+ positionals.push(arg.value);
35181
+ } else if (afterSeparator || isGogFileArg(arg) && arg.positional) {
35182
+ positionals.push(arg);
35183
+ } else {
35184
+ flags.push(arg);
35185
+ }
35186
+ }
35187
+ return { flags, positionals };
35188
+ }
35189
+ function assertNoSafetyOverrides(flags) {
35190
+ for (const arg of flags) {
35191
+ if (typeof arg !== "string") continue;
35192
+ const reason = forbiddenArgReason(arg);
35193
+ if (reason) throw new Error(reason);
35194
+ }
35195
+ }
35026
35196
  function assembleArgs(args, opts) {
35197
+ const { flags, positionals } = placePositionals(args);
35198
+ assertNoSafetyOverrides(flags);
35027
35199
  const effectiveAccount = opts.account ?? readEnvVar("GOG_ACCOUNT");
35028
35200
  const fullArgs = ["--json", "--color=never"];
35029
35201
  if (!opts.interactive) {
@@ -35032,17 +35204,21 @@ function assembleArgs(args, opts) {
35032
35204
  if (opts.readonly || readonlyEnvEnabled()) {
35033
35205
  fullArgs.push("--readonly");
35034
35206
  }
35207
+ if (opts.gmailNoSend) {
35208
+ fullArgs.push("--gmail-no-send");
35209
+ }
35035
35210
  if (effectiveAccount) {
35036
35211
  fullArgs.push("--account", effectiveAccount);
35037
35212
  }
35038
- fullArgs.push(...args);
35213
+ fullArgs.push(...flags);
35214
+ if (positionals.length > 0) fullArgs.push("--", ...positionals);
35039
35215
  return fullArgs;
35040
35216
  }
35041
35217
  async function run(args, options = {}) {
35042
- const { account, spawner, interactive = false, timeout, readonly: readonly2 = false, redactMode = "full", opaqueFields } = options;
35218
+ const { account, spawner, interactive = false, timeout, readonly: readonly2 = false, redactMode = "full", opaqueFields, gmailNoSend = false } = options;
35043
35219
  const base = redactMode === "tokens" ? redactGoogleTokens : redactSecrets2;
35044
35220
  const redact = opaqueFields?.length ? (text) => redactPreservingOpaqueFields(text, opaqueFields, base) : base;
35045
- const fullArgs = assembleArgs(args, { account, interactive, readonly: readonly2 });
35221
+ const fullArgs = assembleArgs(args, { account, interactive, readonly: readonly2, gmailNoSend });
35046
35222
  try {
35047
35223
  return redact(await spawnExecutor(fullArgs, { timeout, interactive, spawner }));
35048
35224
  } catch (err) {
@@ -35070,6 +35246,107 @@ function stripConsumedPageToken(text) {
35070
35246
  return JSON.stringify(obj, null, detectIndent2(text));
35071
35247
  }
35072
35248
 
35249
+ // ../gogcli-mcp/src/file-roots.ts
35250
+ import { homedir as homedir2 } from "node:os";
35251
+ import { delimiter as delimiter2, join as join4 } from "node:path";
35252
+
35253
+ // ../gogcli-mcp/src/attachment-root.ts
35254
+ import { tmpdir, userInfo } from "node:os";
35255
+ import { dirname as dirname2, join as join3, relative as relative2, resolve as resolve3, isAbsolute as isAbsolute3, sep as sep2 } from "node:path";
35256
+ var ATTACHMENT_DOWNLOAD_ROOT = join3(tmpdir(), `gogcli-mcp-attachments-${userInfo().uid}`);
35257
+ var ATTACHMENT_TTL_MS = 24 * 60 * 60 * 1e3;
35258
+
35259
+ // ../gogcli-mcp/src/file-roots.ts
35260
+ var FILE_ROOTS_ENV = "GOG_FILE_ROOTS";
35261
+ function defaultFileRoot() {
35262
+ return join4(homedir2(), "gogcli-mcp-files");
35263
+ }
35264
+ function fileRoots() {
35265
+ const raw = readEnvVar(FILE_ROOTS_ENV);
35266
+ const roots = (raw ?? "").split(delimiter2).map((r) => r.trim()).filter(Boolean);
35267
+ return roots.length > 0 ? roots : [defaultFileRoot()];
35268
+ }
35269
+ function confinePath(path, param, opts = {}) {
35270
+ if (opts.allowDash && path === "-") return path;
35271
+ const roots = [...fileRoots(), ATTACHMENT_DOWNLOAD_ROOT];
35272
+ try {
35273
+ assertPathWithinRoots(path, roots);
35274
+ } catch {
35275
+ throw new Error(
35276
+ `${param} ${JSON.stringify(path)} is outside the directories this server may read or write (${roots.join(", ")}). Put the file in one of them, or ask the server operator to widen ${FILE_ROOTS_ENV}.`
35277
+ );
35278
+ }
35279
+ return path;
35280
+ }
35281
+
35282
+ // ../gogcli-mcp/src/run-path-guard.ts
35283
+ var POSITIONAL_PATH_SUBCOMMANDS = {
35284
+ appscript: { pull: "gog_appscript_pull" },
35285
+ drive: { upload: "gog_drive_upload", sync: "gog_drive_sync_push" },
35286
+ gmail: { import: "gog_gmail_import" },
35287
+ slides: {
35288
+ "add-slide": "gog_slides_add_slide",
35289
+ "insert-image": "gog_slides_insert_image",
35290
+ "replace-slide": "gog_slides_replace_slide"
35291
+ }
35292
+ };
35293
+ var PATH_FLAGS = /* @__PURE__ */ new Set(["out", "output", "out-dir", "output-dir", "dir", "worker-dir", "attach", "file", "key", "cert", "replacements"]);
35294
+ var ID_FLAGS = {
35295
+ drive: /* @__PURE__ */ new Set(["file", "filter-file"])
35296
+ };
35297
+ var EXEC_FLAGS = /* @__PURE__ */ new Set(["on-change", "on-new", "mmdc"]);
35298
+ var SHORT_PATH_CLUSTER = /^-(?!-)[A-Za-z]*[of]/;
35299
+ var LONG_FLAG = /^--([A-Za-z0-9][A-Za-z0-9-]*)(?:=([\s\S]*))?$/;
35300
+ function isPathFlag(service, name) {
35301
+ if (ID_FLAGS[service]?.has(name)) return false;
35302
+ return PATH_FLAGS.has(name) || name.endsWith("-file");
35303
+ }
35304
+ function confineFlagValue(flag, value) {
35305
+ if (value === "-") return;
35306
+ confinePath(value, flag);
35307
+ for (const part of value.split(",")) {
35308
+ if (part !== "" && part !== "-") confinePath(part, flag);
35309
+ }
35310
+ }
35311
+ function positionalPathTool(service, subcommand) {
35312
+ return POSITIONAL_PATH_SUBCOMMANDS[service]?.[subcommand];
35313
+ }
35314
+ function assertRunPathsConfined(service, subcommand, args) {
35315
+ const dedicated = positionalPathTool(service, subcommand);
35316
+ if (dedicated) {
35317
+ throw new Error(
35318
+ `gog ${service} ${subcommand} reads or writes a local path given as a positional argument, so it is not available through gog_${service}_run. Use ${dedicated}, which confines the path to GOG_FILE_ROOTS.`
35319
+ );
35320
+ }
35321
+ for (let i = 0; i < args.length; i++) {
35322
+ const arg = args[i];
35323
+ if (SHORT_PATH_CLUSTER.test(arg)) {
35324
+ throw new Error(
35325
+ `The flag ${arg} is not allowed here: spell a path flag out as --out or --file (e.g. --out=<path>) so its path can be checked against GOG_FILE_ROOTS.`
35326
+ );
35327
+ }
35328
+ const match = LONG_FLAG.exec(arg);
35329
+ if (!match) continue;
35330
+ const name = match[1].toLowerCase();
35331
+ if (EXEC_FLAGS.has(name)) {
35332
+ throw new Error(`The flag --${name} is not allowed here: it runs a local program chosen by the caller.`);
35333
+ }
35334
+ const isJson = name.endsWith("-json");
35335
+ if (!isJson && !isPathFlag(service, name)) continue;
35336
+ let value = match[2];
35337
+ if (value === void 0) {
35338
+ value = args[i + 1];
35339
+ if (value === void 0) continue;
35340
+ i++;
35341
+ }
35342
+ if (isJson) {
35343
+ if (value.startsWith("@")) confineFlagValue(`--${name}`, value.slice(1));
35344
+ continue;
35345
+ }
35346
+ confineFlagValue(`--${name}`, value);
35347
+ }
35348
+ }
35349
+
35073
35350
  // ../gogcli-mcp/src/tools/utils.ts
35074
35351
  var accountParam = external_exports.string().optional().describe(
35075
35352
  "Google account email to use, e.g. you@gmail.com \u2014 must be the full address, not a bare username. Overrides the GOG_ACCOUNT env var. Omit to use the single configured account."
@@ -35114,9 +35391,17 @@ var paginationParams = {
35114
35391
  all: external_exports.boolean().optional().describe("Fetch all pages")
35115
35392
  };
35116
35393
  function registerRunTool(server, options) {
35117
- const { service, examples, omitAccount = false, note } = options;
35394
+ const { service, examples, omitAccount = false, note, allowedSubcommands, vet, gmailNoSend = false } = options;
35395
+ for (const [, example] of examples.matchAll(/"([^"]+)"/g)) {
35396
+ const refused = allowedSubcommands && !allowedSubcommands.includes(example) || vet?.(example, []) || positionalPathTool(service, example);
35397
+ if (refused) {
35398
+ throw new Error(`gog_${service}_run example "${example}" is refused by the tool itself; list a subcommand it runs.`);
35399
+ }
35400
+ }
35118
35401
  const baseDescription = `Run any gog ${service} subcommand not covered by the other tools. Run \`gog ${service} --help\` for the full list of subcommands, or \`gog ${service} <subcommand> --help\` for flags on a specific subcommand.`;
35119
- const description = note ? `${baseDescription} ${note}` : baseDescription;
35402
+ const restriction = allowedSubcommands ? ` Only these subcommands are available: ${allowedSubcommands.join(", ")}.` : "";
35403
+ const safety = ' Flags that override server safety controls (--readonly, --enable-commands, --disable-commands, --account, --access-token, --home, --client, --gmail-no-send, --no-input) and a bare "--" are refused. Local file paths (--out, --out-dir, --attach, --file, --*-file, @file JSON) must be inside GOG_FILE_ROOTS; subcommands that take a local path positionally (e.g. drive upload) are refused in favour of their dedicated tools.';
35404
+ const description = `${baseDescription}${restriction}${safety}${note ? ` ${note}` : ""}`;
35120
35405
  const inputSchema = {
35121
35406
  subcommand: external_exports.string().describe(`The gog ${service} subcommand to run, e.g. ${examples}`),
35122
35407
  args: external_exports.array(external_exports.string()).describe("Additional positional args and flags")
@@ -35130,7 +35415,21 @@ function registerRunTool(server, options) {
35130
35415
  inputSchema: external_exports.object(inputSchema)
35131
35416
  }, async (rawArgs) => {
35132
35417
  const { subcommand, args, account } = rawArgs;
35133
- return runOrDiagnose([service, subcommand, ...args], { account });
35418
+ try {
35419
+ assertSafeSubcommand(subcommand);
35420
+ assertSafeForwardedArgs(args);
35421
+ if (allowedSubcommands && !allowedSubcommands.includes(subcommand)) {
35422
+ throw new Error(
35423
+ `gog ${service} ${subcommand} is not available through gog_${service}_run. Allowed: ${allowedSubcommands.join(", ")}.`
35424
+ );
35425
+ }
35426
+ const refusal = vet?.(subcommand, args);
35427
+ if (refusal) throw new Error(refusal);
35428
+ assertRunPathsConfined(service, subcommand, args);
35429
+ } catch (err) {
35430
+ return errorResult(errorText(err));
35431
+ }
35432
+ return runOrDiagnose([service, subcommand, ...args], gmailNoSend ? { account, gmailNoSend } : { account });
35134
35433
  });
35135
35434
  }
35136
35435
  function errorText(err) {
@@ -35252,6 +35551,7 @@ function formatAuthHealth(raw, now) {
35252
35551
  }
35253
35552
 
35254
35553
  // ../gogcli-mcp/src/tools/auth.ts
35554
+ var AUTH_RUN_SUBCOMMANDS = ["list", "status", "services", "remove", "alias"];
35255
35555
  function registerAuthToolsWith(server, defaultServices) {
35256
35556
  const servicesDescribe = `Services to authorize: "all" or comma-separated list (e.g. "sheets,gmail,calendar"). Default: "${defaultServices}". Prefer the narrowest set you need \u2014 requesting a service whose Google API is not enabled on the OAuth client's project makes Google reject the WHOLE request with invalid_scope.`;
35257
35557
  const extraScopesDescribe = "Additional raw OAuth scope URIs to request, comma-separated, on top of the ones `services` implies. Use for scopes no service covers \u2014 e.g. https://www.googleapis.com/auth/bigquery.readonly, required before gog_sheets_datasource_* can read BigQuery-backed Connected Sheets. Leave unset otherwise: an extra scope whose API is not enabled on the OAuth client project makes Google reject the WHOLE authorization with invalid_scope.";
@@ -35309,7 +35609,7 @@ function registerAuthToolsWith(server, defaultServices) {
35309
35609
  })
35310
35610
  }, async ({ email: email3, services = defaultServices, extraScopes }) => {
35311
35611
  try {
35312
- const args = ["auth", "add", email3, "--services", services];
35612
+ const args = ["auth", "add", pos(email3), "--services", services];
35313
35613
  if (extraScopes) args.push(`--extra-scopes=${extraScopes}`, "--force-consent");
35314
35614
  return rawTextResult(await run(args, {
35315
35615
  interactive: true,
@@ -35329,7 +35629,7 @@ function registerAuthToolsWith(server, defaultServices) {
35329
35629
  })
35330
35630
  }, async ({ email: email3, services = defaultServices, extraScopes }) => {
35331
35631
  try {
35332
- const args = ["auth", "add", email3, "--remote", "--step", "1", "--services", services, "--force-consent"];
35632
+ const args = ["auth", "add", pos(email3), "--remote", "--step", "1", "--services", services, "--force-consent"];
35333
35633
  if (extraScopes) args.push(`--extra-scopes=${extraScopes}`);
35334
35634
  return rawTextResult(await run(args, { redactMode: "tokens" }));
35335
35635
  } catch (err) {
@@ -35356,7 +35656,7 @@ function registerAuthToolsWith(server, defaultServices) {
35356
35656
  const args = [
35357
35657
  "auth",
35358
35658
  "add",
35359
- email3,
35659
+ pos(email3),
35360
35660
  "--remote",
35361
35661
  "--step",
35362
35662
  "2",
@@ -35376,6 +35676,7 @@ function registerAuthToolsWith(server, defaultServices) {
35376
35676
  service: "auth",
35377
35677
  examples: '"remove", "alias", "list"',
35378
35678
  omitAccount: true,
35679
+ allowedSubcommands: AUTH_RUN_SUBCOMMANDS,
35379
35680
  note: "For browser-based authorization, use gog_auth_add instead."
35380
35681
  });
35381
35682
  }
@@ -35423,7 +35724,7 @@ function registerContactsTools(server) {
35423
35724
  account: accountParam
35424
35725
  })
35425
35726
  }, async ({ query, account }) => {
35426
- return runOrDiagnose(["contacts", "search", query], { account });
35727
+ return runOrDiagnose(["contacts", "search", pos(query)], { account });
35427
35728
  });
35428
35729
  server.registerTool("gog_contacts_list", {
35429
35730
  description: "List all Google Contacts.",
@@ -35442,7 +35743,7 @@ function registerContactsTools(server) {
35442
35743
  account: accountParam
35443
35744
  })
35444
35745
  }, async ({ resourceName, account }) => {
35445
- return runOrDiagnose(["contacts", "get", resourceName], { account });
35746
+ return runOrDiagnose(["contacts", "get", pos(resourceName)], { account });
35446
35747
  });
35447
35748
  server.registerTool("gog_contacts_create", {
35448
35749
  description: "Create a new Google Contact.",
@@ -35480,7 +35781,7 @@ var replySchema = {
35480
35781
  remove: external_exports.array(external_exports.string()).optional().describe("Remove these recipients from all fields (repeatable) \u2014 e.g. to drop someone from a reply-all."),
35481
35782
  subject: external_exports.string().optional().describe('Override reply subject (default: "Re: <original>"). A changed subject starts a NEW Gmail thread.'),
35482
35783
  noQuote: external_exports.boolean().optional().describe("Do not include the original message quoted below the reply (default: the original is quoted)"),
35483
- attach: external_exports.array(external_exports.string()).optional().describe(`File paths to attach (repeatable), resolved ON THE GOG SERVER's filesystem \u2014 NOT this client's. Only usable when gog runs on the same machine you do (local stdio); on a hosted deployment (e.g. mcp-host) these paths do not exist and the call fails with "no such file or directory" \u2014 use attachInline there. Read on the server, base64-encoded with a MIME type inferred from the extension.`),
35784
+ attach: external_exports.array(external_exports.string()).optional().describe(`File paths to attach (repeatable), resolved ON THE GOG SERVER's filesystem \u2014 NOT this client's. Only usable when gog runs on the same machine you do (local stdio); on a hosted deployment (e.g. mcp-host) these paths do not exist and the call fails with "no such file or directory" \u2014 use attachInline there. Read on the server, base64-encoded with a MIME type inferred from the extension. Must be inside the server's GOG_FILE_ROOTS directories (default ~/gogcli-mcp-files).`),
35484
35785
  attachInline: attachInlineParam,
35485
35786
  from: external_exports.string().optional().describe("Send from this email address (must be a verified send-as alias)"),
35486
35787
  autoFromAddressedAlias: external_exports.boolean().optional().describe("When from is omitted, send from the verified send-as alias the original message was addressed TO, instead of the account's primary address \u2014 so a reply to mail sent to an alias goes back out from that alias. Ignored when from is set."),
@@ -35501,10 +35802,10 @@ var failIfNotEmptyParam = external_exports.boolean().optional().describe(
35501
35802
  );
35502
35803
 
35503
35804
  // ../gogcli-mcp/src/server.ts
35504
- var VERSION = true ? "4.2.4" : "0.0.0";
35805
+ var VERSION = true ? "4.3.0" : "0.0.0";
35505
35806
 
35506
35807
  // ../gogcli-mcp/src/bootstrap-auth.ts
35507
- import { join as join2 } from "node:path";
35808
+ import { join as join5 } from "node:path";
35508
35809
  var AUTH_BOOTSTRAP_MARKER = "auth-bootstrap.sha256";
35509
35810
  var VARS = ["GOG_CLIENT_ID", "GOG_CLIENT_SECRET", "GOG_REFRESH_TOKEN", "GOG_ACCOUNT"];
35510
35811
  var log = (line) => {
@@ -35541,8 +35842,8 @@ async function bootstrapGogAuth(env = process.env, options = {}) {
35541
35842
  const { createHash } = await import("node:crypto");
35542
35843
  const { mkdir, readFile, writeFile, chmod } = await import("node:fs/promises");
35543
35844
  const home = options.home ?? (await import("node:os")).homedir();
35544
- const dir = join2(home, ".gogcli-mcp");
35545
- const marker = join2(dir, AUTH_BOOTSTRAP_MARKER);
35845
+ const dir = join5(home, ".gogcli-mcp");
35846
+ const marker = join5(dir, AUTH_BOOTSTRAP_MARKER);
35546
35847
  const fingerprint = createHash("sha256").update(values.join("\0")).digest("hex");
35547
35848
  const previous = await readFile(marker, "utf8").catch(() => void 0);
35548
35849
  if (previous === fingerprint && await accountListed(account, spawner)) return "present";
@@ -35594,7 +35895,7 @@ function registerExtraContactsTools(server) {
35594
35895
  account: accountParam
35595
35896
  })
35596
35897
  }, async ({ userId, account }) => {
35597
- return runOrDiagnose(["people", "get", userId], { account });
35898
+ return runOrDiagnose(["people", "get", pos(userId)], { account });
35598
35899
  });
35599
35900
  server.registerTool("gog_people_search", {
35600
35901
  description: "Search the Google Workspace directory (covers internal users, unlike contacts search which is limited to your personal contacts).",
@@ -35608,7 +35909,7 @@ function registerExtraContactsTools(server) {
35608
35909
  account: accountParam
35609
35910
  })
35610
35911
  }, async ({ query, max, pageToken, page, all, account }) => {
35611
- const args = ["people", "search", query];
35912
+ const args = ["people", "search", pos(query)];
35612
35913
  if (max !== void 0) args.push(`--max=${max}`);
35613
35914
  const token = resolvePageToken({ pageToken, page });
35614
35915
  if (token) args.push(`--page=${token}`);
@@ -35625,7 +35926,7 @@ function registerExtraContactsTools(server) {
35625
35926
  })
35626
35927
  }, async ({ userId, type, account }) => {
35627
35928
  const args = ["people", "relations"];
35628
- if (userId) args.push(userId);
35929
+ if (userId) args.push(pos(userId));
35629
35930
  if (type) args.push(`--type=${type}`);
35630
35931
  return runOrDiagnose(args, { account });
35631
35932
  });
@@ -35648,7 +35949,7 @@ function registerExtraContactsTools(server) {
35648
35949
  account: accountParam
35649
35950
  })
35650
35951
  }, async ({ resourceName, given, family, email: email3, phone, org, title, url: url2, note, address, birthday, ignoreEtag, account }) => {
35651
- const args = ["contacts", "update", resourceName];
35952
+ const args = ["contacts", "update", pos(resourceName)];
35652
35953
  if (given !== void 0) args.push(`--given=${given}`);
35653
35954
  if (family !== void 0) args.push(`--family=${family}`);
35654
35955
  if (email3 !== void 0) args.push(`--email=${email3}`);
@@ -35670,11 +35971,12 @@ function registerExtraContactsTools(server) {
35670
35971
  account: accountParam
35671
35972
  })
35672
35973
  }, async ({ resourceName, account }) => {
35673
- return runOrDiagnose(["contacts", "delete", resourceName, "--force"], { account });
35974
+ return runOrDiagnose(["contacts", "delete", pos(resourceName), "--force"], { account });
35674
35975
  });
35675
35976
  server.registerTool("gog_contacts_export", {
35676
35977
  description: "Export contacts as vCard (.vcf). Provide a selector (resource name, email, or name), or use query / all to export multiple.",
35677
- annotations: { readOnlyHint: true },
35978
+ // Writes a file on the gog host and can overwrite one: not read-only (audit SEC-4).
35979
+ annotations: { readOnlyHint: false, destructiveHint: true },
35678
35980
  inputSchema: external_exports.object({
35679
35981
  selector: external_exports.string().optional().describe("Contact resource name (people/...), email, or name"),
35680
35982
  query: external_exports.string().optional().describe("Search query to export (max 30 results)"),
@@ -35686,8 +35988,9 @@ function registerExtraContactsTools(server) {
35686
35988
  account: accountParam
35687
35989
  })
35688
35990
  }, async ({ selector, query, all, out, max, pageToken, page, account }) => {
35991
+ if (out) confinePath(out, "out", { allowDash: true });
35689
35992
  const args = ["contacts", "export"];
35690
- if (selector) args.push(selector);
35993
+ if (selector) args.push(pos(selector));
35691
35994
  if (query) args.push(`--query=${query}`);
35692
35995
  if (all) args.push("--all");
35693
35996
  if (out) args.push(`--out=${out}`);
@@ -35762,7 +36065,7 @@ function registerExtraContactsTools(server) {
35762
36065
  account: accountParam
35763
36066
  })
35764
36067
  }, async ({ query, max, account }) => {
35765
- const args = ["contacts", "other", "search", query];
36068
+ const args = ["contacts", "other", "search", pos(query)];
35766
36069
  if (max !== void 0) args.push(`--max=${max}`);
35767
36070
  return runOrDiagnose(args, { account });
35768
36071
  });
@@ -35776,7 +36079,7 @@ function registerExtraContactsTools(server) {
35776
36079
  account: accountParam
35777
36080
  })
35778
36081
  }, async ({ userId, personFields, pretty, account }) => {
35779
- const args = ["people", "raw", userId];
36082
+ const args = ["people", "raw", pos(userId)];
35780
36083
  if (personFields) args.push(`--person-fields=${personFields}`);
35781
36084
  if (pretty) args.push("--pretty");
35782
36085
  return runOrDiagnose(args, { account, lossless: true });
package/manifest.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "manifest_version": "0.3",
4
4
  "name": "gogcli-mcp-contacts",
5
5
  "display_name": "gogcli (Contacts)",
6
- "version": "4.2.4",
6
+ "version": "4.3.0",
7
7
  "description": "Extended Google Contacts for Claude via gogcli — auth + Contacts + Workspace directory (People API)",
8
8
  "author": {
9
9
  "name": "Chris Hall",
@@ -35,7 +35,8 @@
35
35
  ],
36
36
  "env": {
37
37
  "GOG_ACCOUNT": "${user_config.gog_account}",
38
- "GOG_PATH": "${user_config.gog_path}"
38
+ "GOG_PATH": "${user_config.gog_path}",
39
+ "GOG_FILE_ROOTS": "${user_config.gog_file_roots}"
39
40
  }
40
41
  }
41
42
  },
@@ -51,6 +52,12 @@
51
52
  "title": "gog Executable Path",
52
53
  "description": "Path to the gog executable (optional — defaults to 'gog' on your PATH)",
53
54
  "required": false
55
+ },
56
+ "gog_file_roots": {
57
+ "type": "string",
58
+ "title": "Allowed file directories",
59
+ "description": "Directories tools may read files from (attachments, uploads) or write files to (exports, downloads), separated by ':' (';' on Windows). Optional — defaults to ~/gogcli-mcp-files",
60
+ "required": false
54
61
  }
55
62
  },
56
63
  "tools": [
package/mint.yaml CHANGED
@@ -92,7 +92,7 @@ dependencies:
92
92
  # bumping these nine pins, and the pin stored on each mcp-host registration.
93
93
  - kind: github-release
94
94
  repo: openclaw/gogcli
95
- tag: v0.40.0
95
+ tag: v0.41.0
96
96
  asset: "gogcli_*_linux_amd64.tar.gz"
97
97
  bin: [gog]
98
98
  state:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gogcli-mcp-contacts",
3
- "version": "4.2.4",
3
+ "version": "4.3.0",
4
4
  "mcpName": "io.github.chrischall/gogcli-mcp-contacts",
5
5
  "description": "Extended Google Contacts + People MCP server via gogcli — auth + Contacts + Workspace directory (People API)",
6
6
  "author": "Claude Code (AI) <https://www.anthropic.com/claude>",
@@ -24,7 +24,7 @@
24
24
  "test:coverage": "vitest run --coverage"
25
25
  },
26
26
  "dependencies": {
27
- "@chrischall/mcp-utils": "^2.1.0",
27
+ "@chrischall/mcp-utils": "^2.4.0",
28
28
  "@modelcontextprotocol/server": "^2.0.0",
29
29
  "zod": "^4.6.1"
30
30
  },
@@ -1,6 +1,7 @@
1
1
  import { McpServer } from '@modelcontextprotocol/server';
2
2
  import { z } from 'zod';
3
- import { accountParam, runOrDiagnose, pageTokenParam, pageAliasParam, resolvePageToken} from '../../../gogcli-mcp/src/lib.js';
3
+ import { accountParam, runOrDiagnose, pageTokenParam, pageAliasParam, resolvePageToken, pos, confinePath } from '../../../gogcli-mcp/src/lib.js';
4
+ import type { GogArg } from '../../../gogcli-mcp/src/lib.js';
4
5
 
5
6
  // People is the richer API behind Google Contacts: Workspace directory
6
7
  // search, profile fields, and relations.
@@ -23,7 +24,7 @@ export function registerExtraContactsTools(server: McpServer): void {
23
24
  account: accountParam,
24
25
  }),
25
26
  }, async ({ userId, account }) => {
26
- return runOrDiagnose(['people', 'get', userId], { account });
27
+ return runOrDiagnose(['people', 'get', pos(userId)], { account });
27
28
  });
28
29
 
29
30
  server.registerTool('gog_people_search', {
@@ -38,7 +39,7 @@ export function registerExtraContactsTools(server: McpServer): void {
38
39
  account: accountParam,
39
40
  }),
40
41
  }, async ({ query, max, pageToken, page, all, account }) => {
41
- const args = ['people', 'search', query];
42
+ const args: GogArg[] = ['people', 'search', pos(query)];
42
43
  if (max !== undefined) args.push(`--max=${max}`);
43
44
  const token = resolvePageToken({ pageToken, page });
44
45
  if (token) args.push(`--page=${token}`);
@@ -55,8 +56,8 @@ export function registerExtraContactsTools(server: McpServer): void {
55
56
  account: accountParam,
56
57
  }),
57
58
  }, async ({ userId, type, account }) => {
58
- const args = ['people', 'relations'];
59
- if (userId) args.push(userId);
59
+ const args: GogArg[] = ['people', 'relations'];
60
+ if (userId) args.push(pos(userId));
60
61
  if (type) args.push(`--type=${type}`);
61
62
  return runOrDiagnose(args, { account });
62
63
  });
@@ -80,7 +81,7 @@ export function registerExtraContactsTools(server: McpServer): void {
80
81
  account: accountParam,
81
82
  }),
82
83
  }, async ({ resourceName, given, family, email, phone, org, title, url, note, address, birthday, ignoreEtag, account }) => {
83
- const args = ['contacts', 'update', resourceName];
84
+ const args: GogArg[] = ['contacts', 'update', pos(resourceName)];
84
85
  if (given !== undefined) args.push(`--given=${given}`);
85
86
  if (family !== undefined) args.push(`--family=${family}`);
86
87
  if (email !== undefined) args.push(`--email=${email}`);
@@ -103,12 +104,13 @@ export function registerExtraContactsTools(server: McpServer): void {
103
104
  account: accountParam,
104
105
  }),
105
106
  }, async ({ resourceName, account }) => {
106
- return runOrDiagnose(['contacts', 'delete', resourceName, '--force'], { account }); // gog gates this op; without --force the runner's --no-input makes it refuse
107
+ return runOrDiagnose(['contacts', 'delete', pos(resourceName), '--force'], { account }); // gog gates this op; without --force the runner's --no-input makes it refuse
107
108
  });
108
109
 
109
110
  server.registerTool('gog_contacts_export', {
110
111
  description: 'Export contacts as vCard (.vcf). Provide a selector (resource name, email, or name), or use query / all to export multiple.',
111
- annotations: { readOnlyHint: true },
112
+ // Writes a file on the gog host and can overwrite one: not read-only (audit SEC-4).
113
+ annotations: { readOnlyHint: false, destructiveHint: true },
112
114
  inputSchema: z.object({
113
115
  selector: z.string().optional().describe('Contact resource name (people/...), email, or name'),
114
116
  query: z.string().optional().describe('Search query to export (max 30 results)'),
@@ -120,8 +122,9 @@ export function registerExtraContactsTools(server: McpServer): void {
120
122
  account: accountParam,
121
123
  }),
122
124
  }, async ({ selector, query, all, out, max, pageToken, page, account }) => {
123
- const args = ['contacts', 'export'];
124
- if (selector) args.push(selector);
125
+ if (out) confinePath(out, 'out', { allowDash: true });
126
+ const args: GogArg[] = ['contacts', 'export'];
127
+ if (selector) args.push(pos(selector));
125
128
  if (query) args.push(`--query=${query}`);
126
129
  if (all) args.push('--all');
127
130
  if (out) args.push(`--out=${out}`);
@@ -143,7 +146,7 @@ export function registerExtraContactsTools(server: McpServer): void {
143
146
  account: accountParam,
144
147
  }),
145
148
  }, async ({ match, max, resource, apply, failEmpty, account }) => {
146
- const args = ['contacts', 'dedupe'];
149
+ const args: GogArg[] = ['contacts', 'dedupe'];
147
150
  if (match) args.push(`--match=${match}`);
148
151
  if (max !== undefined) args.push(`--max=${max}`);
149
152
  if (resource) for (const r of resource) args.push(`--resource=${r}`);
@@ -164,7 +167,7 @@ export function registerExtraContactsTools(server: McpServer): void {
164
167
  account: accountParam,
165
168
  }),
166
169
  }, async ({ max, pageToken, page, all, account }) => {
167
- const args = ['contacts', 'directory', 'list'];
170
+ const args: GogArg[] = ['contacts', 'directory', 'list'];
168
171
  if (max !== undefined) args.push(`--max=${max}`);
169
172
  const token = resolvePageToken({ pageToken, page });
170
173
  if (token) args.push(`--page=${token}`);
@@ -183,7 +186,7 @@ export function registerExtraContactsTools(server: McpServer): void {
183
186
  account: accountParam,
184
187
  }),
185
188
  }, async ({ max, pageToken, page, all, account }) => {
186
- const args = ['contacts', 'other', 'list'];
189
+ const args: GogArg[] = ['contacts', 'other', 'list'];
187
190
  if (max !== undefined) args.push(`--max=${max}`);
188
191
  const token = resolvePageToken({ pageToken, page });
189
192
  if (token) args.push(`--page=${token}`);
@@ -200,7 +203,7 @@ export function registerExtraContactsTools(server: McpServer): void {
200
203
  account: accountParam,
201
204
  }),
202
205
  }, async ({ query, max, account }) => {
203
- const args = ['contacts', 'other', 'search', query];
206
+ const args: GogArg[] = ['contacts', 'other', 'search', pos(query)];
204
207
  if (max !== undefined) args.push(`--max=${max}`);
205
208
  return runOrDiagnose(args, { account });
206
209
  });
@@ -215,7 +218,7 @@ export function registerExtraContactsTools(server: McpServer): void {
215
218
  account: accountParam,
216
219
  }),
217
220
  }, async ({ userId, personFields, pretty, account }) => {
218
- const args = ['people', 'raw', userId];
221
+ const args: GogArg[] = ['people', 'raw', pos(userId)];
219
222
  if (personFields) args.push(`--person-fields=${personFields}`);
220
223
  if (pretty) args.push('--pretty');
221
224
  // Verbatim by contract: see the `lossless` note on runOrDiagnose.
@@ -3,6 +3,7 @@ import { registerExtraContactsTools } from '../../src/tools/contacts-extra.js';
3
3
  import * as lib from '../../../gogcli-mcp/src/lib.js';
4
4
  import { createTestHarness, type TestHarness } from '@chrischall/mcp-utils/test';
5
5
  import { rawTextResult } from '@chrischall/mcp-utils';
6
+ import { pos } from '../../../gogcli-mcp/src/argv.js';
6
7
 
7
8
  vi.mock('../../../gogcli-mcp/src/lib.js', async (importOriginal) => {
8
9
  const actual = await importOriginal<typeof lib>();
@@ -35,27 +36,27 @@ describe('gog_people_me', () => {
35
36
  describe('gog_people_get', () => {
36
37
  it('calls runOrDiagnose with userId', async () => {
37
38
  await harness.callTool('gog_people_get', { userId: 'people/c123' });
38
- expect(lib.runOrDiagnose).toHaveBeenCalledWith(['people', 'get', 'people/c123'], { account: undefined });
39
+ expect(lib.runOrDiagnose).toHaveBeenCalledWith(['people', 'get', pos('people/c123')], { account: undefined });
39
40
  });
40
41
  });
41
42
 
42
43
  describe('gog_people_search', () => {
43
44
  it('calls runOrDiagnose with query', async () => {
44
45
  await harness.callTool('gog_people_search', { query: 'alice' });
45
- expect(lib.runOrDiagnose).toHaveBeenCalledWith(['people', 'search', 'alice'], { account: undefined });
46
+ expect(lib.runOrDiagnose).toHaveBeenCalledWith(['people', 'search', pos('alice')], { account: undefined });
46
47
  });
47
48
 
48
49
  it('passes pagination flags', async () => {
49
50
  await harness.callTool('gog_people_search', { query: 'alice', max: 100, page: 'tok', all: true });
50
51
  expect(lib.runOrDiagnose).toHaveBeenCalledWith(
51
- ['people', 'search', 'alice', '--max=100', '--page=tok', '--all'],
52
+ ['people', 'search', pos('alice'), '--max=100', '--page=tok', '--all'],
52
53
  { account: undefined },
53
54
  );
54
55
  });
55
56
 
56
57
  it('omits --all when false', async () => {
57
58
  await harness.callTool('gog_people_search', { query: 'x', all: false });
58
- expect(lib.runOrDiagnose).toHaveBeenCalledWith(['people', 'search', 'x'], { account: undefined });
59
+ expect(lib.runOrDiagnose).toHaveBeenCalledWith(['people', 'search', pos('x')], { account: undefined });
59
60
  });
60
61
  });
61
62
 
@@ -68,7 +69,7 @@ describe('gog_people_relations', () => {
68
69
  it('passes userId and --type when provided', async () => {
69
70
  await harness.callTool('gog_people_relations', { userId: 'people/c123', type: 'manager' });
70
71
  expect(lib.runOrDiagnose).toHaveBeenCalledWith(
71
- ['people', 'relations', 'people/c123', '--type=manager'],
72
+ ['people', 'relations', pos('people/c123'), '--type=manager'],
72
73
  { account: undefined },
73
74
  );
74
75
  });
@@ -77,7 +78,7 @@ describe('gog_people_relations', () => {
77
78
  describe('gog_contacts_update', () => {
78
79
  it('calls runOrDiagnose with just resourceName', async () => {
79
80
  await harness.callTool('gog_contacts_update', { resourceName: 'people/c1' });
80
- expect(lib.runOrDiagnose).toHaveBeenCalledWith(['contacts', 'update', 'people/c1'], { account: undefined });
81
+ expect(lib.runOrDiagnose).toHaveBeenCalledWith(['contacts', 'update', pos('people/c1')], { account: undefined });
81
82
  });
82
83
 
83
84
  it('passes all fields including empty-string clears', async () => {
@@ -97,7 +98,7 @@ describe('gog_contacts_update', () => {
97
98
  });
98
99
  expect(lib.runOrDiagnose).toHaveBeenCalledWith(
99
100
  [
100
- 'contacts', 'update', 'people/c1',
101
+ 'contacts', 'update', pos('people/c1'),
101
102
  '--given=Ada', '--family=Lovelace', '--email=', '--phone=+1',
102
103
  '--org=Analytical', '--title=Engineer', '--url=https://a.com',
103
104
  '--note=hi', '--address=1 St;City', '--birthday=1815-12-10', '--ignore-etag',
@@ -108,14 +109,14 @@ describe('gog_contacts_update', () => {
108
109
 
109
110
  it('omits --ignore-etag when false', async () => {
110
111
  await harness.callTool('gog_contacts_update', { resourceName: 'people/c1', ignoreEtag: false });
111
- expect(lib.runOrDiagnose).toHaveBeenCalledWith(['contacts', 'update', 'people/c1'], { account: undefined });
112
+ expect(lib.runOrDiagnose).toHaveBeenCalledWith(['contacts', 'update', pos('people/c1')], { account: undefined });
112
113
  });
113
114
  });
114
115
 
115
116
  describe('gog_contacts_delete', () => {
116
117
  it('calls runOrDiagnose with resourceName', async () => {
117
118
  await harness.callTool('gog_contacts_delete', { resourceName: 'people/c1' });
118
- expect(lib.runOrDiagnose).toHaveBeenCalledWith(['contacts', 'delete', 'people/c1', '--force'], { account: undefined });
119
+ expect(lib.runOrDiagnose).toHaveBeenCalledWith(['contacts', 'delete', pos('people/c1'), '--force'], { account: undefined });
119
120
  });
120
121
  });
121
122
 
@@ -135,7 +136,7 @@ describe('gog_contacts_export', () => {
135
136
  page: 'tok',
136
137
  });
137
138
  expect(lib.runOrDiagnose).toHaveBeenCalledWith(
138
- ['contacts', 'export', 'people/c1', '--query=ada', '--all', '--out=out.vcf', '--max=10', '--page=tok'],
139
+ ['contacts', 'export', pos('people/c1'), '--query=ada', '--all', '--out=out.vcf', '--max=10', '--page=tok'],
139
140
  { account: undefined },
140
141
  );
141
142
  });
@@ -221,13 +222,13 @@ describe('gog_contacts_other_list', () => {
221
222
  describe('gog_contacts_other_search', () => {
222
223
  it('calls runOrDiagnose with query', async () => {
223
224
  await harness.callTool('gog_contacts_other_search', { query: 'ada' });
224
- expect(lib.runOrDiagnose).toHaveBeenCalledWith(['contacts', 'other', 'search', 'ada'], { account: undefined });
225
+ expect(lib.runOrDiagnose).toHaveBeenCalledWith(['contacts', 'other', 'search', pos('ada')], { account: undefined });
225
226
  });
226
227
 
227
228
  it('passes --max when provided', async () => {
228
229
  await harness.callTool('gog_contacts_other_search', { query: 'ada', max: 25 });
229
230
  expect(lib.runOrDiagnose).toHaveBeenCalledWith(
230
- ['contacts', 'other', 'search', 'ada', '--max=25'],
231
+ ['contacts', 'other', 'search', pos('ada'), '--max=25'],
231
232
  { account: undefined },
232
233
  );
233
234
  });
@@ -236,7 +237,7 @@ describe('gog_contacts_other_search', () => {
236
237
  describe('gog_people_raw', () => {
237
238
  it('calls runOrDiagnose with userId', async () => {
238
239
  await harness.callTool('gog_people_raw', { userId: 'people/c123' });
239
- expect(lib.runOrDiagnose).toHaveBeenCalledWith(['people', 'raw', 'people/c123'], { account: undefined, lossless: true });
240
+ expect(lib.runOrDiagnose).toHaveBeenCalledWith(['people', 'raw', pos('people/c123')], { account: undefined, lossless: true });
240
241
  });
241
242
 
242
243
  it('passes --person-fields and --pretty when provided', async () => {
@@ -246,13 +247,55 @@ describe('gog_people_raw', () => {
246
247
  pretty: true,
247
248
  });
248
249
  expect(lib.runOrDiagnose).toHaveBeenCalledWith(
249
- ['people', 'raw', 'people/c123', '--person-fields=names,emailAddresses', '--pretty'],
250
+ ['people', 'raw', pos('people/c123'), '--person-fields=names,emailAddresses', '--pretty'],
250
251
  { account: undefined, lossless: true },
251
252
  );
252
253
  });
253
254
 
254
255
  it('omits --pretty when false', async () => {
255
256
  await harness.callTool('gog_people_raw', { userId: 'people/c123', pretty: false });
256
- expect(lib.runOrDiagnose).toHaveBeenCalledWith(['people', 'raw', 'people/c123'], { account: undefined, lossless: true });
257
+ expect(lib.runOrDiagnose).toHaveBeenCalledWith(['people', 'raw', pos('people/c123')], { account: undefined, lossless: true });
258
+ });
259
+ });
260
+
261
+ // SEC-3/SEC-4: every model-supplied server path must resolve inside an
262
+ // operator-configured root (GOG_FILE_ROOTS). The suite runs with '/' so the
263
+ // arg-shape tests can use any path; these narrow it.
264
+ async function withFileRoots<T>(roots: string, fn: () => Promise<T>): Promise<T> {
265
+ const prev = process.env.GOG_FILE_ROOTS;
266
+ process.env.GOG_FILE_ROOTS = roots;
267
+ try {
268
+ return await fn();
269
+ } finally {
270
+ process.env.GOG_FILE_ROOTS = prev;
271
+ }
272
+ }
273
+
274
+ describe('server paths are confined to GOG_FILE_ROOTS', () => {
275
+ it.each([
276
+ ['gog_contacts_export', {"out": "/Users/me/.zshrc"}, 'out'],
277
+ ] as Array<[string, Record<string, unknown>, string]>)('%s refuses %j outside the roots', async (tool, args, param) => {
278
+ const h = harness;
279
+ const result = await withFileRoots('/srv/gog-files', () => h.callTool(tool, args));
280
+ expect(result.isError).toBe(true);
281
+ expect(result.content[0].text).toMatch(new RegExp(`${param} ".*" is outside the directories`));
282
+ expect(lib.runOrDiagnose).not.toHaveBeenCalled();
283
+ });
284
+
285
+ // Clients auto-approve readOnlyHint tools; these write (and can overwrite)
286
+ // files on the gog host, so they must not claim to be read-only.
287
+ it.each(["gog_contacts_export"])('%s is not advertised as read-only and is marked destructive', async (name) => {
288
+ const h = harness;
289
+ const { tools } = await h.client.listTools();
290
+ const tool = tools.find((t) => t.name === name)!;
291
+ expect(tool.annotations?.readOnlyHint).not.toBe(true);
292
+ expect(tool.annotations?.destructiveHint).toBe(true);
293
+ });
294
+ });
295
+
296
+ describe('gog_contacts_export — stdout', () => {
297
+ it('still accepts "-" (stdout) whatever the roots', async () => {
298
+ await withFileRoots('/srv/gog-files', () => harness.callTool('gog_contacts_export', { out: '-' }));
299
+ expect(lib.runOrDiagnose).toHaveBeenCalled();
257
300
  });
258
301
  });
package/vitest.config.ts CHANGED
@@ -2,6 +2,11 @@ import { defineConfig } from 'vitest/config';
2
2
 
3
3
  export default defineConfig({
4
4
  test: {
5
+ // The arg-shape tests pass arbitrary server paths; confinement is exercised
6
+ // explicitly by the tests that narrow GOG_FILE_ROOTS themselves.
7
+ env: {
8
+ GOG_FILE_ROOTS: '/',
9
+ },
5
10
  coverage: {
6
11
  provider: 'v8',
7
12
  include: ['src/**/*.ts'],