gogcli-mcp-contacts 4.5.1 → 4.6.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
@@ -37,6 +37,33 @@ var storage2 = new AsyncLocalStorage2();
37
37
  function withCallerCapabilities(capabilities, fn) {
38
38
  return capabilities ? storage2.run(capabilities, fn) : fn();
39
39
  }
40
+ function currentCallerCapabilities() {
41
+ return storage2.getStore();
42
+ }
43
+ var ENVELOPE_CAPABILITIES_KEY = "io.modelcontextprotocol/clientCapabilities";
44
+ var ELICITATION_MODES = ["form", "url"];
45
+ function isRecord(value) {
46
+ return typeof value === "object" && value !== null && !Array.isArray(value);
47
+ }
48
+ function callerCapabilities(ctx) {
49
+ const envelope = isRecord(ctx) && isRecord(ctx.mcpReq) ? ctx.mcpReq.envelope : void 0;
50
+ if (isRecord(envelope)) {
51
+ const declared = envelope[ENVELOPE_CAPABILITIES_KEY];
52
+ if (isRecord(declared))
53
+ return declared;
54
+ }
55
+ return currentCallerCapabilities();
56
+ }
57
+ function callerAcceptsFormElicitation(ctx) {
58
+ const capabilities = callerCapabilities(ctx);
59
+ if (!capabilities)
60
+ return void 0;
61
+ const elicitation = capabilities.elicitation;
62
+ if (!isRecord(elicitation))
63
+ return false;
64
+ const namedModes = ELICITATION_MODES.filter((mode) => mode in elicitation);
65
+ return namedModes.length === 0 || namedModes.includes("form");
66
+ }
40
67
 
41
68
  // ../../node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs
42
69
  var __create = Object.create;
@@ -19763,7 +19790,7 @@ function date4(params) {
19763
19790
  return _coercedDate(ZodDate, params);
19764
19791
  }
19765
19792
 
19766
- // ../../node_modules/@modelcontextprotocol/core/dist/auth-CUe6YdwF.mjs
19793
+ // ../../node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/dist/auth-CGP0BDVq.mjs
19767
19794
  var LATEST_PROTOCOL_VERSION = "2025-11-25";
19768
19795
  var SUPPORTED_PROTOCOL_VERSIONS = [
19769
19796
  LATEST_PROTOCOL_VERSION,
@@ -20600,7 +20627,8 @@ var OAuthMetadataSchema = looseObject({
20600
20627
  introspection_endpoint_auth_signing_alg_values_supported: array(string2()).optional(),
20601
20628
  code_challenge_methods_supported: array(string2()).optional(),
20602
20629
  client_id_metadata_document_supported: boolean2().optional(),
20603
- authorization_response_iss_parameter_supported: boolean2().optional().catch(void 0)
20630
+ authorization_response_iss_parameter_supported: boolean2().optional().catch(void 0),
20631
+ dpop_signing_alg_values_supported: array(string2()).optional()
20604
20632
  });
20605
20633
  var OpenIdProviderMetadataSchema = looseObject({
20606
20634
  issuer: string2(),
@@ -20701,7 +20729,7 @@ var OAuthTokenRevocationRequestSchema = object({
20701
20729
  token_type_hint: string2().optional()
20702
20730
  }).strip();
20703
20731
 
20704
- // ../../node_modules/@modelcontextprotocol/server/dist/src-CX2iR2pK.mjs
20732
+ // ../../node_modules/@modelcontextprotocol/server/dist/src-D-y6h4N7.mjs
20705
20733
  var BRANDS = /* @__PURE__ */ Symbol.for("mcp.sdk.errorBrands");
20706
20734
  function stampErrorBrands(instance, ctor) {
20707
20735
  const brands = /* @__PURE__ */ new Set();
@@ -20815,8 +20843,18 @@ var SdkError = class extends Error {
20815
20843
  if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");
20816
20844
  return brandedHasInstance(this, value);
20817
20845
  }
20818
- constructor(code, message, data) {
20819
- super(message);
20846
+ /**
20847
+ * @param code - Stable string code identifying the failure ({@linkcode SdkErrorCode}).
20848
+ * @param message - Human-readable description.
20849
+ * @param data - Optional structured payload (for example the HTTP status carried by
20850
+ * {@linkcode SdkHttpError}). Opaque to the SDK: a `cause` key inside `data` is not
20851
+ * promoted to `Error.cause`.
20852
+ * @param options - Standard `ErrorOptions`, forwarded to `Error`. Pass the underlying
20853
+ * failure as `{ cause }` so it is reachable through the `Error.cause` chain that
20854
+ * loggers and error trackers walk.
20855
+ */
20856
+ constructor(code, message, data, options) {
20857
+ super(message, options);
20820
20858
  this.code = code;
20821
20859
  this.data = data;
20822
20860
  this.name = "SdkError";
@@ -20827,8 +20865,11 @@ var SdkHttpError = class extends SdkError {
20827
20865
  static {
20828
20866
  Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkHttpError" });
20829
20867
  }
20830
- constructor(code, message, data) {
20831
- super(code, message, data);
20868
+ /**
20869
+ * @param options - Standard `ErrorOptions`, forwarded to `Error` (see {@linkcode SdkError}).
20870
+ */
20871
+ constructor(code, message, data, options) {
20872
+ super(code, message, data, options);
20832
20873
  this.name = "SdkHttpError";
20833
20874
  }
20834
20875
  get status() {
@@ -23779,7 +23820,7 @@ var INBOUND_VALIDATION_LADDER = [
23779
23820
  evaluatedAt: "pre-dispatch",
23780
23821
  codes: [HEADER_MISMATCH_ERROR_CODE],
23781
23822
  conformance: ["http-header-validation"],
23782
- rationale: "SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."
23823
+ rationale: "SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half \u2014 including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."
23783
23824
  },
23784
23825
  {
23785
23826
  rung: "client-capabilities",
@@ -24101,6 +24142,37 @@ var inputRequired = Object.assign(buildInputRequired, {
24101
24142
  return { method: "roots/list" };
24102
24143
  }
24103
24144
  });
24145
+ function acceptedContent(responses, key, schema) {
24146
+ const view = inputResponse(responses, key);
24147
+ if (view.kind !== "elicit" || view.action !== "accept" || view.content === void 0) return void 0;
24148
+ if (schema === void 0) return view.content;
24149
+ const outcome = schema["~standard"].validate(view.content);
24150
+ if (outcome instanceof Promise) throw new TypeError("acceptedContent(responses, key, schema) requires a synchronously-validating schema");
24151
+ return outcome.issues === void 0 ? outcome.value : void 0;
24152
+ }
24153
+ function inputResponse(responses, key) {
24154
+ if (responses === void 0 || typeof responses !== "object" || responses === null) return { kind: "missing" };
24155
+ const entry = responses[key];
24156
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return { kind: "missing" };
24157
+ const candidate = entry;
24158
+ if (candidate["action"] === "accept" || candidate["action"] === "decline" || candidate["action"] === "cancel") {
24159
+ const content = candidate["content"];
24160
+ return {
24161
+ kind: "elicit",
24162
+ action: candidate["action"],
24163
+ ...content !== null && typeof content === "object" && !Array.isArray(content) && { content }
24164
+ };
24165
+ }
24166
+ if (Array.isArray(candidate["roots"])) return {
24167
+ kind: "roots",
24168
+ roots: candidate["roots"]
24169
+ };
24170
+ if (typeof candidate["role"] === "string" && candidate["content"] !== void 0) return {
24171
+ kind: "sampling",
24172
+ result: candidate
24173
+ };
24174
+ return { kind: "missing" };
24175
+ }
24104
24176
  var REQUEST_STATE_ONLY_LEG_PACING_MS = 250;
24105
24177
  function inputRequiredRoundsExceededMessage(method, maxRounds) {
24106
24178
  return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`;
@@ -24549,7 +24621,7 @@ var Protocol = class {
24549
24621
  return this._requestHandlers.get(method);
24550
24622
  }
24551
24623
  async _oncancel(notification) {
24552
- if (!notification.params.requestId) return;
24624
+ if (notification.params.requestId === void 0) return;
24553
24625
  this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason);
24554
24626
  }
24555
24627
  _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
@@ -24948,19 +25020,20 @@ var Protocol = class {
24948
25020
  const cancel = (reason) => {
24949
25021
  if (responseReceived) return;
24950
25022
  this._progressHandlers.delete(messageId);
24951
- if (requestAbort === void 0) this._transport?.send(this._envelopeOutbound({
24952
- jsonrpc: "2.0",
24953
- method: "notifications/cancelled",
24954
- params: {
24955
- requestId: messageId,
24956
- reason: String(reason)
24957
- }
24958
- }), {
24959
- relatedRequestId,
24960
- resumptionToken,
24961
- onresumptiontoken
24962
- }).catch((error62) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error62}`)));
24963
- else requestAbort.abort();
25023
+ if (requestAbort === void 0) {
25024
+ if (request.method !== "initialize") this._transport?.send(this._envelopeOutbound({
25025
+ jsonrpc: "2.0",
25026
+ method: "notifications/cancelled",
25027
+ params: {
25028
+ requestId: messageId,
25029
+ reason: String(reason)
25030
+ }
25031
+ }), {
25032
+ relatedRequestId,
25033
+ resumptionToken,
25034
+ onresumptiontoken
25035
+ }).catch((error62) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error62}`)));
25036
+ } else requestAbort.abort();
24964
25037
  reject(reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason)));
24965
25038
  };
24966
25039
  this._responseHandlers.set(messageId, (response) => {
@@ -25040,7 +25113,7 @@ var Protocol = class {
25040
25113
  jsonrpc: "2.0",
25041
25114
  ...notification
25042
25115
  });
25043
- if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && !options?.relatedRequestId) {
25116
+ if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && options?.relatedRequestId === void 0) {
25044
25117
  if (this._pendingDebouncedNotifications.has(notification.method)) return;
25045
25118
  this._pendingDebouncedNotifications.add(notification.method);
25046
25119
  Promise.resolve().then(() => {
@@ -32343,7 +32416,7 @@ var Ajv = import_ajv.Ajv;
32343
32416
  // ../../node_modules/@modelcontextprotocol/server/dist/shimsNode.mjs
32344
32417
  import process2 from "node:process";
32345
32418
 
32346
- // ../../node_modules/@modelcontextprotocol/server/dist/mcp-DXXb3Vv3.mjs
32419
+ // ../../node_modules/@modelcontextprotocol/server/dist/mcp-Dw2OlZ1f.mjs
32347
32420
  var COMPLETABLE_SYMBOL = /* @__PURE__ */ Symbol.for("mcp.completable");
32348
32421
  function isCompletable(schema) {
32349
32422
  return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema;
@@ -32536,6 +32609,9 @@ function notificationToServerEvent(method, uri) {
32536
32609
  };
32537
32610
  }
32538
32611
  }
32612
+ function supportsScopeChallengeResolver(transport) {
32613
+ return typeof transport === "object" && transport !== null && "setScopeChallengeResolver" in transport && typeof transport.setScopeChallengeResolver === "function";
32614
+ }
32539
32615
  var DEFAULT_LEGACY_SHIM_MAX_ROUNDS = 8;
32540
32616
  var DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS = 6e5;
32541
32617
  function resolveLegacyShimOptions(options) {
@@ -33346,6 +33422,7 @@ var McpServer = class {
33346
33422
  * ```
33347
33423
  */
33348
33424
  async connect(transport) {
33425
+ if (supportsScopeChallengeResolver(transport)) transport.setScopeChallengeResolver((context) => this.resolveScopeChallenge(context));
33349
33426
  return await this.server.connect(transport);
33350
33427
  }
33351
33428
  /**
@@ -33354,6 +33431,41 @@ var McpServer = class {
33354
33431
  async close() {
33355
33432
  await this.server.close();
33356
33433
  }
33434
+ /** @internal */
33435
+ resolveScopeChallenge = (context) => {
33436
+ switch (context.request.method) {
33437
+ case "tools/call": {
33438
+ const toolName = context.request.params?.name;
33439
+ if (typeof toolName !== "string") return;
33440
+ const tool = this._registeredTools[toolName];
33441
+ if (tool === void 0 || !tool.enabled) return;
33442
+ return tool.scopeChallenge?.(context);
33443
+ }
33444
+ case "resources/read": {
33445
+ const resourceUri = context.request.params?.uri;
33446
+ if (typeof resourceUri !== "string") return;
33447
+ let uri;
33448
+ try {
33449
+ uri = new URL(resourceUri);
33450
+ } catch {
33451
+ return;
33452
+ }
33453
+ const resource = this._registeredResources[uri.toString()];
33454
+ if (resource !== void 0) return resource.enabled ? resource.scopeChallenge?.(context) : void 0;
33455
+ for (const template of Object.values(this._registeredResourceTemplates)) if (template.resourceTemplate.uriTemplate.match(uri.toString())) return template.enabled ? template.scopeChallenge?.(context) : void 0;
33456
+ return;
33457
+ }
33458
+ case "prompts/get": {
33459
+ const promptName = context.request.params?.name;
33460
+ if (typeof promptName !== "string") return;
33461
+ const prompt = this._registeredPrompts[promptName];
33462
+ if (prompt === void 0 || !prompt.enabled) return;
33463
+ return prompt.scopeChallenge?.(context);
33464
+ }
33465
+ default:
33466
+ return;
33467
+ }
33468
+ };
33357
33469
  _toolHandlersInitialized = false;
33358
33470
  setToolRequestHandlers() {
33359
33471
  if (this._toolHandlersInitialized) return;
@@ -33520,7 +33632,10 @@ var McpServer = class {
33520
33632
  }
33521
33633
  for (const template of Object.values(this._registeredResourceTemplates)) {
33522
33634
  const variables = template.resourceTemplate.uriTemplate.match(uri.toString());
33523
- if (variables) return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint);
33635
+ if (variables) {
33636
+ if (!template.enabled) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Resource template ${template.resourceTemplate.uriTemplate} disabled`);
33637
+ return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint);
33638
+ }
33524
33639
  }
33525
33640
  throw new ResourceNotFoundError(request.params.uri);
33526
33641
  });
@@ -33551,36 +33666,32 @@ var McpServer = class {
33551
33666
  this._promptHandlersInitialized = true;
33552
33667
  }
33553
33668
  registerResource(name, uriOrTemplate, config2, readCallback) {
33554
- const cacheHint = config2.cacheHint;
33555
- let metadata = config2;
33556
- if (cacheHint !== void 0) {
33557
- assertValidCacheHint(cacheHint, `resource ${name}`);
33558
- const rest = { ...config2 };
33559
- delete rest.cacheHint;
33560
- metadata = rest;
33561
- }
33669
+ const { cacheHint, scopeChallenge, ...resourceMetadata } = config2;
33670
+ const metadata = resourceMetadata;
33671
+ if (cacheHint !== void 0) assertValidCacheHint(cacheHint, `resource ${name}`);
33562
33672
  if (typeof uriOrTemplate === "string") {
33563
33673
  if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`);
33564
- const registeredResource = this._createRegisteredResource(name, config2.title, uriOrTemplate, metadata, readCallback);
33674
+ const registeredResource = this._createRegisteredResource(name, config2.title, uriOrTemplate, metadata, scopeChallenge, readCallback);
33565
33675
  if (cacheHint !== void 0) registeredResource.cacheHint = cacheHint;
33566
33676
  this.setResourceRequestHandlers();
33567
33677
  this.sendResourceListChanged();
33568
33678
  return registeredResource;
33569
33679
  } else {
33570
33680
  if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`);
33571
- const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config2.title, uriOrTemplate, metadata, readCallback);
33681
+ const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config2.title, uriOrTemplate, metadata, scopeChallenge, readCallback);
33572
33682
  if (cacheHint !== void 0) registeredResourceTemplate.cacheHint = cacheHint;
33573
33683
  this.setResourceRequestHandlers();
33574
33684
  this.sendResourceListChanged();
33575
33685
  return registeredResourceTemplate;
33576
33686
  }
33577
33687
  }
33578
- _createRegisteredResource(name, title, uri, metadata, readCallback) {
33688
+ _createRegisteredResource(name, title, uri, metadata, scopeChallenge, readCallback) {
33579
33689
  const registeredResource = {
33580
33690
  name,
33581
33691
  title,
33582
33692
  metadata,
33583
33693
  readCallback,
33694
+ scopeChallenge,
33584
33695
  enabled: true,
33585
33696
  disable: () => registeredResource.update({ enabled: false }),
33586
33697
  enable: () => registeredResource.update({ enabled: true }),
@@ -33594,6 +33705,7 @@ var McpServer = class {
33594
33705
  if (updates.title !== void 0) registeredResource.title = updates.title;
33595
33706
  if (updates.metadata !== void 0) registeredResource.metadata = updates.metadata;
33596
33707
  if (updates.callback !== void 0) registeredResource.readCallback = updates.callback;
33708
+ if (updates.scopeChallenge !== void 0) registeredResource.scopeChallenge = updates.scopeChallenge === null ? void 0 : updates.scopeChallenge;
33597
33709
  if (updates.enabled !== void 0) registeredResource.enabled = updates.enabled;
33598
33710
  this.sendResourceListChanged();
33599
33711
  }
@@ -33601,12 +33713,13 @@ var McpServer = class {
33601
33713
  this._registeredResources[uri] = registeredResource;
33602
33714
  return registeredResource;
33603
33715
  }
33604
- _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) {
33716
+ _createRegisteredResourceTemplate(name, title, template, metadata, scopeChallenge, readCallback) {
33605
33717
  const registeredResourceTemplate = {
33606
33718
  resourceTemplate: template,
33607
33719
  title,
33608
33720
  metadata,
33609
33721
  readCallback,
33722
+ scopeChallenge,
33610
33723
  enabled: true,
33611
33724
  disable: () => registeredResourceTemplate.update({ enabled: false }),
33612
33725
  enable: () => registeredResourceTemplate.update({ enabled: true }),
@@ -33620,6 +33733,7 @@ var McpServer = class {
33620
33733
  if (updates.template !== void 0) registeredResourceTemplate.resourceTemplate = updates.template;
33621
33734
  if (updates.metadata !== void 0) registeredResourceTemplate.metadata = updates.metadata;
33622
33735
  if (updates.callback !== void 0) registeredResourceTemplate.readCallback = updates.callback;
33736
+ if (updates.scopeChallenge !== void 0) registeredResourceTemplate.scopeChallenge = updates.scopeChallenge === null ? void 0 : updates.scopeChallenge;
33623
33737
  if (updates.enabled !== void 0) registeredResourceTemplate.enabled = updates.enabled;
33624
33738
  this.sendResourceListChanged();
33625
33739
  }
@@ -33629,7 +33743,7 @@ var McpServer = class {
33629
33743
  if (Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v))) this.setCompletionRequestHandler();
33630
33744
  return registeredResourceTemplate;
33631
33745
  }
33632
- _createRegisteredPrompt(name, title, description, argsSchema, callback, icons, _meta) {
33746
+ _createRegisteredPrompt(name, title, description, argsSchema, callback, icons, scopeChallenge, _meta) {
33633
33747
  let currentArgsSchema = argsSchema;
33634
33748
  let currentCallback = callback;
33635
33749
  const registeredPrompt = {
@@ -33637,6 +33751,7 @@ var McpServer = class {
33637
33751
  description,
33638
33752
  argsSchema,
33639
33753
  icons,
33754
+ scopeChallenge,
33640
33755
  _meta,
33641
33756
  handler: createPromptHandler(name, argsSchema, callback),
33642
33757
  enabled: true,
@@ -33651,6 +33766,7 @@ var McpServer = class {
33651
33766
  if (updates.title !== void 0) registeredPrompt.title = updates.title;
33652
33767
  if (updates.description !== void 0) registeredPrompt.description = updates.description;
33653
33768
  if (updates.icons !== void 0) registeredPrompt.icons = updates.icons;
33769
+ if (updates.scopeChallenge !== void 0) registeredPrompt.scopeChallenge = updates.scopeChallenge === null ? void 0 : updates.scopeChallenge;
33654
33770
  if (updates._meta !== void 0) registeredPrompt._meta = updates._meta;
33655
33771
  let needsHandlerRegen = false;
33656
33772
  if (updates.argsSchema !== void 0) {
@@ -33678,7 +33794,7 @@ var McpServer = class {
33678
33794
  }
33679
33795
  return registeredPrompt;
33680
33796
  }
33681
- _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, icons, execution, _meta, handler) {
33797
+ _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, icons, execution, scopeChallenge, _meta, handler) {
33682
33798
  validateAndWarnToolName(name);
33683
33799
  if (inputSchema !== void 0) try {
33684
33800
  const json2 = standardSchemaToJsonSchema(inputSchema, "input");
@@ -33697,6 +33813,7 @@ var McpServer = class {
33697
33813
  annotations,
33698
33814
  icons,
33699
33815
  execution,
33816
+ scopeChallenge,
33700
33817
  _meta,
33701
33818
  handler,
33702
33819
  executor: createToolExecutor(inputSchema, handler),
@@ -33735,6 +33852,7 @@ var McpServer = class {
33735
33852
  }
33736
33853
  if (updates.annotations !== void 0) registeredTool.annotations = updates.annotations;
33737
33854
  if (updates.icons !== void 0) registeredTool.icons = updates.icons;
33855
+ if (updates.scopeChallenge !== void 0) registeredTool.scopeChallenge = updates.scopeChallenge === null ? void 0 : updates.scopeChallenge;
33738
33856
  if (updates._meta !== void 0) registeredTool._meta = updates._meta;
33739
33857
  if (updates.enabled !== void 0) registeredTool.enabled = updates.enabled;
33740
33858
  this.sendToolListChanged();
@@ -33747,13 +33865,13 @@ var McpServer = class {
33747
33865
  }
33748
33866
  registerTool(name, config2, cb) {
33749
33867
  if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`);
33750
- const { title, description, inputSchema, outputSchema, annotations, icons, _meta } = config2;
33751
- return this._createRegisteredTool(name, title, description, normalizeRawShapeSchema(inputSchema), normalizeRawShapeSchema(outputSchema), annotations, icons, void 0, _meta, cb);
33868
+ const { title, description, inputSchema, outputSchema, annotations, icons, scopeChallenge, _meta } = config2;
33869
+ return this._createRegisteredTool(name, title, description, normalizeRawShapeSchema(inputSchema), normalizeRawShapeSchema(outputSchema), annotations, icons, void 0, scopeChallenge, _meta, cb);
33752
33870
  }
33753
33871
  registerPrompt(name, config2, cb) {
33754
33872
  if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`);
33755
- const { title, description, argsSchema, icons, _meta } = config2;
33756
- const registeredPrompt = this._createRegisteredPrompt(name, title, description, normalizeRawShapeSchema(argsSchema), cb, icons, _meta);
33873
+ const { title, description, argsSchema, icons, scopeChallenge, _meta } = config2;
33874
+ const registeredPrompt = this._createRegisteredPrompt(name, title, description, normalizeRawShapeSchema(argsSchema), cb, icons, scopeChallenge, _meta);
33757
33875
  this.setPromptRequestHandlers();
33758
33876
  this.sendPromptListChanged();
33759
33877
  return registeredPrompt;
@@ -33865,6 +33983,7 @@ function unwrapOptionalSchema(schema) {
33865
33983
  }
33866
33984
 
33867
33985
  // ../../node_modules/@modelcontextprotocol/server/dist/stdio.mjs
33986
+ var swallowsErrorsAfterClose = /* @__PURE__ */ Symbol("swallowsErrorsAfterClose");
33868
33987
  var StdioServerTransport = class {
33869
33988
  _readBuffer;
33870
33989
  _started = false;
@@ -33891,18 +34010,27 @@ var StdioServerTransport = class {
33891
34010
  this.onerror?.(error62);
33892
34011
  };
33893
34012
  _onstdouterror = (error62) => {
34013
+ if (this._closed) return;
33894
34014
  this.onerror?.(error62);
33895
34015
  this.close().catch(() => {
33896
34016
  });
33897
34017
  };
34018
+ _onstdinclose = () => {
34019
+ this.close().catch(() => {
34020
+ });
34021
+ };
33898
34022
  /**
33899
34023
  * Starts listening for messages on `stdin`.
33900
34024
  */
33901
34025
  async start() {
33902
34026
  if (this._started) throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");
33903
34027
  this._started = true;
34028
+ for (const listener of this._stdout.listeners("error")) if (listener[swallowsErrorsAfterClose]) this._stdout.off("error", listener);
34029
+ if (this._stdin.readableEnded || this._stdin.destroyed) setImmediate(this._onstdinclose);
33904
34030
  this._stdin.on("data", this._ondata);
33905
34031
  this._stdin.on("error", this._onerror);
34032
+ this._stdin.on("end", this._onstdinclose);
34033
+ this._stdin.on("close", this._onstdinclose);
33906
34034
  this._stdout.on("error", this._onstdouterror);
33907
34035
  }
33908
34036
  processReadBuffer() {
@@ -33919,7 +34047,9 @@ var StdioServerTransport = class {
33919
34047
  this._closed = true;
33920
34048
  this._stdin.off("data", this._ondata);
33921
34049
  this._stdin.off("error", this._onerror);
33922
- this._stdout.off("error", this._onstdouterror);
34050
+ this._stdin.off("end", this._onstdinclose);
34051
+ this._stdin.off("close", this._onstdinclose);
34052
+ this._onstdouterror[swallowsErrorsAfterClose] = true;
33923
34053
  if (this._stdin.listenerCount("data") === 0) this._stdin.pause();
33924
34054
  this._readBuffer.clear();
33925
34055
  this.onclose?.();
@@ -34148,14 +34278,14 @@ function serveStdio(factory, options = {}) {
34148
34278
  return false;
34149
34279
  };
34150
34280
  const answerLegacyRejection = (request, reason, requestedVersion) => {
34151
- const rejection2 = modernOnlyStrictRejection({
34281
+ const rejection3 = modernOnlyStrictRejection({
34152
34282
  kind: "legacy",
34153
34283
  reason,
34154
34284
  ...requestedVersion !== void 0 && { requestedVersion }
34155
34285
  }, SUPPORTED_MODERN_PROTOCOL_VERSIONS);
34156
- if (rejection2 === void 0) return Promise.resolve();
34157
- reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only stdio connection (${rejection2.cell}): ${rejection2.message}`));
34158
- return writeErrorResponse(request.id, rejection2.code, rejection2.message, rejection2.data);
34286
+ if (rejection3 === void 0) return Promise.resolve();
34287
+ reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only stdio connection (${rejection3.cell}): ${rejection3.message}`));
34288
+ return writeErrorResponse(request.id, rejection3.code, rejection3.message, rejection3.data);
34159
34289
  };
34160
34290
  const onInstanceClosed = (channel) => {
34161
34291
  if (closing || channel === discarding) return;
@@ -34196,6 +34326,7 @@ function serveStdio(factory, options = {}) {
34196
34326
  return;
34197
34327
  }
34198
34328
  if (state.era === "modern" && await tryServeListen(message)) return;
34329
+ if (isTornDown()) return;
34199
34330
  state.instance.channel.deliver(message);
34200
34331
  return;
34201
34332
  }
@@ -34262,6 +34393,7 @@ function serveStdio(factory, options = {}) {
34262
34393
  };
34263
34394
  }
34264
34395
  if (await tryServeListen(message)) return;
34396
+ if (isTornDown()) return;
34265
34397
  state.instance.channel.deliver(message, { classification: opening.classification });
34266
34398
  return;
34267
34399
  case "legacy": {
@@ -34348,6 +34480,9 @@ function toError(value) {
34348
34480
  return value instanceof Error ? value : new Error(String(value));
34349
34481
  }
34350
34482
 
34483
+ // ../../node_modules/@modelcontextprotocol/server/dist/index.mjs
34484
+ var DEFAULT_MAX_REQUEST_BODY_SIZE = 4 * 1024 * 1024;
34485
+
34351
34486
  // ../../node_modules/@chrischall/mcp-utils/dist/errors/index.js
34352
34487
  var McpToolError = class extends Error {
34353
34488
  /** Actionable remediation text, when one applies. */
@@ -34458,6 +34593,11 @@ function walk(value, keep, drop) {
34458
34593
  }
34459
34594
 
34460
34595
  // ../../node_modules/@chrischall/mcp-utils/dist/response/index.js
34596
+ function textResult(data) {
34597
+ return {
34598
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }]
34599
+ };
34600
+ }
34461
34601
  function rawTextResult(text) {
34462
34602
  return { content: [{ type: "text", text }] };
34463
34603
  }
@@ -34468,7 +34608,160 @@ function errorResult(message) {
34468
34608
  };
34469
34609
  }
34470
34610
 
34611
+ // ../../node_modules/@chrischall/mcp-utils/dist/server/confirmation.js
34612
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
34613
+
34614
+ // ../../node_modules/@chrischall/mcp-utils/dist/server/canonical.js
34615
+ function canonicalJson(value) {
34616
+ if (value === null || typeof value === "string" || typeof value === "boolean")
34617
+ return JSON.stringify(value);
34618
+ if (value === void 0)
34619
+ return "null";
34620
+ if (typeof value === "number")
34621
+ return Number.isFinite(value) ? JSON.stringify(value) : `{"$num":"${String(value)}"}`;
34622
+ if (typeof value === "bigint")
34623
+ return `{"$bigint":"${value.toString()}"}`;
34624
+ if (typeof value === "function" || typeof value === "symbol") {
34625
+ throw new TypeError(`confirmation: cannot bind a ${typeof value} argument value.`);
34626
+ }
34627
+ if (Array.isArray(value))
34628
+ return `[${value.map(canonicalJson).join(",")}]`;
34629
+ if (value instanceof Date) {
34630
+ return `{"$date":${JSON.stringify(Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString())}}`;
34631
+ }
34632
+ if (ArrayBuffer.isView(value)) {
34633
+ const bytes = Buffer.from(value.buffer, value.byteOffset, value.byteLength);
34634
+ return `{"$bytes":${JSON.stringify(bytes.toString("base64"))}}`;
34635
+ }
34636
+ if (value instanceof ArrayBuffer)
34637
+ return `{"$bytes":${JSON.stringify(Buffer.from(value).toString("base64"))}}`;
34638
+ if (value instanceof Map) {
34639
+ const entries2 = [...value.entries()].map(([k, v]) => `[${canonicalJson(k)},${canonicalJson(v)}]`).sort();
34640
+ return `{"$map":[${entries2.join(",")}]}`;
34641
+ }
34642
+ if (value instanceof Set) {
34643
+ return `{"$set":[${[...value].map(canonicalJson).sort().join(",")}]}`;
34644
+ }
34645
+ const proto = Object.getPrototypeOf(value);
34646
+ if (proto !== Object.prototype && proto !== null) {
34647
+ throw new TypeError("confirmation: cannot bind a non-plain object argument value (class instance).");
34648
+ }
34649
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
34650
+ return `{${entries.map(([k, v]) => `${JSON.stringify(escapeKey(k))}:${canonicalJson(v)}`).join(",")}}`;
34651
+ }
34652
+ function escapeKey(key) {
34653
+ return key.startsWith("$") ? `$${key}` : key;
34654
+ }
34655
+
34656
+ // ../../node_modules/@chrischall/mcp-utils/dist/server/confirmation.js
34657
+ var DEFAULT_REQUEST_KEY = "confirmation";
34658
+ var DEFAULT_CONFIRMATION_LABEL = "Confirm this action should proceed.";
34659
+ var UNSUPPORTED_NOTE = "Nothing was done because this client cannot show a confirmation prompt (it declares no MCP elicitation capability), and this action is never taken without one";
34660
+ var STATE_PREFIX = "mcpu.confirm.v1.";
34661
+ function bindingKey(binding) {
34662
+ if (binding.ttlSeconds !== void 0 && !(Number.isFinite(binding.ttlSeconds) && binding.ttlSeconds > 0)) {
34663
+ throw new RangeError("requireConfirmation: binding.ttlSeconds must be a finite number greater than 0.");
34664
+ }
34665
+ const key = typeof binding.key === "string" ? Buffer.from(binding.key, "utf8") : Buffer.from(binding.key);
34666
+ if (key.length < 32) {
34667
+ throw new RangeError("requireConfirmation: binding.key must be at least 32 bytes.");
34668
+ }
34669
+ return key;
34670
+ }
34671
+ function commitment(action, args) {
34672
+ return createHash("sha256").update(`${action}\0${canonicalJson(args)}`).digest("base64url");
34673
+ }
34674
+ function mintState(key, action, binding) {
34675
+ const exp = Math.floor(Date.now() / 1e3) + (binding.ttlSeconds ?? 600);
34676
+ const body = Buffer.from(JSON.stringify({ c: commitment(action, binding.args), exp })).toString("base64url");
34677
+ const mac3 = createHmac("sha256", key).update(`${STATE_PREFIX}${body}`).digest("base64url");
34678
+ return `${STATE_PREFIX}${body}.${mac3}`;
34679
+ }
34680
+ function verifyState(key, action, binding, state) {
34681
+ if (typeof state !== "string" || !state.startsWith(STATE_PREFIX))
34682
+ return false;
34683
+ const rest = state.slice(STATE_PREFIX.length);
34684
+ const dot = rest.indexOf(".");
34685
+ if (dot < 0)
34686
+ return false;
34687
+ const body = rest.slice(0, dot);
34688
+ const mac3 = Buffer.from(rest.slice(dot + 1), "base64url");
34689
+ const expected = createHmac("sha256", key).update(`${STATE_PREFIX}${body}`).digest();
34690
+ if (mac3.length !== expected.length || !timingSafeEqual(mac3, expected))
34691
+ return false;
34692
+ let payload;
34693
+ try {
34694
+ payload = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
34695
+ } catch {
34696
+ return false;
34697
+ }
34698
+ if (typeof payload.exp !== "number" || payload.exp * 1e3 <= Date.now())
34699
+ return false;
34700
+ const want = Buffer.from(commitment(action, binding.args));
34701
+ const got = Buffer.from(typeof payload.c === "string" ? payload.c : "");
34702
+ return got.length === want.length && timingSafeEqual(got, want);
34703
+ }
34704
+ function echoedState(ctx) {
34705
+ const accessor = ctx.mcpReq.requestState;
34706
+ return typeof accessor === "function" ? accessor() : void 0;
34707
+ }
34708
+ function requireConfirmation(ctx, options) {
34709
+ const requestKey = options.requestKey ?? DEFAULT_REQUEST_KEY;
34710
+ const key = options.binding ? bindingKey(options.binding) : void 0;
34711
+ const confirmationSchema = external_exports.object({
34712
+ confirmed: external_exports.boolean().describe(options.confirmationLabel ?? DEFAULT_CONFIRMATION_LABEL)
34713
+ });
34714
+ const ask = () => {
34715
+ const preview = {
34716
+ action: options.action,
34717
+ ...options.details === void 0 ? {} : { details: options.details }
34718
+ };
34719
+ return inputRequired({
34720
+ inputRequests: {
34721
+ [requestKey]: inputRequired.elicit({
34722
+ message: `${options.message}
34723
+ ${JSON.stringify(preview, null, 2)}`,
34724
+ requestedSchema: confirmationSchema
34725
+ })
34726
+ },
34727
+ ...key && options.binding ? { requestState: mintState(key, options.action, options.binding) } : {}
34728
+ });
34729
+ };
34730
+ const response = inputResponse(ctx.mcpReq.inputResponses, requestKey);
34731
+ const accepted = acceptedContent(ctx.mcpReq.inputResponses, requestKey, confirmationSchema);
34732
+ if (response.kind === "missing") {
34733
+ if (callerAcceptsFormElicitation(ctx) === false) {
34734
+ return textResult({
34735
+ confirmed: false,
34736
+ dispatched: false,
34737
+ action: options.action,
34738
+ reason: "confirmation-unsupported",
34739
+ note: options.unsupportedNote ? `${UNSUPPORTED_NOTE}. ${options.unsupportedNote}` : `${UNSUPPORTED_NOTE}.`
34740
+ });
34741
+ }
34742
+ return ask();
34743
+ }
34744
+ if (response.kind === "elicit" && response.action === "accept" && accepted?.confirmed === true) {
34745
+ if (key && options.binding) {
34746
+ const state = echoedState(ctx);
34747
+ if (state === void 0 || state === null) {
34748
+ return errorResult(`Confirmation for ${options.action} was accepted, but the retry carried no requestState, so it cannot be checked against the prompt that was shown. Nothing was done. The likely cause is that the MCP client or host does not round-trip requestState (it must echo the requestState from the input_required result back on the retry); asking again would loop.`);
34749
+ }
34750
+ if (!verifyState(key, options.action, options.binding, state))
34751
+ return ask();
34752
+ }
34753
+ return void 0;
34754
+ }
34755
+ return textResult({
34756
+ confirmed: false,
34757
+ cancelled: true,
34758
+ action: options.action,
34759
+ note: "Nothing was changed because the confirmation was declined, cancelled, or left unchecked."
34760
+ });
34761
+ }
34762
+
34471
34763
  // ../../node_modules/@chrischall/mcp-utils/dist/server/confirm-token.js
34764
+ import { createHash as createHash2, createHmac as createHmac2, randomBytes, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
34472
34765
  function createSpentTokenStore() {
34473
34766
  const spent2 = /* @__PURE__ */ new Map();
34474
34767
  return {
@@ -34488,7 +34781,148 @@ function createSpentTokenStore() {
34488
34781
  };
34489
34782
  }
34490
34783
  var PROCESS_SPENT = createSpentTokenStore();
34784
+ var PREFIX = "mcpu.token.v1.";
34785
+ var DEFAULT_TTL_SECONDS = 600;
34786
+ function tokenKey(key) {
34787
+ const bytes = typeof key === "string" ? Buffer.from(key, "utf8") : Buffer.from(key);
34788
+ if (bytes.length < 32)
34789
+ throw new RangeError("confirm token: key must be at least 32 bytes.");
34790
+ return bytes;
34791
+ }
34792
+ function ttlOf(ttlSeconds) {
34793
+ if (ttlSeconds === void 0)
34794
+ return DEFAULT_TTL_SECONDS;
34795
+ if (!(Number.isFinite(ttlSeconds) && ttlSeconds > 0)) {
34796
+ throw new RangeError("confirm token: ttlSeconds must be a finite number greater than 0.");
34797
+ }
34798
+ return ttlSeconds;
34799
+ }
34800
+ function sign(key, body) {
34801
+ return createHmac2("sha256", key).update(`${PREFIX}${body}`).digest();
34802
+ }
34803
+ function hashConfirmPayload(payload) {
34804
+ return createHash2("sha256").update(canonicalJson(payload)).digest("base64url");
34805
+ }
34806
+ function issueConfirmToken(key, binding, options = {}) {
34807
+ const k = tokenKey(key);
34808
+ const now = options.now ?? Date.now();
34809
+ const exp = now + ttlOf(options.ttlSeconds) * 1e3;
34810
+ const claims = {
34811
+ t: binding.tool,
34812
+ ...binding.account === void 0 ? {} : { a: binding.account },
34813
+ g: binding.target,
34814
+ ...binding.revision === void 0 ? {} : { r: binding.revision },
34815
+ h: binding.payloadHash,
34816
+ exp,
34817
+ n: randomBytes(16).toString("base64url")
34818
+ };
34819
+ const body = Buffer.from(JSON.stringify(claims), "utf8").toString("base64url");
34820
+ return { token: `${PREFIX}${body}.${sign(k, body).toString("base64url")}`, expiresAt: new Date(exp).toISOString() };
34821
+ }
34822
+ function parseClaims(body) {
34823
+ try {
34824
+ const claims = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
34825
+ return claims && typeof claims === "object" ? claims : void 0;
34826
+ } catch {
34827
+ return void 0;
34828
+ }
34829
+ }
34830
+ function verifyConfirmToken(key, token, binding, options = {}) {
34831
+ const k = tokenKey(key);
34832
+ const now = options.now ?? Date.now();
34833
+ const spent2 = options.spent ?? PROCESS_SPENT;
34834
+ spent2.prune(now);
34835
+ if (!token.startsWith(PREFIX))
34836
+ return { ok: false, error: "TOKEN_INVALID" };
34837
+ const rest = token.slice(PREFIX.length);
34838
+ const dot = rest.indexOf(".");
34839
+ const body = dot < 0 ? "" : rest.slice(0, dot);
34840
+ const mac3 = Buffer.from(dot < 0 ? "" : rest.slice(dot + 1), "base64url");
34841
+ const expected = sign(k, body);
34842
+ if (!body || mac3.length !== expected.length || !timingSafeEqual2(mac3, expected))
34843
+ return { ok: false, error: "TOKEN_INVALID" };
34844
+ const claims = parseClaims(body);
34845
+ if (!claims)
34846
+ return { ok: false, error: "TOKEN_INVALID" };
34847
+ if (claims.t !== binding.tool || claims.a !== binding.account || claims.g !== binding.target) {
34848
+ return { ok: false, error: "TOKEN_INVALID" };
34849
+ }
34850
+ if (spent2.has(claims.n))
34851
+ return { ok: false, error: "TOKEN_REUSED" };
34852
+ if (now > claims.exp)
34853
+ return { ok: false, error: "TOKEN_EXPIRED" };
34854
+ if (claims.r !== binding.revision)
34855
+ return { ok: false, error: "DRAFT_CHANGED", reason: "revision-changed" };
34856
+ if (claims.h !== binding.payloadHash)
34857
+ return { ok: false, error: "DRAFT_CHANGED", reason: "payload-changed" };
34858
+ spent2.add(claims.n, claims.exp);
34859
+ return { ok: true };
34860
+ }
34861
+ var CONFIRM_TOKEN_INSTRUCTION = "Show this preview to the user verbatim and proceed only after they explicitly approve in chat. Then call again with confirmToken.";
34491
34862
  var confirmTokenParam = external_exports.string().optional().describe(`ONLY for the two-step confirmation fallback (a client without MCP elicitation). The confirmToken from this same tool's phase-1 "confirmation-required" response, passed back ONLY after the user has seen that preview and explicitly approved it in chat \u2014 never on the first call, never invented, never reused. Call again with the same arguments. Ignored when the client supports elicitation.`);
34863
+ var TOKEN_ERROR_NOTE = {
34864
+ TOKEN_EXPIRED: "Nothing was sent or changed: the confirmToken expired. Call again WITHOUT confirmToken for a fresh preview, and ask the user to approve it again.",
34865
+ TOKEN_REUSED: "Nothing was sent or changed by this call: this confirmToken was already used, and one approval acts once. If doing it again is really intended, call again WITHOUT confirmToken and get a new approval.",
34866
+ TOKEN_INVALID: "Nothing was sent or changed: this confirmToken was not issued by this server for this tool, account and target (or the server has restarted since). Call again WITHOUT confirmToken for a fresh preview and approval."
34867
+ };
34868
+ var CHANGED_NOTE = {
34869
+ "revision-changed": "Nothing was sent or changed: the target was edited since the user approved it (its version rotated), so what would happen is not what they saw.",
34870
+ "payload-changed": "Nothing was sent or changed: what would happen no longer matches what the user approved."
34871
+ };
34872
+ function isToolResult(value) {
34873
+ return Array.isArray(value.content);
34874
+ }
34875
+ function rejection2(data) {
34876
+ return { ...textResult({ status: "confirmation-rejected", confirmed: false, dispatched: false, ...data }), isError: true };
34877
+ }
34878
+ async function tokenConfirmation(action, fb) {
34879
+ const subject = await fb.subject();
34880
+ if (isToolResult(subject))
34881
+ return subject;
34882
+ const binding = {
34883
+ tool: fb.tool,
34884
+ ...fb.account === void 0 ? {} : { account: fb.account },
34885
+ target: subject.target,
34886
+ ...subject.revision === void 0 ? {} : { revision: subject.revision },
34887
+ payloadHash: hashConfirmPayload(subject.payload)
34888
+ };
34889
+ const phaseOne = () => {
34890
+ const { token, expiresAt } = issueConfirmToken(fb.key, binding, { ttlSeconds: fb.ttlSeconds });
34891
+ return {
34892
+ action,
34893
+ preview: subject.preview,
34894
+ confirmToken: token,
34895
+ expiresAt,
34896
+ ttlSeconds: ttlOf(fb.ttlSeconds),
34897
+ instruction: fb.instruction ?? CONFIRM_TOKEN_INSTRUCTION
34898
+ };
34899
+ };
34900
+ if (!fb.confirmToken) {
34901
+ return textResult({ status: "confirmation-required", confirmed: false, dispatched: false, ...phaseOne() });
34902
+ }
34903
+ const verdict = verifyConfirmToken(fb.key, fb.confirmToken, binding, { spent: fb.spent });
34904
+ if (verdict.ok)
34905
+ return void 0;
34906
+ if (verdict.error === "DRAFT_CHANGED") {
34907
+ return rejection2({
34908
+ error: "DRAFT_CHANGED",
34909
+ reason: verdict.reason,
34910
+ note: `${CHANGED_NOTE[verdict.reason]} The current preview and a fresh confirmToken are below.`,
34911
+ ...phaseOne()
34912
+ });
34913
+ }
34914
+ return rejection2({ error: verdict.error, action, note: TOKEN_ERROR_NOTE[verdict.error] });
34915
+ }
34916
+ async function requireConfirmationWithFallback(ctx, options) {
34917
+ const { tokenFallback, ...confirmation } = options;
34918
+ if (tokenFallback && callerAcceptsFormElicitation(ctx) === false) {
34919
+ return tokenConfirmation(options.action, tokenFallback);
34920
+ }
34921
+ return requireConfirmation(ctx, confirmation);
34922
+ }
34923
+
34924
+ // ../../node_modules/@chrischall/mcp-utils/dist/server/confirm-env.js
34925
+ import { createHash as createHash3, randomBytes as randomBytes2 } from "node:crypto";
34492
34926
 
34493
34927
  // ../../node_modules/@chrischall/mcp-utils/dist/config/index.js
34494
34928
  import { homedir } from "node:os";
@@ -34529,6 +34963,61 @@ function expandPath(p) {
34529
34963
  return isAbsolute(expanded) ? expanded : resolve(expanded);
34530
34964
  }
34531
34965
 
34966
+ // ../../node_modules/@chrischall/mcp-utils/dist/server/confirm-env.js
34967
+ var MODES = /* @__PURE__ */ new Set(["ask-user", "auto", "refuse"]);
34968
+ var DEFAULT_TTL_SECONDS2 = 600;
34969
+ var warned = /* @__PURE__ */ new Set();
34970
+ function readConfirmMode(env = process.env) {
34971
+ const raw = readEnvVar("MCP_CONFIRM_MODE", { env })?.trim().toLowerCase();
34972
+ if (!raw)
34973
+ return "ask-user";
34974
+ if (MODES.has(raw))
34975
+ return raw;
34976
+ if (!warned.has(raw)) {
34977
+ warned.add(raw);
34978
+ process.stderr.write(`MCP_CONFIRM_MODE="${raw}" is not one of ask-user, auto, refuse; treating it as refuse.
34979
+ `);
34980
+ }
34981
+ return "refuse";
34982
+ }
34983
+ function confirmTtlFromEnv(env = process.env) {
34984
+ const raw = readEnvVar("MCP_CONFIRM_TTL_SECONDS", { env })?.trim();
34985
+ return raw && /^[1-9]\d*$/.test(raw) ? Number(raw) : DEFAULT_TTL_SECONDS2;
34986
+ }
34987
+ var processKey;
34988
+ function confirmKeyFromEnv(env = process.env) {
34989
+ const secret = readEnvVar("MCP_CONFIRM_SECRET", { env });
34990
+ if (secret)
34991
+ return createHash3("sha256").update(secret, "utf8").digest();
34992
+ processKey ??= randomBytes2(32);
34993
+ return processKey;
34994
+ }
34995
+ var CONFIRM_TOKEN_AUTO_INSTRUCTION = "Nothing has been done yet. Review this preview; if it is what was intended, call again with the same arguments plus confirmToken. (This server runs with MCP_CONFIRM_MODE=auto, so the user's approval in chat is not required.)";
34996
+ var REFUSE_HINT = "Set MCP_CONFIRM_MODE=ask-user on the server to allow two-step confirmation instead.";
34997
+ function confirmationFromEnv(options) {
34998
+ const { tool, account, confirmToken, subject, instruction, spent: spent2, env = process.env, ...confirmation } = options;
34999
+ const mode = readConfirmMode(env);
35000
+ if (mode === "refuse") {
35001
+ return {
35002
+ ...confirmation,
35003
+ unsupportedNote: confirmation.unsupportedNote ? `${confirmation.unsupportedNote} ${REFUSE_HINT}` : REFUSE_HINT
35004
+ };
35005
+ }
35006
+ return {
35007
+ ...confirmation,
35008
+ tokenFallback: {
35009
+ key: confirmKeyFromEnv(env),
35010
+ tool,
35011
+ ...account === void 0 ? {} : { account },
35012
+ ...confirmToken === void 0 ? {} : { confirmToken },
35013
+ subject,
35014
+ ttlSeconds: confirmTtlFromEnv(env),
35015
+ instruction: mode === "auto" ? CONFIRM_TOKEN_AUTO_INSTRUCTION : instruction ?? CONFIRM_TOKEN_INSTRUCTION,
35016
+ ...spent2 === void 0 ? {} : { spent: spent2 }
35017
+ }
35018
+ };
35019
+ }
35020
+
34532
35021
  // ../../node_modules/@chrischall/mcp-utils/dist/server/index.js
34533
35022
  var SERVER_PROTOCOL_VERSIONS = Object.freeze([
34534
35023
  "2026-07-28",
@@ -34785,9 +35274,9 @@ function offsetAt(instant, tz) {
34785
35274
  const w = wallPartsIn(instant, tz);
34786
35275
  const asUTC = Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute, w.second, instant.getUTCMilliseconds());
34787
35276
  const minutes = Math.round((asUTC - instant.getTime()) / 6e4);
34788
- const sign = minutes < 0 ? "-" : "+";
35277
+ const sign2 = minutes < 0 ? "-" : "+";
34789
35278
  const abs = Math.abs(minutes);
34790
- return `${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`;
35279
+ return `${sign2}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`;
34791
35280
  }
34792
35281
  function wallPartsIn(instant, tz) {
34793
35282
  const parts = new Intl.DateTimeFormat("en-US", {
@@ -35575,6 +36064,41 @@ function formatAuthHealth(raw, now) {
35575
36064
 
35576
36065
  // ../gogcli-mcp/src/send-confirm-token.ts
35577
36066
  var spent = createSpentTokenStore();
36067
+ function confirmSpentStore() {
36068
+ return spent;
36069
+ }
36070
+
36071
+ // ../gogcli-mcp/src/dispatch-confirmation.ts
36072
+ var CONFIRM_ACTION_INSTRUCTION = CONFIRM_TOKEN_INSTRUCTION;
36073
+ function refusedInRun(what, via, does, instead) {
36074
+ return `${what} ${does} and is not available through ${via}. ${instead}`;
36075
+ }
36076
+ function gatedElsewhere(what, via, does, tool) {
36077
+ return refusedInRun(what, via, does, `Use ${tool}, which asks the user to confirm.`);
36078
+ }
36079
+ function hasCommandWord(args, words) {
36080
+ return args.find((a) => words.has(a.toLowerCase()));
36081
+ }
36082
+ async function requireDispatchConfirmation(ctx, options) {
36083
+ const { action, fallback } = options;
36084
+ const confirmation = {
36085
+ action,
36086
+ message: options.message,
36087
+ details: options.details,
36088
+ confirmationLabel: options.confirmationLabel,
36089
+ ...options.unsupportedNote ? { unsupportedNote: options.unsupportedNote } : {}
36090
+ };
36091
+ if (!fallback) return requireConfirmationWithFallback(ctx, confirmation);
36092
+ return requireConfirmationWithFallback(ctx, confirmationFromEnv({
36093
+ ...confirmation,
36094
+ tool: fallback.tool,
36095
+ account: fallback.account ?? readEnvVar("GOG_ACCOUNT") ?? "",
36096
+ confirmToken: fallback.confirmToken,
36097
+ subject: fallback.subject,
36098
+ instruction: fallback.instruction ?? CONFIRM_ACTION_INSTRUCTION,
36099
+ spent: confirmSpentStore()
36100
+ }));
36101
+ }
35578
36102
 
35579
36103
  // ../gogcli-mcp/src/tools/auth.ts
35580
36104
  var AUTH_RUN_SUBCOMMANDS = ["list", "status", "services", "remove", "alias"];
@@ -35762,6 +36286,11 @@ var attachInlineParam = external_exports.array(inlineAttachmentSchema).optional(
35762
36286
  );
35763
36287
 
35764
36288
  // ../gogcli-mcp/src/tools/contacts.ts
36289
+ var BATCH_DELETE = /* @__PURE__ */ new Set(["delete"]);
36290
+ function vetContactsRun(subcommand, args) {
36291
+ if (subcommand.toLowerCase() !== "batch" || !hasCommandWord(args, BATCH_DELETE)) return void 0;
36292
+ return gatedElsewhere("gog contacts batch delete", "gog_contacts_run", "deletes contacts for good, with no Trash to restore them from", "gog_contacts_batch_delete");
36293
+ }
35765
36294
  function registerContactsTools(server) {
35766
36295
  server.registerTool("gog_contacts_search", {
35767
36296
  description: "Search personal Google Contacts by name, email, or phone. For searching the Workspace directory (internal users not in your personal contacts), use gog_people_search from gogcli-mcp-contacts.",
@@ -35813,7 +36342,7 @@ function registerContactsTools(server) {
35813
36342
  if (title) args.push(`--title=${title}`);
35814
36343
  return runOrDiagnose(args, { account });
35815
36344
  });
35816
- registerRunTool(server, { service: "contacts", examples: '"update", "delete", "directory"' });
36345
+ registerRunTool(server, { service: "contacts", examples: '"update", "delete", "directory"', vet: vetContactsRun });
35817
36346
  }
35818
36347
 
35819
36348
  // ../gogcli-mcp/src/tools/gmail.ts
@@ -35849,7 +36378,7 @@ var failIfNotEmptyParam = external_exports.boolean().optional().describe(
35849
36378
  );
35850
36379
 
35851
36380
  // ../gogcli-mcp/src/server.ts
35852
- var VERSION = true ? "4.5.1" : "0.0.0";
36381
+ var VERSION = true ? "4.6.0" : "0.0.0";
35853
36382
 
35854
36383
  // ../gogcli-mcp/src/bootstrap-auth.ts
35855
36384
  import { join as join5 } from "node:path";
@@ -35886,12 +36415,12 @@ async function bootstrapGogAuth(env = process.env, options = {}) {
35886
36415
  const [clientId, clientSecret, refreshToken, account] = values;
35887
36416
  const { spawner } = options;
35888
36417
  try {
35889
- const { createHash } = await import("node:crypto");
36418
+ const { createHash: createHash4 } = await import("node:crypto");
35890
36419
  const { mkdir, readFile, writeFile, chmod } = await import("node:fs/promises");
35891
36420
  const home = options.home ?? (await import("node:os")).homedir();
35892
36421
  const dir = join5(home, ".gogcli-mcp");
35893
36422
  const marker = join5(dir, AUTH_BOOTSTRAP_MARKER);
35894
- const fingerprint = createHash("sha256").update(values.join("\0")).digest("hex");
36423
+ const fingerprint = createHash4("sha256").update(values.join("\0")).digest("hex");
35895
36424
  const previous = await readFile(marker, "utf8").catch(() => void 0);
35896
36425
  if (previous === fingerprint && await accountListed(account, spawner)) return "present";
35897
36426
  await run(
@@ -36020,6 +36549,56 @@ function registerExtraContactsTools(server) {
36020
36549
  }, async ({ resourceName, account }) => {
36021
36550
  return runOrDiagnose(["contacts", "delete", pos(resourceName), "--force"], { account });
36022
36551
  });
36552
+ server.registerTool("gog_contacts_batch_get", {
36553
+ description: "Fetch exact Google Contacts by People resource name in native API batches (up to 200).",
36554
+ annotations: { readOnlyHint: true },
36555
+ inputSchema: external_exports.object({ resourceNames: external_exports.array(external_exports.string().min(1)).min(1).max(200).describe("Exact resource names such as people/c123; maximum 200"), account: accountParam })
36556
+ }, async ({ resourceNames, account }) => runOrDiagnose(["contacts", "batch", "get", ...resourceNames.map(pos)], { account }));
36557
+ server.registerTool("gog_contacts_batch_create", {
36558
+ description: "Create Google Contacts in native People API batches (up to 200). peopleJson is a JSON array of People API Person resources. The payload is materialized in a temporary file on the gog host.",
36559
+ // Same kind of write as gog_contacts_create, so the same annotation.
36560
+ annotations: { readOnlyHint: false, destructiveHint: true },
36561
+ inputSchema: external_exports.object({ peopleJson: external_exports.string().describe("JSON array of People API Person resources, up to 200 contacts"), account: accountParam })
36562
+ }, async ({ peopleJson, account }) => {
36563
+ let people;
36564
+ try {
36565
+ people = JSON.parse(peopleJson);
36566
+ } catch {
36567
+ throw new Error("peopleJson must be valid JSON");
36568
+ }
36569
+ if (!Array.isArray(people) || people.length === 0 || people.length > 200) throw new Error("peopleJson must be a non-empty array with at most 200 contacts");
36570
+ return runOrDiagnose(["contacts", "batch", "create", { kind: "file", flag: "from-file", contents: peopleJson, ext: "json" }], { account });
36571
+ });
36572
+ server.registerTool("gog_contacts_batch_update", {
36573
+ description: "Update Google Contacts in native People API batches. peopleByResourceName is a JSON object keyed by People resource name; each value must include the CONTACT source metadata and etag returned by a prior read. gog preserves those etag guards and reports partial progress.",
36574
+ // Overwrites fields like gog_contacts_update, so the same annotation.
36575
+ annotations: { readOnlyHint: false, destructiveHint: true },
36576
+ inputSchema: external_exports.object({ peopleByResourceName: external_exports.string().describe("JSON object keyed by people/... resource name, with Person resources including CONTACT source metadata and etag"), account: accountParam })
36577
+ }, async ({ peopleByResourceName, account }) => {
36578
+ let people;
36579
+ try {
36580
+ people = JSON.parse(peopleByResourceName);
36581
+ } catch {
36582
+ throw new Error("peopleByResourceName must be valid JSON");
36583
+ }
36584
+ if (!people || typeof people !== "object" || Array.isArray(people) || Object.keys(people).length === 0 || Object.keys(people).length > 200) throw new Error("peopleByResourceName must be a JSON object with between 1 and 200 contacts");
36585
+ return runOrDiagnose(["contacts", "batch", "update", { kind: "file", flag: "from-file", contents: peopleByResourceName, ext: "json" }], { account });
36586
+ });
36587
+ server.registerTool("gog_contacts_batch_delete", {
36588
+ description: "Permanently delete exact Google Contacts in native People API batches (up to 500). Requires explicit user confirmation; deleted contacts cannot be restored from Trash.",
36589
+ annotations: { destructiveHint: true },
36590
+ inputSchema: external_exports.object({ resourceNames: external_exports.array(external_exports.string().min(1)).min(1).max(500).describe("Exact People resource names; maximum 500"), account: accountParam, confirmToken: confirmTokenParam })
36591
+ }, async ({ resourceNames, account, confirmToken }, ctx) => {
36592
+ const confirmation = await requireDispatchConfirmation(ctx, {
36593
+ action: "contacts.batch-delete",
36594
+ message: "Review and confirm permanent deletion of these Google Contacts:",
36595
+ confirmationLabel: "Confirm permanent deletion of the listed contacts.",
36596
+ details: { resourceNames },
36597
+ fallback: { tool: "gog_contacts_batch_delete", account, confirmToken, subject: () => ({ target: "contacts", payload: { resourceNames }, preview: { resourceNames } }) }
36598
+ });
36599
+ if (confirmation) return confirmation;
36600
+ return runOrDiagnose(["contacts", "batch", "delete", ...resourceNames.map(pos), "--force"], { account });
36601
+ });
36023
36602
  server.registerTool("gog_contacts_export", {
36024
36603
  description: "Export contacts as vCard (.vcf). Provide a selector (resource name, email, or name), or use query / all to export multiple.",
36025
36604
  // Writes a file on the gog host and can overwrite one: not read-only (audit SEC-4).
@@ -36142,7 +36721,7 @@ await runMcp({
36142
36721
  });
36143
36722
  /*! Bundled license information:
36144
36723
 
36145
- @modelcontextprotocol/server/dist/src-CX2iR2pK.mjs:
36724
+ @modelcontextprotocol/server/dist/src-D-y6h4N7.mjs:
36146
36725
  (*!
36147
36726
  * content-type
36148
36727
  * Copyright(c) 2015 Douglas Christopher Wilson
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.5.1",
6
+ "version": "4.6.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",
@@ -160,6 +160,22 @@
160
160
  {
161
161
  "name": "gog_contacts_other_search",
162
162
  "description": "Search auto-collected other contacts"
163
+ },
164
+ {
165
+ "name": "gog_contacts_batch_get",
166
+ "description": "Fetch exact Contacts in native People API batches."
167
+ },
168
+ {
169
+ "name": "gog_contacts_batch_create",
170
+ "description": "Create Contacts in native People API batches."
171
+ },
172
+ {
173
+ "name": "gog_contacts_batch_update",
174
+ "description": "Update Contacts in native People API batches with etag guards."
175
+ },
176
+ {
177
+ "name": "gog_contacts_batch_delete",
178
+ "description": "Permanently delete Contacts in native People API batches after confirmation."
163
179
  }
164
180
  ],
165
181
  "compatibility": {
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.41.0
95
+ tag: v0.43.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.5.1",
3
+ "version": "4.6.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>",
@@ -25,7 +25,7 @@
25
25
  },
26
26
  "dependencies": {
27
27
  "@chrischall/mcp-utils": "^2.6.0",
28
- "@modelcontextprotocol/server": "^2.0.0",
28
+ "@modelcontextprotocol/server": "^2.1.0",
29
29
  "zod": "^4.6.1"
30
30
  },
31
31
  "license": "MIT",
@@ -1,6 +1,6 @@
1
1
  import { McpServer } from '@modelcontextprotocol/server';
2
2
  import { z } from 'zod';
3
- import { accountParam, runOrDiagnose, pageTokenParam, pageAliasParam, resolvePageToken, pos, confinePath } from '../../../gogcli-mcp/src/lib.js';
3
+ import { accountParam, runOrDiagnose, pageTokenParam, pageAliasParam, resolvePageToken, pos, confinePath, confirmTokenParam, requireDispatchConfirmation } from '../../../gogcli-mcp/src/lib.js';
4
4
  import type { GogArg } from '../../../gogcli-mcp/src/lib.js';
5
5
 
6
6
  // People is the richer API behind Google Contacts: Workspace directory
@@ -107,6 +107,52 @@ export function registerExtraContactsTools(server: McpServer): void {
107
107
  return runOrDiagnose(['contacts', 'delete', pos(resourceName), '--force'], { account }); // gog gates this op; without --force the runner's --no-input makes it refuse
108
108
  });
109
109
 
110
+ server.registerTool('gog_contacts_batch_get', {
111
+ description: 'Fetch exact Google Contacts by People resource name in native API batches (up to 200).',
112
+ annotations: { readOnlyHint: true },
113
+ inputSchema: z.object({ resourceNames: z.array(z.string().min(1)).min(1).max(200).describe('Exact resource names such as people/c123; maximum 200'), account: accountParam }),
114
+ }, async ({ resourceNames, account }) => runOrDiagnose(['contacts', 'batch', 'get', ...resourceNames.map(pos)], { account }));
115
+
116
+ server.registerTool('gog_contacts_batch_create', {
117
+ description: 'Create Google Contacts in native People API batches (up to 200). peopleJson is a JSON array of People API Person resources. The payload is materialized in a temporary file on the gog host.',
118
+ // Same kind of write as gog_contacts_create, so the same annotation.
119
+ annotations: { readOnlyHint: false, destructiveHint: true },
120
+ inputSchema: z.object({ peopleJson: z.string().describe('JSON array of People API Person resources, up to 200 contacts'), account: accountParam }),
121
+ }, async ({ peopleJson, account }) => {
122
+ let people: unknown;
123
+ try { people = JSON.parse(peopleJson); } catch { throw new Error('peopleJson must be valid JSON'); }
124
+ if (!Array.isArray(people) || people.length === 0 || people.length > 200) throw new Error('peopleJson must be a non-empty array with at most 200 contacts');
125
+ return runOrDiagnose(['contacts', 'batch', 'create', { kind: 'file', flag: 'from-file', contents: peopleJson, ext: 'json' }], { account });
126
+ });
127
+
128
+ server.registerTool('gog_contacts_batch_update', {
129
+ description: 'Update Google Contacts in native People API batches. peopleByResourceName is a JSON object keyed by People resource name; each value must include the CONTACT source metadata and etag returned by a prior read. gog preserves those etag guards and reports partial progress.',
130
+ // Overwrites fields like gog_contacts_update, so the same annotation.
131
+ annotations: { readOnlyHint: false, destructiveHint: true },
132
+ inputSchema: z.object({ peopleByResourceName: z.string().describe('JSON object keyed by people/... resource name, with Person resources including CONTACT source metadata and etag'), account: accountParam }),
133
+ }, async ({ peopleByResourceName, account }) => {
134
+ let people: unknown;
135
+ try { people = JSON.parse(peopleByResourceName); } catch { throw new Error('peopleByResourceName must be valid JSON'); }
136
+ if (!people || typeof people !== 'object' || Array.isArray(people) || Object.keys(people).length === 0 || Object.keys(people).length > 200) throw new Error('peopleByResourceName must be a JSON object with between 1 and 200 contacts');
137
+ return runOrDiagnose(['contacts', 'batch', 'update', { kind: 'file', flag: 'from-file', contents: peopleByResourceName, ext: 'json' }], { account });
138
+ });
139
+
140
+ server.registerTool('gog_contacts_batch_delete', {
141
+ description: 'Permanently delete exact Google Contacts in native People API batches (up to 500). Requires explicit user confirmation; deleted contacts cannot be restored from Trash.',
142
+ annotations: { destructiveHint: true },
143
+ inputSchema: z.object({ resourceNames: z.array(z.string().min(1)).min(1).max(500).describe('Exact People resource names; maximum 500'), account: accountParam, confirmToken: confirmTokenParam }),
144
+ }, async ({ resourceNames, account, confirmToken }, ctx) => {
145
+ const confirmation = await requireDispatchConfirmation(ctx, {
146
+ action: 'contacts.batch-delete',
147
+ message: 'Review and confirm permanent deletion of these Google Contacts:',
148
+ confirmationLabel: 'Confirm permanent deletion of the listed contacts.',
149
+ details: { resourceNames },
150
+ fallback: { tool: 'gog_contacts_batch_delete', account, confirmToken, subject: () => ({ target: 'contacts', payload: { resourceNames }, preview: { resourceNames } }) },
151
+ });
152
+ if (confirmation) return confirmation;
153
+ return runOrDiagnose(['contacts', 'batch', 'delete', ...resourceNames.map(pos), '--force'], { account });
154
+ });
155
+
110
156
  server.registerTool('gog_contacts_export', {
111
157
  description: 'Export contacts as vCard (.vcf). Provide a selector (resource name, email, or name), or use query / all to export multiple.',
112
158
  // Writes a file on the gog host and can overwrite one: not read-only (audit SEC-4).
@@ -120,6 +120,73 @@ describe('gog_contacts_delete', () => {
120
120
  });
121
121
  });
122
122
 
123
+ describe('native batched Contacts tools', () => {
124
+ it('fetches exact resource names in one command', async () => {
125
+ await harness.callTool('gog_contacts_batch_get', { resourceNames: ['people/a', 'people/b'] });
126
+ expect(lib.runOrDiagnose).toHaveBeenCalledWith(['contacts', 'batch', 'get', pos('people/a'), pos('people/b')], { account: undefined });
127
+ });
128
+
129
+ it('materializes a validated create array as a JSON file argument', async () => {
130
+ const peopleJson = '[{"names":[{"givenName":"Ada"}]}]';
131
+ await harness.callTool('gog_contacts_batch_create', { peopleJson });
132
+ expect(lib.runOrDiagnose).toHaveBeenCalledWith([
133
+ 'contacts', 'batch', 'create', { kind: 'file', flag: 'from-file', contents: peopleJson, ext: 'json' },
134
+ ], { account: undefined });
135
+ });
136
+
137
+ it('rejects invalid create JSON before invoking gog', async () => {
138
+ const result = await harness.callTool('gog_contacts_batch_create', { peopleJson: '{' });
139
+ expect(result.isError).toBe(true);
140
+ expect(lib.runOrDiagnose).not.toHaveBeenCalled();
141
+ });
142
+
143
+ it('rejects an empty or non-array create payload', async () => {
144
+ expect((await harness.callTool('gog_contacts_batch_create', { peopleJson: '{}' })).isError).toBe(true);
145
+ expect((await harness.callTool('gog_contacts_batch_create', { peopleJson: '[]' })).isError).toBe(true);
146
+ expect((await harness.callTool('gog_contacts_batch_create', { peopleJson: JSON.stringify(Array(201).fill({})) })).isError).toBe(true);
147
+ expect(lib.runOrDiagnose).not.toHaveBeenCalled();
148
+ });
149
+
150
+ it('materializes an update map and preserves the account', async () => {
151
+ const peopleByResourceName = '{"people/a":{"etag":"x"}}';
152
+ await harness.callTool('gog_contacts_batch_update', { peopleByResourceName, account: 'a@b.com' });
153
+ expect(lib.runOrDiagnose).toHaveBeenCalledWith([
154
+ 'contacts', 'batch', 'update', { kind: 'file', flag: 'from-file', contents: peopleByResourceName, ext: 'json' },
155
+ ], { account: 'a@b.com' });
156
+ });
157
+
158
+ it('rejects invalid or empty update maps', async () => {
159
+ expect((await harness.callTool('gog_contacts_batch_update', { peopleByResourceName: '{' })).isError).toBe(true);
160
+ expect((await harness.callTool('gog_contacts_batch_update', { peopleByResourceName: '[]' })).isError).toBe(true);
161
+ expect((await harness.callTool('gog_contacts_batch_update', { peopleByResourceName: '{}' })).isError).toBe(true);
162
+ const tooMany = Object.fromEntries(Array.from({ length: 201 }, (_, i) => [`people/${i}`, {}]));
163
+ expect((await harness.callTool('gog_contacts_batch_update', { peopleByResourceName: JSON.stringify(tooMany) })).isError).toBe(true);
164
+ expect(lib.runOrDiagnose).not.toHaveBeenCalled();
165
+ });
166
+
167
+ it('requires confirmation and then forces the guarded permanent delete', async () => {
168
+ const confirmed = await createTestHarness(registerExtraContactsTools, {
169
+ elicitation: async () => ({ action: 'accept', content: { confirmed: true } }),
170
+ });
171
+ await confirmed.callTool('gog_contacts_batch_delete', { resourceNames: ['people/a', 'people/b'] });
172
+ expect(lib.runOrDiagnose).toHaveBeenCalledWith([
173
+ 'contacts', 'batch', 'delete', pos('people/a'), pos('people/b'), '--force',
174
+ ], { account: undefined });
175
+ });
176
+
177
+ it('allows an unprompted client to confirm the exact batch with a one-time token', async () => {
178
+ process.env.MCP_CONFIRM_MODE = 'ask-user';
179
+ const unprompted = await createTestHarness(registerExtraContactsTools);
180
+ const args = { resourceNames: ['people/a'] };
181
+ const prompt = await unprompted.callTool('gog_contacts_batch_delete', args);
182
+ const payload = JSON.parse(prompt.content[0].text);
183
+ await unprompted.callTool('gog_contacts_batch_delete', { ...args, confirmToken: payload.confirmToken });
184
+ expect(lib.runOrDiagnose).toHaveBeenCalledWith(
185
+ ['contacts', 'batch', 'delete', pos('people/a'), '--force'], { account: undefined });
186
+ delete process.env.MCP_CONFIRM_MODE;
187
+ });
188
+ });
189
+
123
190
  describe('gog_contacts_export', () => {
124
191
  it('calls runOrDiagnose with no options', async () => {
125
192
  await harness.callTool('gog_contacts_export', {});