@togglhq/mcp 1.12.7 → 1.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10865,7 +10865,7 @@ var require_localDisplayPath = /* @__PURE__ */ __commonJSMin$1(((exports, module
10865
10865
  module.exports = localDisplayPath;
10866
10866
  }));
10867
10867
  //#endregion
10868
- //#region ../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs
10868
+ //#region ../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.0/node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs
10869
10869
  var import_main = /* @__PURE__ */ __toESM$1((/* @__PURE__ */ __commonJSMin$1(((exports, module) => {
10870
10870
  const path$1 = __require("path");
10871
10871
  const { setLogLevel, setLogName, setLogVersion, logger } = require_logger();
@@ -11078,7 +11078,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
11078
11078
  enumerable: true
11079
11079
  }) : target, mod));
11080
11080
  //#endregion
11081
- //#region ../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/dialects-DoSzNhcb.mjs
11081
+ //#region ../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.0/node_modules/@modelcontextprotocol/server/dist/dialects-DoSzNhcb.mjs
11082
11082
  /**
11083
11083
  * Canonical `$schema` URIs per supported dialect (http + https variants, trailing-`#` stripped).
11084
11084
  */
@@ -16852,7 +16852,8 @@ const OAuthMetadataSchema = looseObject$1({
16852
16852
  introspection_endpoint_auth_signing_alg_values_supported: array$2(string$2()).optional(),
16853
16853
  code_challenge_methods_supported: array$2(string$2()).optional(),
16854
16854
  client_id_metadata_document_supported: boolean$2().optional(),
16855
- authorization_response_iss_parameter_supported: boolean$2().optional().catch(void 0)
16855
+ authorization_response_iss_parameter_supported: boolean$2().optional().catch(void 0),
16856
+ dpop_signing_alg_values_supported: array$2(string$2()).optional()
16856
16857
  });
16857
16858
  /**
16858
16859
  * OpenID Connect Discovery 1.0 Provider Metadata
@@ -16916,7 +16917,8 @@ const OAuthTokensSchema = object$1({
16916
16917
  token_type: string$2(),
16917
16918
  expires_in: number$1().optional(),
16918
16919
  scope: string$2().optional(),
16919
- refresh_token: string$2().optional()
16920
+ refresh_token: string$2().optional(),
16921
+ issuer: string$2().optional().catch(void 0)
16920
16922
  }).strip();
16921
16923
  /**
16922
16924
  * RFC 8693 §2.2.1 Token Exchange response for ID-JAG tokens.
@@ -16973,7 +16975,8 @@ const OAuthClientInformationSchema = object$1({
16973
16975
  client_id: string$2(),
16974
16976
  client_secret: string$2().optional(),
16975
16977
  client_id_issued_at: number$3().optional(),
16976
- client_secret_expires_at: number$3().optional()
16978
+ client_secret_expires_at: number$3().optional(),
16979
+ issuer: string$2().optional().catch(void 0)
16977
16980
  }).strip();
16978
16981
  /**
16979
16982
  * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata)
@@ -16994,7 +16997,7 @@ const OAuthTokenRevocationRequestSchema = object$1({
16994
16997
  token_type_hint: string$2().optional()
16995
16998
  }).strip();
16996
16999
  //#endregion
16997
- //#region ../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/src-CX2iR2pK.mjs
17000
+ //#region ../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.0/node_modules/@modelcontextprotocol/server/dist/src-Cqbh3MYc.mjs
16998
17001
  /**
16999
17002
  * Cross-bundle `instanceof` support for the SDK error classes.
17000
17003
  *
@@ -17259,8 +17262,18 @@ var SdkError = class extends Error {
17259
17262
  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)`");
17260
17263
  return brandedHasInstance(this, value);
17261
17264
  }
17262
- constructor(code, message, data) {
17263
- super(message);
17265
+ /**
17266
+ * @param code - Stable string code identifying the failure ({@linkcode SdkErrorCode}).
17267
+ * @param message - Human-readable description.
17268
+ * @param data - Optional structured payload (for example the HTTP status carried by
17269
+ * {@linkcode SdkHttpError}). Opaque to the SDK: a `cause` key inside `data` is not
17270
+ * promoted to `Error.cause`.
17271
+ * @param options - Standard `ErrorOptions`, forwarded to `Error`. Pass the underlying
17272
+ * failure as `{ cause }` so it is reachable through the `Error.cause` chain that
17273
+ * loggers and error trackers walk.
17274
+ */
17275
+ constructor(code, message, data, options) {
17276
+ super(message, options);
17264
17277
  this.code = code;
17265
17278
  this.data = data;
17266
17279
  this.name = "SdkError";
@@ -17271,8 +17284,11 @@ var SdkError = class extends Error {
17271
17284
  static {
17272
17285
  Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkHttpError" });
17273
17286
  }
17274
- constructor(code, message, data) {
17275
- super(code, message, data);
17287
+ /**
17288
+ * @param options - Standard `ErrorOptions`, forwarded to `Error` (see {@linkcode SdkError}).
17289
+ */
17290
+ constructor(code, message, data, options) {
17291
+ super(code, message, data, options);
17276
17292
  this.name = "SdkHttpError";
17277
17293
  }
17278
17294
  get status() {
@@ -19930,7 +19946,7 @@ function build() {
19930
19946
  const subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema$1 };
19931
19947
  const SubscriptionsListenRequestSchema$1 = wireRequest("subscriptions/listen", subscriptionsListenParamsShape);
19932
19948
  /**
19933
- * Anchor SubscriptionsListenResultMeta — required subscriptionId stamp on
19949
+ * Anchor SubscriptionsListenResultMetaObject — required subscriptionId stamp on
19934
19950
  * the graceful-close result. Extends `ResultMetaObject` since spec PR
19935
19951
  * #3002 (composed, so the serverInfo key and its leniency stay single-sourced).
19936
19952
  */
@@ -20203,7 +20219,8 @@ function build() {
20203
20219
  ListResourceTemplatesResultResponseSchema: wireResultResponse(ListResourceTemplatesResultSchema$1),
20204
20220
  ReadResourceResultResponseSchema: wireResultResponse(union$2([ReadResourceResultSchema$1, InputRequiredResultSchema])),
20205
20221
  CompleteResultResponseSchema: wireResultResponse(CompleteResultSchema$1),
20206
- DiscoverResultResponseSchema: wireResultResponse(DiscoverResultSchema$1)
20222
+ DiscoverResultResponseSchema: wireResultResponse(DiscoverResultSchema$1),
20223
+ SubscriptionsListenResultResponseSchema: wireResultResponse(SubscriptionsListenResultSchema$1)
20207
20224
  };
20208
20225
  }
20209
20226
  let memo;
@@ -20834,6 +20851,8 @@ const rev2026Codec = {
20834
20851
  const rawInputRequests = raw["inputRequests"];
20835
20852
  const inputRequests = isPlainObject$4(rawInputRequests) ? rawInputRequests : {};
20836
20853
  const requestState = raw["requestState"];
20854
+ const metaParse = raw["_meta"] === void 0 ? void 0 : buildSchemas2026().ResultMetaSchema.safeParse(raw["_meta"]);
20855
+ const meta = metaParse?.success ? metaParse.data : void 0;
20837
20856
  if (Object.keys(inputRequests).length === 0 && typeof requestState !== "string") return {
20838
20857
  kind: "invalid",
20839
20858
  error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`, {
@@ -20844,7 +20863,8 @@ const rev2026Codec = {
20844
20863
  return {
20845
20864
  kind: "input_required",
20846
20865
  inputRequests,
20847
- ...typeof requestState === "string" && { requestState }
20866
+ ...typeof requestState === "string" && { requestState },
20867
+ ...meta !== void 0 && { _meta: meta }
20848
20868
  };
20849
20869
  }
20850
20870
  if (rawResultType !== "complete") return {
@@ -20942,6 +20962,10 @@ function isSpecRequestMethod(method) {
20942
20962
  function isSpecNotificationMethod(method) {
20943
20963
  return ALL_CODECS.some((codec) => codec.hasNotificationMethod(method));
20944
20964
  }
20965
+ /** The names SEP-2663 re-defines for the Tasks extension on the era that removed them from core. */
20966
+ function isExtensionReusedRequestMethod(method) {
20967
+ return method === "tasks/get" || method === "tasks/cancel";
20968
+ }
20945
20969
  const ALL_CODECS = [rev2025Codec, rev2026Codec];
20946
20970
  /**
20947
20971
  * Per-request `_meta` envelope claim helpers (protocol revision 2026-07-28).
@@ -22111,6 +22135,8 @@ var Protocol = class {
22111
22135
  _transport;
22112
22136
  _requestMessageId = 0;
22113
22137
  _requestHandlers = /* @__PURE__ */ new Map();
22138
+ /** Methods registered with an explicit schema; the era gate in `_onrequest` reads it for the Tasks extension names. */
22139
+ _customSchemaRequestMethods = /* @__PURE__ */ new Set();
22114
22140
  _requestHandlerAbortControllers = /* @__PURE__ */ new Map();
22115
22141
  _notificationHandlers = /* @__PURE__ */ new Map();
22116
22142
  _responseHandlers = /* @__PURE__ */ new Map();
@@ -22245,7 +22271,7 @@ var Protocol = class {
22245
22271
  return this._requestHandlers.get(method);
22246
22272
  }
22247
22273
  async _oncancel(notification) {
22248
- if (!notification.params.requestId) return;
22274
+ if (notification.params.requestId === void 0) return;
22249
22275
  this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason);
22250
22276
  }
22251
22277
  _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
@@ -22392,7 +22418,7 @@ var Protocol = class {
22392
22418
  return;
22393
22419
  }
22394
22420
  }
22395
- if (isSpecRequestMethod(request.method) && !codec.hasRequestMethod(request.method)) {
22421
+ if (isSpecRequestMethod(request.method) && !codec.hasRequestMethod(request.method) && !(isExtensionReusedRequestMethod(request.method) && this._customSchemaRequestMethods.has(request.method))) {
22396
22422
  sendErrorResponse(ProtocolErrorCode.MethodNotFound, "Method not found");
22397
22423
  return;
22398
22424
  }
@@ -22525,8 +22551,11 @@ var Protocol = class {
22525
22551
  }
22526
22552
  request(request, schemaOrOptions, maybeOptions) {
22527
22553
  const codec = this._resolveOutboundCodec(request.method);
22554
+ if (isStandardSchema(schemaOrOptions)) {
22555
+ if (!isExtensionReusedRequestMethod(request.method)) this._assertOutboundRequestInEra(codec, request.method);
22556
+ return this._requestWithSchemaViaCodec(codec, request, schemaOrOptions, maybeOptions);
22557
+ }
22528
22558
  this._assertOutboundRequestInEra(codec, request.method);
22529
- if (isStandardSchema(schemaOrOptions)) return this._requestWithSchemaViaCodec(codec, request, schemaOrOptions, maybeOptions);
22530
22559
  const validate = codecResultValidator(codec, request.method);
22531
22560
  if (validate === void 0) throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`);
22532
22561
  return this._requestWithSchemaViaCodec(codec, request, validate, schemaOrOptions);
@@ -22644,19 +22673,20 @@ var Protocol = class {
22644
22673
  const cancel = (reason) => {
22645
22674
  if (responseReceived) return;
22646
22675
  this._progressHandlers.delete(messageId);
22647
- if (requestAbort === void 0) this._transport?.send(this._envelopeOutbound({
22648
- jsonrpc: "2.0",
22649
- method: "notifications/cancelled",
22650
- params: {
22651
- requestId: messageId,
22652
- reason: String(reason)
22653
- }
22654
- }), {
22655
- relatedRequestId,
22656
- resumptionToken,
22657
- onresumptiontoken
22658
- }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error}`)));
22659
- else requestAbort.abort();
22676
+ if (requestAbort === void 0) {
22677
+ if (request.method !== "initialize") this._transport?.send(this._envelopeOutbound({
22678
+ jsonrpc: "2.0",
22679
+ method: "notifications/cancelled",
22680
+ params: {
22681
+ requestId: messageId,
22682
+ reason: String(reason)
22683
+ }
22684
+ }), {
22685
+ relatedRequestId,
22686
+ resumptionToken,
22687
+ onresumptiontoken
22688
+ }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error}`)));
22689
+ } else requestAbort.abort();
22660
22690
  reject(reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason)));
22661
22691
  };
22662
22692
  this._responseHandlers.set(messageId, (response) => {
@@ -22718,7 +22748,7 @@ var Protocol = class {
22718
22748
  * Emits a notification, which is a one-way message that does not expect a response.
22719
22749
  */
22720
22750
  async notification(notification, options) {
22721
- return this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, options);
22751
+ return await this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, options);
22722
22752
  }
22723
22753
  /**
22724
22754
  * The notification funnel proper, keyed by the resolved era codec —
@@ -22736,7 +22766,7 @@ var Protocol = class {
22736
22766
  jsonrpc: "2.0",
22737
22767
  ...notification
22738
22768
  });
22739
- if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && !options?.relatedRequestId) {
22769
+ if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && options?.relatedRequestId === void 0) {
22740
22770
  if (this._pendingDebouncedNotifications.has(notification.method)) return;
22741
22771
  this._pendingDebouncedNotifications.add(notification.method);
22742
22772
  Promise.resolve().then(() => {
@@ -22769,6 +22799,8 @@ var Protocol = class {
22769
22799
  return maybeHandler(parsed.data, ctx);
22770
22800
  };
22771
22801
  else throw new TypeError("setRequestHandler: handler is required");
22802
+ if (typeof schemasOrHandler === "function") this._customSchemaRequestMethods.delete(method);
22803
+ else this._customSchemaRequestMethods.add(method);
22772
22804
  this._requestHandlers.set(method, this._wrapHandler(method, stored));
22773
22805
  }
22774
22806
  /**
@@ -22797,6 +22829,7 @@ var Protocol = class {
22797
22829
  */
22798
22830
  removeRequestHandler(method) {
22799
22831
  this._requestHandlers.delete(method);
22832
+ this._customSchemaRequestMethods.delete(method);
22800
22833
  }
22801
22834
  /**
22802
22835
  * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.
@@ -22887,7 +22920,8 @@ function manualInputRequiredValue(decoded) {
22887
22920
  return {
22888
22921
  resultType: "input_required",
22889
22922
  inputRequests: decoded.inputRequests,
22890
- ...decoded.requestState !== void 0 && { requestState: decoded.requestState }
22923
+ ...decoded.requestState !== void 0 && { requestState: decoded.requestState },
22924
+ ...decoded._meta !== void 0 && { _meta: decoded._meta }
22891
22925
  };
22892
22926
  }
22893
22927
  (/* @__PURE__ */ __commonJSMin(((exports) => {
@@ -23134,7 +23168,7 @@ function normalizeRawShapeSchema(schema) {
23134
23168
  return schema;
23135
23169
  }
23136
23170
  //#endregion
23137
- //#region ../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/ajvProvider-CEoC__sr.mjs
23171
+ //#region ../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.0/node_modules/@modelcontextprotocol/server/dist/ajvProvider-CEoC__sr.mjs
23138
23172
  var require_code$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
23139
23173
  Object.defineProperty(exports, "__esModule", { value: true });
23140
23174
  exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;
@@ -30269,7 +30303,7 @@ var AjvJsonSchemaValidator = class {
30269
30303
  };
30270
30304
  import_ajv.Ajv;
30271
30305
  //#endregion
30272
- //#region ../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/mcp-DXXb3Vv3.mjs
30306
+ //#region ../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.0/node_modules/@modelcontextprotocol/server/dist/mcp-DIH4cS6P.mjs
30273
30307
  const COMPLETABLE_SYMBOL = Symbol.for("mcp.completable");
30274
30308
  /**
30275
30309
  * Checks if a schema is completable (has completion metadata).
@@ -30379,7 +30413,7 @@ var StdioListenRouter = class {
30379
30413
  _serverCapabilities;
30380
30414
  /**
30381
30415
  * The serving instance's identity, stamped onto the graceful-close
30382
- * results' `_meta` (the spec's `SubscriptionsListenResultMeta` extends
30416
+ * results' `_meta` (the spec's `SubscriptionsListenResultMetaObject` extends
30383
30417
  * `ResultMetaObject`). Handed over together with the capabilities.
30384
30418
  */
30385
30419
  _serverInfo;
@@ -30503,6 +30537,10 @@ function notificationToServerEvent(method, uri) {
30503
30537
  };
30504
30538
  }
30505
30539
  }
30540
+ /** @internal */
30541
+ function supportsScopeChallengeResolver(transport) {
30542
+ return typeof transport === "object" && transport !== null && "setScopeChallengeResolver" in transport && typeof transport.setScopeChallengeResolver === "function";
30543
+ }
30506
30544
  /**
30507
30545
  * Default handler re-entries per originating request — tighter than the
30508
30546
  * client driver's 10 because the shim holds a live wire request open.
@@ -30675,7 +30713,7 @@ function installModernOnlyHandlers(server, servedModernVersions) {
30675
30713
  * Package-internal: the instance's implementation identity, for the serving
30676
30714
  * entries to stamp onto entry-built results (the `subscriptions/listen`
30677
30715
  * graceful-close result — built outside the encode seam, but the spec's
30678
- * `SubscriptionsListenResultMeta` extends `ResultMetaObject`, so it carries
30716
+ * `SubscriptionsListenResultMetaObject` extends `ResultMetaObject`, so it carries
30679
30717
  * the serverInfo SHOULD like every other result). Not public API.
30680
30718
  */
30681
30719
  function serverIdentityOf(server) {
@@ -30742,6 +30780,11 @@ var Server = class extends Protocol {
30742
30780
  if (modernProtocolVersions(this._supportedProtocolVersions).length > 0) this.setRequestHandler("server/discover", () => this._ondiscover());
30743
30781
  if (this._capabilities.logging) this._registerLoggingHandler();
30744
30782
  }
30783
+ /** Attaches to the given transport; rejects while this instance is connected to another one. */
30784
+ async connect(transport) {
30785
+ if (this.transport !== void 0) throw new SdkError(SdkErrorCode.AlreadyConnected, "Use a separate Server instance per connection: this instance is already connected to a transport. To connect it to a new transport, call close() first.");
30786
+ await super.connect(transport);
30787
+ }
30745
30788
  /**
30746
30789
  * Registers the built-in `logging/setLevel` request handler.
30747
30790
  *
@@ -31300,6 +31343,30 @@ var Server = class extends Protocol {
31300
31343
  function discoverAdvertisedCapabilities(capabilities) {
31301
31344
  return { ...capabilities };
31302
31345
  }
31346
+ function toolInputElementCount(value, max) {
31347
+ let count = 0;
31348
+ const stack = [value];
31349
+ while (stack.length > 0) {
31350
+ const node = stack.pop();
31351
+ if (node === null || typeof node !== "object") continue;
31352
+ if (Array.isArray(node)) for (const child of node) {
31353
+ if (++count > max) return count;
31354
+ if (child !== null && typeof child === "object") stack.push(child);
31355
+ }
31356
+ else for (const key in node) {
31357
+ if (!Object.prototype.hasOwnProperty.call(node, key)) continue;
31358
+ if (++count > max) return count;
31359
+ const child = node[key];
31360
+ if (child !== null && typeof child === "object") stack.push(child);
31361
+ }
31362
+ }
31363
+ return count;
31364
+ }
31365
+ function resolveMaxToolInputElements(value) {
31366
+ if (value === void 0 || value === Infinity) return void 0;
31367
+ if (typeof value !== "number" || Number.isNaN(value) || value < 1) throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(value)}`);
31368
+ return value;
31369
+ }
31303
31370
  /**
31304
31371
  * High-level MCP server that provides a simpler API for working with resources, tools, and prompts.
31305
31372
  * For advanced usage (like sending notifications or setting custom request handlers), use the underlying
@@ -31318,16 +31385,12 @@ var McpServer = class {
31318
31385
  * The underlying {@linkcode Server} instance, useful for advanced operations like sending notifications.
31319
31386
  */
31320
31387
  server;
31388
+ _maxToolInputElements;
31321
31389
  _registeredResources = {};
31322
31390
  _registeredResourceTemplates = {};
31323
31391
  _registeredTools = {};
31324
31392
  _registeredPrompts = {};
31325
- /**
31326
- * Per-tool JSON-converted `inputSchema`, memoized so the SEP-2243
31327
- * registration-time scan and the pre-dispatch validation step share one
31328
- * conversion instead of paying it twice per request under the
31329
- * per-request-factory `createMcpHandler` model.
31330
- */
31393
+ /** Per-tool JSON-converted `inputSchema`, filled on first use by `toolInputSchemaJson()`. */
31331
31394
  _toolInputSchemaJson = {};
31332
31395
  /**
31333
31396
  * The JSON-serialized `inputSchema` of a registered tool, or `undefined`
@@ -31352,6 +31415,7 @@ var McpServer = class {
31352
31415
  }
31353
31416
  constructor(serverInfo, options) {
31354
31417
  this.server = new Server(serverInfo, options);
31418
+ this._maxToolInputElements = resolveMaxToolInputElements(options?.maxToolInputElements);
31355
31419
  if (options?.capabilities?.tools) this.setToolRequestHandlers();
31356
31420
  if (options?.capabilities?.resources) this.setResourceRequestHandlers();
31357
31421
  if (options?.capabilities?.prompts) this.setPromptRequestHandlers();
@@ -31369,6 +31433,7 @@ var McpServer = class {
31369
31433
  * ```
31370
31434
  */
31371
31435
  async connect(transport) {
31436
+ if (supportsScopeChallengeResolver(transport)) transport.setScopeChallengeResolver((context) => this.resolveScopeChallenge(context));
31372
31437
  return await this.server.connect(transport);
31373
31438
  }
31374
31439
  /**
@@ -31377,6 +31442,40 @@ var McpServer = class {
31377
31442
  async close() {
31378
31443
  await this.server.close();
31379
31444
  }
31445
+ /** @internal */
31446
+ resolveScopeChallenge = (context) => {
31447
+ switch (context.request.method) {
31448
+ case "tools/call": {
31449
+ const toolName = context.request.params?.name;
31450
+ if (typeof toolName !== "string") return;
31451
+ const tool = this._registeredTools[toolName];
31452
+ if (tool === void 0 || !tool.enabled) return;
31453
+ return tool.scopeChallenge?.(context);
31454
+ }
31455
+ case "resources/read": {
31456
+ const resourceUri = context.request.params?.uri;
31457
+ if (typeof resourceUri !== "string") return;
31458
+ let uri;
31459
+ try {
31460
+ uri = new URL(resourceUri);
31461
+ } catch {
31462
+ return;
31463
+ }
31464
+ const resource = this._registeredResources[uri.toString()];
31465
+ if (resource !== void 0) return resource.enabled ? resource.scopeChallenge?.(context) : void 0;
31466
+ for (const template of Object.values(this._registeredResourceTemplates)) if (template.resourceTemplate.uriTemplate.match(uri.toString())) return template.enabled ? template.scopeChallenge?.(context) : void 0;
31467
+ return;
31468
+ }
31469
+ case "prompts/get": {
31470
+ const promptName = context.request.params?.name;
31471
+ if (typeof promptName !== "string") return;
31472
+ const prompt = this._registeredPrompts[promptName];
31473
+ if (prompt === void 0 || !prompt.enabled) return;
31474
+ return prompt.scopeChallenge?.(context);
31475
+ }
31476
+ default: return;
31477
+ }
31478
+ };
31380
31479
  _toolHandlersInitialized = false;
31381
31480
  setToolRequestHandlers() {
31382
31481
  if (this._toolHandlersInitialized) return;
@@ -31388,7 +31487,7 @@ var McpServer = class {
31388
31487
  name,
31389
31488
  title: tool.title,
31390
31489
  description: tool.description,
31391
- inputSchema: tool.inputSchema ? standardSchemaToJsonSchema(tool.inputSchema, "input") : EMPTY_OBJECT_JSON_SCHEMA,
31490
+ inputSchema: tool.inputSchema ? convertListedInputSchema(name, tool.inputSchema) : EMPTY_OBJECT_JSON_SCHEMA,
31392
31491
  annotations: tool.annotations,
31393
31492
  icons: tool.icons,
31394
31493
  execution: tool.execution,
@@ -31433,6 +31532,7 @@ var McpServer = class {
31433
31532
  * Validates tool input arguments against the tool's input schema.
31434
31533
  */
31435
31534
  async validateToolInput(tool, args, toolName) {
31535
+ if (this._maxToolInputElements !== void 0 && toolInputElementCount(args, this._maxToolInputElements) > this._maxToolInputElements) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid arguments for tool ${toolName}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);
31436
31536
  if (!tool.inputSchema) return;
31437
31537
  const parseResult = await validateStandardSchema(tool.inputSchema, args ?? {});
31438
31538
  if (!parseResult.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`);
@@ -31542,7 +31642,10 @@ var McpServer = class {
31542
31642
  }
31543
31643
  for (const template of Object.values(this._registeredResourceTemplates)) {
31544
31644
  const variables = template.resourceTemplate.uriTemplate.match(uri.toString());
31545
- if (variables) return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint);
31645
+ if (variables) {
31646
+ if (!template.enabled) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Resource template ${template.resourceTemplate.uriTemplate} disabled`);
31647
+ return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint);
31648
+ }
31546
31649
  }
31547
31650
  throw new ResourceNotFoundError(request.params.uri);
31548
31651
  });
@@ -31573,36 +31676,32 @@ var McpServer = class {
31573
31676
  this._promptHandlersInitialized = true;
31574
31677
  }
31575
31678
  registerResource(name, uriOrTemplate, config, readCallback) {
31576
- const cacheHint = config.cacheHint;
31577
- let metadata = config;
31578
- if (cacheHint !== void 0) {
31579
- assertValidCacheHint(cacheHint, `resource ${name}`);
31580
- const rest = { ...config };
31581
- delete rest.cacheHint;
31582
- metadata = rest;
31583
- }
31679
+ const { cacheHint, scopeChallenge, ...resourceMetadata } = config;
31680
+ const metadata = resourceMetadata;
31681
+ if (cacheHint !== void 0) assertValidCacheHint(cacheHint, `resource ${name}`);
31584
31682
  if (typeof uriOrTemplate === "string") {
31585
31683
  if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`);
31586
- const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, metadata, readCallback);
31684
+ const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, metadata, scopeChallenge, readCallback);
31587
31685
  if (cacheHint !== void 0) registeredResource.cacheHint = cacheHint;
31588
31686
  this.setResourceRequestHandlers();
31589
31687
  this.sendResourceListChanged();
31590
31688
  return registeredResource;
31591
31689
  } else {
31592
31690
  if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`);
31593
- const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, metadata, readCallback);
31691
+ const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, metadata, scopeChallenge, readCallback);
31594
31692
  if (cacheHint !== void 0) registeredResourceTemplate.cacheHint = cacheHint;
31595
31693
  this.setResourceRequestHandlers();
31596
31694
  this.sendResourceListChanged();
31597
31695
  return registeredResourceTemplate;
31598
31696
  }
31599
31697
  }
31600
- _createRegisteredResource(name, title, uri, metadata, readCallback) {
31698
+ _createRegisteredResource(name, title, uri, metadata, scopeChallenge, readCallback) {
31601
31699
  const registeredResource = {
31602
31700
  name,
31603
31701
  title,
31604
31702
  metadata,
31605
31703
  readCallback,
31704
+ scopeChallenge,
31606
31705
  enabled: true,
31607
31706
  disable: () => registeredResource.update({ enabled: false }),
31608
31707
  enable: () => registeredResource.update({ enabled: true }),
@@ -31616,6 +31715,7 @@ var McpServer = class {
31616
31715
  if (updates.title !== void 0) registeredResource.title = updates.title;
31617
31716
  if (updates.metadata !== void 0) registeredResource.metadata = updates.metadata;
31618
31717
  if (updates.callback !== void 0) registeredResource.readCallback = updates.callback;
31718
+ if (updates.scopeChallenge !== void 0) registeredResource.scopeChallenge = updates.scopeChallenge === null ? void 0 : updates.scopeChallenge;
31619
31719
  if (updates.enabled !== void 0) registeredResource.enabled = updates.enabled;
31620
31720
  this.sendResourceListChanged();
31621
31721
  }
@@ -31623,12 +31723,13 @@ var McpServer = class {
31623
31723
  this._registeredResources[uri] = registeredResource;
31624
31724
  return registeredResource;
31625
31725
  }
31626
- _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) {
31726
+ _createRegisteredResourceTemplate(name, title, template, metadata, scopeChallenge, readCallback) {
31627
31727
  const registeredResourceTemplate = {
31628
31728
  resourceTemplate: template,
31629
31729
  title,
31630
31730
  metadata,
31631
31731
  readCallback,
31732
+ scopeChallenge,
31632
31733
  enabled: true,
31633
31734
  disable: () => registeredResourceTemplate.update({ enabled: false }),
31634
31735
  enable: () => registeredResourceTemplate.update({ enabled: true }),
@@ -31642,6 +31743,7 @@ var McpServer = class {
31642
31743
  if (updates.template !== void 0) registeredResourceTemplate.resourceTemplate = updates.template;
31643
31744
  if (updates.metadata !== void 0) registeredResourceTemplate.metadata = updates.metadata;
31644
31745
  if (updates.callback !== void 0) registeredResourceTemplate.readCallback = updates.callback;
31746
+ if (updates.scopeChallenge !== void 0) registeredResourceTemplate.scopeChallenge = updates.scopeChallenge === null ? void 0 : updates.scopeChallenge;
31645
31747
  if (updates.enabled !== void 0) registeredResourceTemplate.enabled = updates.enabled;
31646
31748
  this.sendResourceListChanged();
31647
31749
  }
@@ -31651,7 +31753,7 @@ var McpServer = class {
31651
31753
  if (Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v))) this.setCompletionRequestHandler();
31652
31754
  return registeredResourceTemplate;
31653
31755
  }
31654
- _createRegisteredPrompt(name, title, description, argsSchema, callback, icons, _meta) {
31756
+ _createRegisteredPrompt(name, title, description, argsSchema, callback, icons, scopeChallenge, _meta) {
31655
31757
  let currentArgsSchema = argsSchema;
31656
31758
  let currentCallback = callback;
31657
31759
  const registeredPrompt = {
@@ -31659,6 +31761,7 @@ var McpServer = class {
31659
31761
  description,
31660
31762
  argsSchema,
31661
31763
  icons,
31764
+ scopeChallenge,
31662
31765
  _meta,
31663
31766
  handler: createPromptHandler(name, argsSchema, callback),
31664
31767
  enabled: true,
@@ -31673,6 +31776,7 @@ var McpServer = class {
31673
31776
  if (updates.title !== void 0) registeredPrompt.title = updates.title;
31674
31777
  if (updates.description !== void 0) registeredPrompt.description = updates.description;
31675
31778
  if (updates.icons !== void 0) registeredPrompt.icons = updates.icons;
31779
+ if (updates.scopeChallenge !== void 0) registeredPrompt.scopeChallenge = updates.scopeChallenge === null ? void 0 : updates.scopeChallenge;
31676
31780
  if (updates._meta !== void 0) registeredPrompt._meta = updates._meta;
31677
31781
  let needsHandlerRegen = false;
31678
31782
  if (updates.argsSchema !== void 0) {
@@ -31700,24 +31804,25 @@ var McpServer = class {
31700
31804
  }
31701
31805
  return registeredPrompt;
31702
31806
  }
31703
- _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, icons, execution, _meta, handler) {
31807
+ _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, icons, execution, scopeChallenge, _meta, handler) {
31704
31808
  validateAndWarnToolName(name);
31705
- if (inputSchema !== void 0) try {
31706
- const json = standardSchemaToJsonSchema(inputSchema, "input");
31707
- this._toolInputSchemaJson[name] = json;
31708
- const scan = scanXMcpHeaderDeclarations(json);
31709
- if (!scan.valid) console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan.reason}`);
31710
- } catch {}
31711
31809
  let currentHandler = handler;
31810
+ let outputSchemaJson;
31712
31811
  const registeredTool = {
31713
31812
  title,
31714
31813
  description,
31715
31814
  inputSchema,
31716
31815
  outputSchema,
31717
- outputSchemaJson: convertOutputSchemaJson(outputSchema),
31816
+ get outputSchemaJson() {
31817
+ return outputSchemaJson ??= convertOutputSchemaJson(registeredTool.outputSchema);
31818
+ },
31819
+ set outputSchemaJson(value) {
31820
+ outputSchemaJson = value;
31821
+ },
31718
31822
  annotations,
31719
31823
  icons,
31720
31824
  execution,
31825
+ scopeChallenge,
31721
31826
  _meta,
31722
31827
  handler,
31723
31828
  executor: createToolExecutor(inputSchema, handler),
@@ -31756,6 +31861,7 @@ var McpServer = class {
31756
31861
  }
31757
31862
  if (updates.annotations !== void 0) registeredTool.annotations = updates.annotations;
31758
31863
  if (updates.icons !== void 0) registeredTool.icons = updates.icons;
31864
+ if (updates.scopeChallenge !== void 0) registeredTool.scopeChallenge = updates.scopeChallenge === null ? void 0 : updates.scopeChallenge;
31759
31865
  if (updates._meta !== void 0) registeredTool._meta = updates._meta;
31760
31866
  if (updates.enabled !== void 0) registeredTool.enabled = updates.enabled;
31761
31867
  this.sendToolListChanged();
@@ -31768,13 +31874,13 @@ var McpServer = class {
31768
31874
  }
31769
31875
  registerTool(name, config, cb) {
31770
31876
  if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`);
31771
- const { title, description, inputSchema, outputSchema, annotations, icons, _meta } = config;
31772
- return this._createRegisteredTool(name, title, description, normalizeRawShapeSchema(inputSchema), normalizeRawShapeSchema(outputSchema), annotations, icons, void 0, _meta, cb);
31877
+ const { title, description, inputSchema, outputSchema, annotations, icons, scopeChallenge, _meta } = config;
31878
+ return this._createRegisteredTool(name, title, description, normalizeRawShapeSchema(inputSchema), normalizeRawShapeSchema(outputSchema), annotations, icons, void 0, scopeChallenge, _meta, cb);
31773
31879
  }
31774
31880
  registerPrompt(name, config, cb) {
31775
31881
  if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`);
31776
- const { title, description, argsSchema, icons, _meta } = config;
31777
- const registeredPrompt = this._createRegisteredPrompt(name, title, description, normalizeRawShapeSchema(argsSchema), cb, icons, _meta);
31882
+ const { title, description, argsSchema, icons, scopeChallenge, _meta } = config;
31883
+ const registeredPrompt = this._createRegisteredPrompt(name, title, description, normalizeRawShapeSchema(argsSchema), cb, icons, scopeChallenge, _meta);
31778
31884
  this.setPromptRequestHandlers();
31779
31885
  this.sendPromptListChanged();
31780
31886
  return registeredPrompt;
@@ -31844,6 +31950,13 @@ const EMPTY_OBJECT_JSON_SCHEMA = {
31844
31950
  type: "object",
31845
31951
  properties: {}
31846
31952
  };
31953
+ /** Converts a tool's `inputSchema` for `tools/list` and warns on an invalid SEP-2243 `x-mcp-header` declaration. */
31954
+ function convertListedInputSchema(name, inputSchema) {
31955
+ const json = standardSchemaToJsonSchema(inputSchema, "input");
31956
+ const scan = scanXMcpHeaderDeclarations(json);
31957
+ if (!scan.valid) console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan.reason}`);
31958
+ return json;
31959
+ }
31847
31960
  /**
31848
31961
  * Convert a registered `outputSchema` to JSON Schema, memoised on {@link RegisteredTool.outputSchemaJson}
31849
31962
  * so `tools/call` passes the SAME advertised schema to the wire codec's `projectCallToolResult` that
@@ -31866,7 +31979,7 @@ function createPromptHandler(name, argsSchema, callback) {
31866
31979
  if (argsSchema) {
31867
31980
  const typedCallback = callback;
31868
31981
  return async (args, ctx) => {
31869
- const parseResult = await validateStandardSchema(argsSchema, args);
31982
+ const parseResult = await validateStandardSchema(argsSchema, args ?? {});
31870
31983
  if (!parseResult.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid arguments for prompt ${name}: ${parseResult.error}`);
31871
31984
  return typedCallback(parseResult.data, ctx);
31872
31985
  };
@@ -31903,12 +32016,27 @@ function unwrapOptionalSchema(schema) {
31903
32016
  return schema.def?.innerType ?? schema;
31904
32017
  }
31905
32018
  //#endregion
31906
- //#region ../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/stdio.mjs
32019
+ //#region ../../node_modules/.pnpm/@modelcontextprotocol+server@2.3.0/node_modules/@modelcontextprotocol/server/dist/stdio.mjs
32020
+ /**
32021
+ * Marks a stdout `'error'` listener that a closed transport left attached purely to
32022
+ * swallow late write failures (see {@link StdioServerTransport.close}). A fresh
32023
+ * transport taking over the same stream removes listeners carrying this tag in
32024
+ * `start()`, so repeated create→close cycles on the process-global `process.stdout`
32025
+ * don't accumulate listeners.
32026
+ */
32027
+ const swallowsErrorsAfterClose = Symbol("swallowsErrorsAfterClose");
31907
32028
  /**
31908
32029
  * Server transport for stdio: this communicates with an MCP client by reading from the current process' `stdin` and writing to `stdout`.
31909
32030
  *
31910
32031
  * This transport is only available in Node.js environments.
31911
32032
  *
32033
+ * When the client closes its end of the pipe (stdin reaches end-of-file), the transport
32034
+ * closes itself and fires `onclose`, per the MCP stdio binding's guidance that servers
32035
+ * should exit promptly when their standard input is closed. A server that holds no other
32036
+ * keep-alive handles will then exit naturally. Requests still in flight when stdin ends are
32037
+ * aborted and not answered; a client that expects responses keeps stdin open until it has
32038
+ * read them.
32039
+ *
31912
32040
  * @example
31913
32041
  * ```ts source="./stdio.examples.ts#StdioServerTransport_basicUsage"
31914
32042
  * const server = new McpServer({ name: 'my-server', version: '1.0.0' });
@@ -31941,17 +32069,25 @@ var StdioServerTransport = class {
31941
32069
  this.onerror?.(error);
31942
32070
  };
31943
32071
  _onstdouterror = (error) => {
32072
+ if (this._closed) return;
31944
32073
  this.onerror?.(error);
31945
32074
  this.close().catch(() => {});
31946
32075
  };
32076
+ _onstdinclose = () => {
32077
+ this.close().catch(() => {});
32078
+ };
31947
32079
  /**
31948
32080
  * Starts listening for messages on `stdin`.
31949
32081
  */
31950
32082
  async start() {
31951
32083
  if (this._started) throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");
31952
32084
  this._started = true;
32085
+ for (const listener of this._stdout.listeners("error")) if (listener[swallowsErrorsAfterClose]) this._stdout.off("error", listener);
32086
+ if (this._stdin.readableEnded || this._stdin.destroyed) setImmediate(this._onstdinclose);
31953
32087
  this._stdin.on("data", this._ondata);
31954
32088
  this._stdin.on("error", this._onerror);
32089
+ this._stdin.on("end", this._onstdinclose);
32090
+ this._stdin.on("close", this._onstdinclose);
31955
32091
  this._stdout.on("error", this._onstdouterror);
31956
32092
  }
31957
32093
  processReadBuffer() {
@@ -31968,7 +32104,9 @@ var StdioServerTransport = class {
31968
32104
  this._closed = true;
31969
32105
  this._stdin.off("data", this._ondata);
31970
32106
  this._stdin.off("error", this._onerror);
31971
- this._stdout.off("error", this._onstdouterror);
32107
+ this._stdin.off("end", this._onstdinclose);
32108
+ this._stdin.off("close", this._onstdinclose);
32109
+ this._onstdouterror[swallowsErrorsAfterClose] = true;
31972
32110
  if (this._stdin.listenerCount("data") === 0) this._stdin.pause();
31973
32111
  this._readBuffer.clear();
31974
32112
  this.onclose?.();
@@ -32305,6 +32443,7 @@ function serveStdio(factory, options = {}) {
32305
32443
  return;
32306
32444
  }
32307
32445
  if (state.era === "modern" && await tryServeListen(message)) return;
32446
+ if (isTornDown()) return;
32308
32447
  state.instance.channel.deliver(message);
32309
32448
  return;
32310
32449
  }
@@ -32371,6 +32510,7 @@ function serveStdio(factory, options = {}) {
32371
32510
  };
32372
32511
  }
32373
32512
  if (await tryServeListen(message)) return;
32513
+ if (isTornDown()) return;
32374
32514
  state.instance.channel.deliver(message, { classification: opening.classification });
32375
32515
  return;
32376
32516
  case "legacy": {
@@ -55539,6 +55679,28 @@ Call the auth tool to authenticate (or run ${npxMcpAuthCommand()} manually).
55539
55679
  ${core}`;
55540
55680
  }
55541
55681
  //#endregion
55682
+ //#region src/utils.ts
55683
+ function mcpJson(value) {
55684
+ const text = JSON.stringify(value ?? null, null, 2);
55685
+ const structuredContent = JSON.parse(text);
55686
+ return {
55687
+ content: [{
55688
+ type: "text",
55689
+ text
55690
+ }],
55691
+ structuredContent
55692
+ };
55693
+ }
55694
+ function mcpFailure(text) {
55695
+ return {
55696
+ content: [{
55697
+ type: "text",
55698
+ text
55699
+ }],
55700
+ isError: true
55701
+ };
55702
+ }
55703
+ //#endregion
55542
55704
  //#region ../../node_modules/.pnpm/@valibot+to-json-schema@1.6.0_valibot@1.3.1_typescript@6.0.3_/node_modules/@valibot/to-json-schema/dist/index.mjs
55543
55705
  /**
55544
55706
  * Adds an error message to the errors array.
@@ -56139,23 +56301,6 @@ function optionalDescString(description) {
56139
56301
  }
56140
56302
  const optionalConfirmToken = /* @__PURE__ */ optional(/* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ description("Mutation confirmation token from previous call")));
56141
56303
  //#endregion
56142
- //#region src/utils.ts
56143
- function mcpText(text) {
56144
- return { content: [{
56145
- type: "text",
56146
- text
56147
- }] };
56148
- }
56149
- function mcpFailure(text) {
56150
- return {
56151
- content: [{
56152
- type: "text",
56153
- text
56154
- }],
56155
- isError: true
56156
- };
56157
- }
56158
- //#endregion
56159
56304
  //#region src/runtime/safety/mutation-gate.ts
56160
56305
  var MutationConfirmationRequired = class extends Error {
56161
56306
  confirmToken;
@@ -56229,7 +56374,7 @@ function createMutationApprovalScope(confirmToken) {
56229
56374
  //#endregion
56230
56375
  //#region src/tools/focus-tool-utils.ts
56231
56376
  function apiResult(response) {
56232
- if (response.ok) return mcpText(JSON.stringify(response.data, null, 2));
56377
+ if (response.ok) return mcpJson(response.data);
56233
56378
  return {
56234
56379
  content: [{
56235
56380
  type: "text",
@@ -56240,13 +56385,13 @@ function apiResult(response) {
56240
56385
  }
56241
56386
  function withMutationApproval(params, run) {
56242
56387
  return run(createMutationApprovalScope(params.confirm_token)).catch((err) => {
56243
- if (err instanceof MutationConfirmationRequired) return mcpText(JSON.stringify({
56388
+ if (err instanceof MutationConfirmationRequired) return mcpJson({
56244
56389
  confirm_required: true,
56245
56390
  confirm_token: err.confirmToken,
56246
56391
  operation: err.operation,
56247
56392
  summary: err.summary,
56248
56393
  hint: "Call this tool again with the same arguments and confirm_token to execute once."
56249
- }, null, 2));
56394
+ });
56250
56395
  return {
56251
56396
  content: [{
56252
56397
  type: "text",
@@ -56294,12 +56439,12 @@ function registerWorkspaceTools(server) {
56294
56439
  const runApiTokenAuth = async () => {
56295
56440
  const status = await apiTokenStatus();
56296
56441
  if (!status.ok) return mcpFailure(status.message);
56297
- return mcpText(JSON.stringify({
56442
+ return mcpJson({
56298
56443
  authenticated: true,
56299
56444
  requires_workspace_selection: false,
56300
56445
  ...describeApiTokenIdentity(status.identity),
56301
56446
  message: "Signed in with TOGGL_API_TOKEN. No browser sign-in runs and nothing is saved to ~/.toggl/focus-tools.json."
56302
- }, null, 2));
56447
+ });
56303
56448
  };
56304
56449
  const runAuth = async ({ workspace_id, accounts_api_url, focus_api_url }) => {
56305
56450
  if (isApiTokenMode()) return runApiTokenAuth();
@@ -56310,40 +56455,34 @@ function registerWorkspaceTools(server) {
56310
56455
  continuation
56311
56456
  });
56312
56457
  pendingAuthContext = null;
56313
- return { content: [{
56314
- type: "text",
56315
- text: JSON.stringify({
56316
- authenticated: true,
56317
- requires_workspace_selection: false,
56318
- workspace: {
56319
- workspace_id: authResult.config.workspace_id,
56320
- workspace_name: authResult.config.workspace_name,
56321
- organization_id: authResult.config.organization_id
56322
- },
56323
- user_id: authResult.config.user_id,
56324
- available_workspaces: authResult.workspaces.map((workspace) => ({
56458
+ return mcpJson({
56459
+ authenticated: true,
56460
+ requires_workspace_selection: false,
56461
+ workspace: {
56462
+ workspace_id: authResult.config.workspace_id,
56463
+ workspace_name: authResult.config.workspace_name,
56464
+ organization_id: authResult.config.organization_id
56465
+ },
56466
+ user_id: authResult.config.user_id,
56467
+ available_workspaces: authResult.workspaces.map((workspace) => ({
56468
+ workspace_id: workspace.workspace_id,
56469
+ workspace_name: workspace.workspace_name,
56470
+ organization_name: workspace.organization_name
56471
+ }))
56472
+ });
56473
+ } catch (error) {
56474
+ if (error instanceof WorkspaceSelectionRequiredError) {
56475
+ pendingAuthContext = error.context;
56476
+ return mcpJson({
56477
+ authenticated: false,
56478
+ requires_workspace_selection: true,
56479
+ message: "Multiple workspaces found. Call auth again with workspace_id to complete authentication.",
56480
+ available_workspaces: error.workspaces.map((workspace) => ({
56325
56481
  workspace_id: workspace.workspace_id,
56326
56482
  workspace_name: workspace.workspace_name,
56327
56483
  organization_name: workspace.organization_name
56328
56484
  }))
56329
- }, null, 2)
56330
- }] };
56331
- } catch (error) {
56332
- if (error instanceof WorkspaceSelectionRequiredError) {
56333
- pendingAuthContext = error.context;
56334
- return { content: [{
56335
- type: "text",
56336
- text: JSON.stringify({
56337
- authenticated: false,
56338
- requires_workspace_selection: true,
56339
- message: "Multiple workspaces found. Call auth again with workspace_id to complete authentication.",
56340
- available_workspaces: error.workspaces.map((workspace) => ({
56341
- workspace_id: workspace.workspace_id,
56342
- workspace_name: workspace.workspace_name,
56343
- organization_name: workspace.organization_name
56344
- }))
56345
- }, null, 2)
56346
- }] };
56485
+ });
56347
56486
  }
56348
56487
  pendingAuthContext = null;
56349
56488
  return {
@@ -56357,21 +56496,18 @@ function registerWorkspaceTools(server) {
56357
56496
  };
56358
56497
  const runLogout = async () => {
56359
56498
  pendingAuthContext = null;
56360
- if (isApiTokenMode()) return mcpText(JSON.stringify({
56499
+ if (isApiTokenMode()) return mcpJson({
56361
56500
  logged_out: false,
56362
56501
  auth_mode: "api_token",
56363
56502
  removed_config: false,
56364
56503
  message: "This server authenticates with TOGGL_API_TOKEN, so there is no stored session to clear. Remove TOGGL_API_TOKEN from the MCP server config to sign out. Saved OAuth profiles were left untouched."
56365
- }, null, 2));
56504
+ });
56366
56505
  const removed = clearConfig();
56367
- return { content: [{
56368
- type: "text",
56369
- text: JSON.stringify({
56370
- logged_out: true,
56371
- removed_config: removed,
56372
- message: removed ? "Authentication config cleared. Call auth to authenticate again." : "No auth config existed. Call auth to authenticate."
56373
- }, null, 2)
56374
- }] };
56506
+ return mcpJson({
56507
+ logged_out: true,
56508
+ removed_config: removed,
56509
+ message: removed ? "Authentication config cleared. Call auth to authenticate again." : "No auth config existed. Call auth to authenticate."
56510
+ });
56375
56511
  };
56376
56512
  server.registerTool("workspace-list", {
56377
56513
  title: "List Workspaces",
@@ -56388,12 +56524,12 @@ function registerWorkspaceTools(server) {
56388
56524
  if (params.refresh) return mcpFailure(mcpOAuthRequiredMessage("workspace-list refresh"));
56389
56525
  const status = await apiTokenStatus();
56390
56526
  if (!status.ok) return mcpFailure(status.message);
56391
- return mcpText(JSON.stringify([{
56527
+ return mcpJson([{
56392
56528
  workspace_id: status.identity.workspace_id,
56393
56529
  organization_id: status.identity.organization_id,
56394
56530
  active: true,
56395
56531
  auth_mode: "api_token"
56396
- }], null, 2));
56532
+ }]);
56397
56533
  }
56398
56534
  try {
56399
56535
  if (params.refresh) await refreshMcpWorkspaces();
@@ -56414,7 +56550,7 @@ function registerWorkspaceTools(server) {
56414
56550
  }],
56415
56551
  isError: true
56416
56552
  };
56417
- const result = (config.workspaces ?? [{
56553
+ return mcpJson((config.workspaces ?? [{
56418
56554
  workspace_id: config.workspace_id,
56419
56555
  workspace_name: config.workspace_name,
56420
56556
  organization_id: config.organization_id,
@@ -56424,11 +56560,7 @@ function registerWorkspaceTools(server) {
56424
56560
  workspace_name: w.workspace_name,
56425
56561
  organization_name: w.organization_name,
56426
56562
  active: w.workspace_id === config.workspace_id
56427
- }));
56428
- return { content: [{
56429
- type: "text",
56430
- text: JSON.stringify(result, null, 2)
56431
- }] };
56563
+ })));
56432
56564
  });
56433
56565
  server.registerTool("workspace-switch", {
56434
56566
  title: "Switch Workspace",
@@ -56480,13 +56612,13 @@ function registerWorkspaceTools(server) {
56480
56612
  }, async (_ctx) => {
56481
56613
  if (isApiTokenMode()) {
56482
56614
  const status = await apiTokenStatus();
56483
- return mcpText(JSON.stringify({
56615
+ return mcpJson({
56484
56616
  auth_mode: "api_token",
56485
56617
  active: status.ok ? describeApiTokenIdentity(status.identity) : { error: status.message },
56486
56618
  message: API_TOKEN_PROFILES_MESSAGE
56487
- }, null, 2));
56619
+ });
56488
56620
  }
56489
- const payload = listMcpProfiles().map((row) => ({
56621
+ return mcpJson(listMcpProfiles().map((row) => ({
56490
56622
  name: row.name,
56491
56623
  active_for_mcp: row.active,
56492
56624
  environment: row.environment,
@@ -56496,11 +56628,7 @@ function registerWorkspaceTools(server) {
56496
56628
  organization_id: row.organization_id,
56497
56629
  organization_name: row.organization_name,
56498
56630
  token_expired: row.token_expired
56499
- }));
56500
- return { content: [{
56501
- type: "text",
56502
- text: JSON.stringify(payload, null, 2)
56503
- }] };
56631
+ })));
56504
56632
  });
56505
56633
  server.registerTool("profile-switch", {
56506
56634
  title: "Switch MCP profile",
@@ -56516,15 +56644,12 @@ function registerWorkspaceTools(server) {
56516
56644
  if (isApiTokenMode()) return mcpFailure(API_TOKEN_PROFILES_MESSAGE);
56517
56645
  try {
56518
56646
  const row = switchMcpProfile(params.profile_name);
56519
- return { content: [{
56520
- type: "text",
56521
- text: JSON.stringify({
56522
- switched_to: row.name,
56523
- workspace_id: row.workspace_id,
56524
- workspace_name: row.workspace_name,
56525
- environment: row.environment
56526
- }, null, 2)
56527
- }] };
56647
+ return mcpJson({
56648
+ switched_to: row.name,
56649
+ workspace_id: row.workspace_id,
56650
+ workspace_name: row.workspace_name,
56651
+ environment: row.environment
56652
+ });
56528
56653
  } catch (error) {
56529
56654
  return {
56530
56655
  content: [{
@@ -56551,13 +56676,10 @@ function registerWorkspaceTools(server) {
56551
56676
  approvalScope.requireMutationApproval("profile-remove", mutationFingerprint({ profile_name: params.profile_name }), () => JSON.stringify({ profile_name: params.profile_name }));
56552
56677
  try {
56553
56678
  const removed = removeMcpProfile(params.profile_name);
56554
- return { content: [{
56555
- type: "text",
56556
- text: JSON.stringify({
56557
- removed_profile: removed.name,
56558
- had_been_active_for_mcp: removed.active
56559
- }, null, 2)
56560
- }] };
56679
+ return mcpJson({
56680
+ removed_profile: removed.name,
56681
+ had_been_active_for_mcp: removed.active
56682
+ });
56561
56683
  } catch (error) {
56562
56684
  return {
56563
56685
  content: [{
@@ -56599,7 +56721,7 @@ function registerWorkspaceTools(server) {
56599
56721
  //#region src/package-version.ts
56600
56722
  function mcpPackageVersion() {
56601
56723
  try {
56602
- return "1.12.7";
56724
+ return "1.13.1";
56603
56725
  } catch {
56604
56726
  return "unknown";
56605
56727
  }
@@ -56718,11 +56840,11 @@ async function runOperation(operation, data, client, confirmToken, dryRun) {
56718
56840
  const parseResult = /* @__PURE__ */ safeParse(operation.inputSchema, coercePayload(data) ?? {});
56719
56841
  if (!parseResult.success) return mcpFailure(`Invalid input: ${formatValibotError(parseResult.issues)}`);
56720
56842
  const input = parseResult.output;
56721
- if (dryRun) return mcpText(JSON.stringify({
56843
+ if (dryRun) return mcpJson({
56722
56844
  dry_run: true,
56723
56845
  operation: operation.id,
56724
56846
  input
56725
- }, null, 2));
56847
+ });
56726
56848
  if (isApiTokenMode()) try {
56727
56849
  await apiTokenIdentity().resolve();
56728
56850
  } catch (error) {
@@ -56780,7 +56902,9 @@ import_main.default.config({
56780
56902
  quiet: true,
56781
56903
  ignore: ["MISSING_ENV_FILE"]
56782
56904
  });
56783
- const packageVersion = "1.12.7";
56905
+ const packageVersion = "1.13.1";
56906
+ const MCP_CACHE_TTL_MS = 300 * 1e3;
56907
+ const MCP_MAX_TOOL_INPUT_ELEMENTS = 1e4;
56784
56908
  function resolvePublicUrls() {
56785
56909
  return {
56786
56910
  focusApiUrl: process.env.TOGGL_FOCUS_API_URL ?? "https://focus.toggl.com",
@@ -56862,12 +56986,25 @@ function bootstrapServer(options = {}) {
56862
56986
  const rawServer = new McpServer({
56863
56987
  name: "toggl-focus",
56864
56988
  version: packageVersion
56865
- }, { instructions: buildMcpServerInstructions({
56866
- authenticated,
56867
- workspaceLabel,
56868
- authMode: tokenMode ? "api_token" : "oauth",
56869
- apiTokenError
56870
- }) });
56989
+ }, {
56990
+ instructions: buildMcpServerInstructions({
56991
+ authenticated,
56992
+ workspaceLabel,
56993
+ authMode: tokenMode ? "api_token" : "oauth",
56994
+ apiTokenError
56995
+ }),
56996
+ cacheHints: {
56997
+ "server/discover": {
56998
+ ttlMs: MCP_CACHE_TTL_MS,
56999
+ cacheScope: "private"
57000
+ },
57001
+ "tools/list": {
57002
+ ttlMs: MCP_CACHE_TTL_MS,
57003
+ cacheScope: "private"
57004
+ }
57005
+ },
57006
+ maxToolInputElements: MCP_MAX_TOOL_INPUT_ELEMENTS
57007
+ });
56871
57008
  const server = options.beforeRegister?.(rawServer) ?? rawServer;
56872
57009
  registerWorkspaceTools(server);
56873
57010
  registerGeneratedEntityTools(server, client);
@@ -56883,6 +57020,6 @@ function bootstrapServer(options = {}) {
56883
57020
  if (options.beforeExit) process.on("beforeExit", async () => await options.beforeExit?.());
56884
57021
  }
56885
57022
  //#endregion
56886
- export { getProductAnalyticsDistinctId as a, resolvePublicSentryDsn as c, captureToolInvocation as i, shutdownProductAnalytics as l, runMcpCli as n, initProductAnalytics as o, PUBLIC_SENTRY_PRIVACY_OPTIONS as r, resolveProductAnalyticsDistinctId as s, bootstrapServer as t };
57023
+ export { PUBLIC_SENTRY_PRIVACY_OPTIONS as a, initProductAnalytics as c, shutdownProductAnalytics as d, runMcpCli as i, resolveProductAnalyticsDistinctId as l, MCP_MAX_TOOL_INPUT_ELEMENTS as n, captureToolInvocation as o, bootstrapServer as r, getProductAnalyticsDistinctId as s, MCP_CACHE_TTL_MS as t, resolvePublicSentryDsn as u };
56887
57024
 
56888
- //# sourceMappingURL=src-RGqqLBRK.js.map
57025
+ //# sourceMappingURL=src-5RYMrZge.js.map