@frontmcp/sdk 1.9.4 → 1.9.6

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.
Files changed (138) hide show
  1. package/README.md +22 -22
  2. package/app/instances/app.esm.instance.d.ts.map +1 -1
  3. package/app/instances/app.remote.instance.d.ts.map +1 -1
  4. package/auth/flows/oauth.connect.flow.d.ts +1 -1
  5. package/auth/flows/oauth.connect.flow.d.ts.map +1 -1
  6. package/auth/flows/session.verify.flow.d.ts.map +1 -1
  7. package/auth/instances/instance.local-primary-auth.d.ts +6 -0
  8. package/auth/instances/instance.local-primary-auth.d.ts.map +1 -1
  9. package/browser/index.cjs +1653 -1175
  10. package/browser/index.mjs +956 -488
  11. package/channel/channel-scope.helper.d.ts +4 -3
  12. package/channel/channel-scope.helper.d.ts.map +1 -1
  13. package/common/entries/job.entry.d.ts +1 -0
  14. package/common/entries/job.entry.d.ts.map +1 -1
  15. package/common/interfaces/execution-context.interface.d.ts +1 -3
  16. package/common/interfaces/execution-context.interface.d.ts.map +1 -1
  17. package/common/interfaces/job.interface.d.ts +11 -0
  18. package/common/interfaces/job.interface.d.ts.map +1 -1
  19. package/common/interfaces/server.interface.d.ts +0 -6
  20. package/common/interfaces/server.interface.d.ts.map +1 -1
  21. package/common/interfaces/skill.interface.d.ts +2 -1
  22. package/common/interfaces/skill.interface.d.ts.map +1 -1
  23. package/common/interfaces/tool.interface.d.ts +3 -2
  24. package/common/interfaces/tool.interface.d.ts.map +1 -1
  25. package/common/metadata/agent.metadata.d.ts +1 -1
  26. package/common/metadata/app.metadata.d.ts +3 -3
  27. package/common/metadata/front-mcp.metadata.d.ts +109 -90
  28. package/common/metadata/front-mcp.metadata.d.ts.map +1 -1
  29. package/common/metadata/job.metadata.d.ts +1 -1
  30. package/common/metadata/plugin.metadata.d.ts +2 -2
  31. package/common/metadata/skill.metadata.d.ts +6 -4
  32. package/common/metadata/skill.metadata.d.ts.map +1 -1
  33. package/common/metadata/tool-ui.metadata.d.ts +1 -1
  34. package/common/metadata/tool.metadata.d.ts +1 -1
  35. package/common/metadata/workflow.metadata.d.ts +1 -1
  36. package/common/schemas/annotated-class.schema.d.ts +2 -2
  37. package/common/schemas/http-output.schema.d.ts +4 -4
  38. package/common/types/options/logging/schema.d.ts +2 -0
  39. package/common/types/options/logging/schema.d.ts.map +1 -1
  40. package/common/types/options/skills-http/interfaces.d.ts +17 -0
  41. package/common/types/options/skills-http/interfaces.d.ts.map +1 -1
  42. package/common/types/options/skills-http/schema.d.ts +8 -13
  43. package/common/types/options/skills-http/schema.d.ts.map +1 -1
  44. package/common/types/options/transport/schema.d.ts +2 -2
  45. package/context/frontmcp-context.provider.d.ts +1 -1
  46. package/direct/create.d.ts.map +1 -1
  47. package/direct/create.types.d.ts +1 -1
  48. package/direct/create.types.d.ts.map +1 -1
  49. package/errors/index.d.ts +1 -1
  50. package/errors/index.d.ts.map +1 -1
  51. package/errors/task.error.d.ts +5 -0
  52. package/errors/task.error.d.ts.map +1 -1
  53. package/esm/index.mjs +952 -488
  54. package/flows/flow.http-path.d.ts +8 -0
  55. package/flows/flow.http-path.d.ts.map +1 -1
  56. package/health/health.routes.d.ts +2 -0
  57. package/health/health.routes.d.ts.map +1 -1
  58. package/health/index.d.ts +1 -1
  59. package/health/index.d.ts.map +1 -1
  60. package/index.d.ts +22 -20
  61. package/index.d.ts.map +1 -1
  62. package/index.js +1658 -1184
  63. package/job/flows/execute-job.flow.d.ts +9 -2
  64. package/job/flows/execute-job.flow.d.ts.map +1 -1
  65. package/job/job-attempt.d.ts +4 -1
  66. package/job/job-attempt.d.ts.map +1 -1
  67. package/job/job.instance.d.ts +1 -0
  68. package/job/job.instance.d.ts.map +1 -1
  69. package/package.json +11 -11
  70. package/plugin/plugin.registry.d.ts.map +1 -1
  71. package/prompt/flows/prompts-list.flow.d.ts.map +1 -1
  72. package/provider/provider.registry.d.ts +3 -1
  73. package/provider/provider.registry.d.ts.map +1 -1
  74. package/resource/flows/read-resource.flow.d.ts.map +1 -1
  75. package/resource/resource.registry.d.ts +2 -2
  76. package/resource/resource.registry.d.ts.map +1 -1
  77. package/scope/flows/http.request.flow.d.ts +2 -1
  78. package/scope/flows/http.request.flow.d.ts.map +1 -1
  79. package/scope/scope.instance.d.ts +7 -0
  80. package/scope/scope.instance.d.ts.map +1 -1
  81. package/server/adapters/express.host.adapter.d.ts +1 -1
  82. package/server/adapters/express.host.adapter.d.ts.map +1 -1
  83. package/server/custom-routes.helper.d.ts +15 -5
  84. package/server/custom-routes.helper.d.ts.map +1 -1
  85. package/server/noop-server.d.ts +0 -1
  86. package/server/noop-server.d.ts.map +1 -1
  87. package/server/server.instance.d.ts +0 -1
  88. package/server/server.instance.d.ts.map +1 -1
  89. package/skill/errors/tool-not-allowed.error.d.ts +1 -1
  90. package/skill/index.d.ts +1 -1
  91. package/skill/index.d.ts.map +1 -1
  92. package/skill/sep-2640/resources/skill-index.resource.d.ts.map +1 -1
  93. package/skill/sep-2640/resources/skill-md.resource.d.ts +2 -0
  94. package/skill/sep-2640/resources/skill-md.resource.d.ts.map +1 -1
  95. package/skill/sep-2640/sep-2640.per-skill.d.ts +5 -1
  96. package/skill/sep-2640/sep-2640.per-skill.d.ts.map +1 -1
  97. package/skill/sep-2640/sep-2640.resource-helpers.d.ts +9 -0
  98. package/skill/sep-2640/sep-2640.resource-helpers.d.ts.map +1 -1
  99. package/skill/skill-audit.helper.d.ts +1 -1
  100. package/skill/skill-audit.helper.d.ts.map +1 -1
  101. package/skill/skill-directory-loader.d.ts +5 -2
  102. package/skill/skill-directory-loader.d.ts.map +1 -1
  103. package/skill/skill-mode.utils.d.ts +20 -2
  104. package/skill/skill-mode.utils.d.ts.map +1 -1
  105. package/skill/skill-scope.helper.d.ts.map +1 -1
  106. package/skill/skill.registry.d.ts +12 -1
  107. package/skill/skill.registry.d.ts.map +1 -1
  108. package/task/helpers/cli-task-runner.d.ts.map +1 -1
  109. package/task/helpers/process-liveness.d.ts +4 -0
  110. package/task/helpers/process-liveness.d.ts.map +1 -1
  111. package/task/helpers/task-runner.d.ts.map +1 -1
  112. package/task/runtime/execute-task.d.ts.map +1 -1
  113. package/task/store/storage-task.store.d.ts +10 -0
  114. package/task/store/storage-task.store.d.ts.map +1 -1
  115. package/task/store/task.store.d.ts +2 -0
  116. package/task/store/task.store.d.ts.map +1 -1
  117. package/task/task.types.d.ts +7 -1
  118. package/task/task.types.d.ts.map +1 -1
  119. package/tool/flows/call-tool.flow.d.ts +7 -1
  120. package/tool/flows/call-tool.flow.d.ts.map +1 -1
  121. package/tool/flows/tools-list.flow.d.ts.map +1 -1
  122. package/tool/ui/template-helpers.d.ts +1 -1
  123. package/transport/mcp-20260728/dispatcher.d.ts.map +1 -1
  124. package/transport/mcp-20260728/protocol-20260728.constants.d.ts +2 -0
  125. package/transport/mcp-20260728/protocol-20260728.constants.d.ts.map +1 -1
  126. package/transport/mcp-20260728/tasks-extension.d.ts +3 -19
  127. package/transport/mcp-20260728/tasks-extension.d.ts.map +1 -1
  128. package/transport/mcp-handlers/call-tool-error.utils.d.ts +12 -0
  129. package/transport/mcp-handlers/call-tool-error.utils.d.ts.map +1 -0
  130. package/transport/mcp-handlers/call-tool-request.handler.d.ts.map +1 -1
  131. package/transport/mcp-handlers/index.d.ts +5 -5
  132. package/transport/mcp-handlers/initialize-request.handler.d.ts.map +1 -1
  133. package/transport/mcp-handlers/skills-mcp.types.d.ts +1 -1
  134. package/transport/web-fetch-handler.d.ts +5 -4
  135. package/transport/web-fetch-handler.d.ts.map +1 -1
  136. package/transport/web-http-route.d.ts +11 -0
  137. package/transport/web-http-route.d.ts.map +1 -0
  138. package/workflow/engine/workflow-step.executor.d.ts +3 -3
package/browser/index.mjs CHANGED
@@ -625,6 +625,39 @@ var init_decorator_errors = __esm({
625
625
  }
626
626
  });
627
627
 
628
+ // libs/sdk/src/task/task.types.ts
629
+ function toWireShape(record) {
630
+ const wire = {
631
+ taskId: record.taskId,
632
+ status: record.status,
633
+ ttl: record.ttlMs,
634
+ createdAt: record.createdAt,
635
+ lastUpdatedAt: record.lastUpdatedAt
636
+ };
637
+ if (record.pollIntervalMs !== void 0) wire.pollInterval = record.pollIntervalMs;
638
+ if (record.statusMessage !== void 0) wire.statusMessage = record.statusMessage;
639
+ return wire;
640
+ }
641
+ function isTerminal(status) {
642
+ return status === "completed" || status === "failed" || status === "cancelled";
643
+ }
644
+ var TASK_DEFAULTS, MAX_CONCURRENT_TASKS_PER_SESSION, RELATED_TASK_META_KEY;
645
+ var init_task_types = __esm({
646
+ "libs/sdk/src/task/task.types.ts"() {
647
+ "use strict";
648
+ TASK_DEFAULTS = {
649
+ defaultTtlMs: 36e5,
650
+ // 1 hour
651
+ maxTtlMs: 864e5,
652
+ // 24 hours
653
+ defaultPollIntervalMs: 2e3,
654
+ maxConcurrentPerSession: 16
655
+ };
656
+ MAX_CONCURRENT_TASKS_PER_SESSION = 1e3;
657
+ RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task";
658
+ }
659
+ });
660
+
628
661
  // libs/sdk/src/errors/esm.errors.ts
629
662
  var EsmPackageLoadError, EsmVersionResolutionError, EsmManifestInvalidError, EsmCacheError, EsmRegistryAuthError, EsmInvalidSpecifierError;
630
663
  var init_esm_errors = __esm({
@@ -2571,7 +2604,7 @@ var init_interfaces = __esm({
2571
2604
 
2572
2605
  // libs/sdk/src/common/types/options/logging/schema.ts
2573
2606
  import { z as z9 } from "@frontmcp/lazy-zod";
2574
- import { getEnv as getEnv2 } from "@frontmcp/utils";
2607
+ import { getEnv as getEnv2, getRuntimeContext } from "@frontmcp/utils";
2575
2608
  function logLevelFromEnv() {
2576
2609
  const name45 = getEnv2("FRONTMCP_LOG_LEVEL")?.trim().toLowerCase();
2577
2610
  const match = Object.entries(LogLevelName).find(([, levelName]) => levelName === name45);
@@ -2584,7 +2617,7 @@ var init_schema4 = __esm({
2584
2617
  init_schemas();
2585
2618
  init_interfaces();
2586
2619
  loggingOptionsSchema = z9.object({
2587
- level: z9.nativeEnum(LogLevel).optional().default(() => logLevelFromEnv() ?? 2 /* Info */),
2620
+ level: z9.nativeEnum(LogLevel).optional().default(() => logLevelFromEnv() ?? (getRuntimeContext().runtime === "browser" ? 3 /* Warn */ : 2 /* Info */)),
2588
2621
  prefix: z9.string().optional(),
2589
2622
  enableConsole: z9.boolean().optional().default(true),
2590
2623
  transports: z9.array(annotatedFrontMcpLoggerSchema).optional().default([])
@@ -2823,7 +2856,7 @@ var init_schema6 = __esm({
2823
2856
  });
2824
2857
 
2825
2858
  // libs/sdk/src/common/types/options/sqlite/resolve.ts
2826
- import { getRuntimeContext, readFileSync } from "@frontmcp/utils";
2859
+ import { getRuntimeContext as getRuntimeContext2, readFileSync } from "@frontmcp/utils";
2827
2860
  function nodeOs() {
2828
2861
  return __require("os");
2829
2862
  }
@@ -2832,7 +2865,7 @@ function nodePath() {
2832
2865
  }
2833
2866
  function resolveDefaultSqlitePath(ctx) {
2834
2867
  const cwd = ctx.cwd ?? process.cwd();
2835
- const { env, runtime } = getRuntimeContext();
2868
+ const { env, runtime } = getRuntimeContext2();
2836
2869
  const namespace = sanitizeForFs(ctx.appName) || "frontmcp";
2837
2870
  if (ctx.cliMode || env === "production") {
2838
2871
  return nodePath().join(nodeOs().homedir(), `.${namespace}`, "sessions.sqlite");
@@ -3171,6 +3204,11 @@ var init_elicitation = __esm({
3171
3204
 
3172
3205
  // libs/sdk/src/common/types/options/skills-http/schema.ts
3173
3206
  import { z as z16 } from "@frontmcp/lazy-zod";
3207
+ function isExternalSkillProvider(value) {
3208
+ if (typeof value !== "object" || value === null) return false;
3209
+ const provider = value;
3210
+ return EXTERNAL_SKILL_PROVIDER_METHODS.every((method) => typeof provider[method] === "function");
3211
+ }
3174
3212
  function normalizeEndpointConfig(config, defaultPath, parentAuth, parentApiKeys) {
3175
3213
  if (config === void 0 || config === true) {
3176
3214
  return {
@@ -3215,7 +3253,7 @@ function normalizeSkillsConfigOptions(options) {
3215
3253
  normalizedApi: normalizeEndpointConfig(parsed.api, `${prefix}/skills`, auth, apiKeys)
3216
3254
  };
3217
3255
  }
3218
- var skillsConfigAuthModeSchema, skillsConfigEndpointConfigSchema, skillsConfigEndpointInputSchema, skillsConfigJwtOptionsSchema, skillsConfigCacheOptionsSchema, skillsConfigAuditOptionsSchema, skillsConfigOptionsSchema;
3256
+ var skillsConfigAuthModeSchema, skillsConfigEndpointConfigSchema, skillsConfigEndpointInputSchema, skillsConfigJwtOptionsSchema, skillsConfigCacheOptionsSchema, SUBJECT_HASH_SECRET_MIN_BYTES, skillsConfigAuditOptionsSchema, EXTERNAL_SKILL_PROVIDER_METHODS, skillsConfigOptionsSchema;
3219
3257
  var init_schema11 = __esm({
3220
3258
  "libs/sdk/src/common/types/options/skills-http/schema.ts"() {
3221
3259
  "use strict";
@@ -3244,14 +3282,30 @@ var init_schema11 = __esm({
3244
3282
  ttlMs: z16.number().int().positive().optional().default(6e4),
3245
3283
  keyPrefix: z16.string().optional()
3246
3284
  });
3285
+ SUBJECT_HASH_SECRET_MIN_BYTES = 32;
3247
3286
  skillsConfigAuditOptionsSchema = z16.object({
3248
3287
  enabled: z16.boolean().optional().default(false),
3249
3288
  signer: z16.unknown().optional(),
3250
3289
  store: z16.unknown().optional(),
3251
3290
  metrics: z16.unknown().optional(),
3252
3291
  subjectMode: z16.enum(["plain", "hash", "omit"]).optional(),
3292
+ subjectHashSecret: z16.union([
3293
+ z16.string().min(SUBJECT_HASH_SECRET_MIN_BYTES),
3294
+ z16.custom((secret) => secret instanceof Uint8Array && secret.length >= SUBJECT_HASH_SECRET_MIN_BYTES, {
3295
+ message: `subjectHashSecret must be at least ${SUBJECT_HASH_SECRET_MIN_BYTES} bytes`
3296
+ })
3297
+ ]).optional(),
3253
3298
  headAnchorIntervalMs: z16.number().int().positive().optional()
3254
3299
  });
3300
+ EXTERNAL_SKILL_PROVIDER_METHODS = [
3301
+ "initialize",
3302
+ "isReadOnly",
3303
+ "search",
3304
+ "load",
3305
+ "list",
3306
+ "count",
3307
+ "syncSkills"
3308
+ ];
3255
3309
  skillsConfigOptionsSchema = z16.object({
3256
3310
  enabled: z16.boolean().optional().default(false),
3257
3311
  prefix: z16.string().optional(),
@@ -3267,7 +3321,10 @@ var init_schema11 = __esm({
3267
3321
  audit: skillsConfigAuditOptionsSchema.optional(),
3268
3322
  injectInstructions: z16.enum(["off", "append", "prepend", "replace"]).optional().default("append"),
3269
3323
  scoring: z16.enum(["cosine", "bm25"]).optional(),
3270
- failOnInvalidSkills: z16.boolean().optional()
3324
+ failOnInvalidSkills: z16.boolean().optional(),
3325
+ externalProvider: z16.custom(isExternalSkillProvider, {
3326
+ message: `externalProvider must be an ExternalSkillProviderBase (${EXTERNAL_SKILL_PROVIDER_METHODS.join(", ")} functions)`
3327
+ }).optional()
3271
3328
  });
3272
3329
  }
3273
3330
  });
@@ -3859,6 +3916,7 @@ var frontMcpBaseSchema, frontMcpMultiAppSchema, frontMcpSplitByAppSchema, frontM
3859
3916
  var init_front_mcp_metadata = __esm({
3860
3917
  "libs/sdk/src/common/metadata/front-mcp.metadata.ts"() {
3861
3918
  "use strict";
3919
+ init_task_types();
3862
3920
  init_schemas();
3863
3921
  init_types();
3864
3922
  init_schema2();
@@ -3942,7 +4000,7 @@ var init_front_mcp_metadata = __esm({
3942
4000
  defaultTtlMs: z26.number().int().positive().optional(),
3943
4001
  maxTtlMs: z26.number().int().positive().optional(),
3944
4002
  defaultPollIntervalMs: z26.number().int().positive().optional(),
3945
- maxConcurrentPerSession: z26.number().int().positive().optional(),
4003
+ maxConcurrentPerSession: z26.number().int().positive().max(MAX_CONCURRENT_TASKS_PER_SESSION).optional(),
3946
4004
  strict: z26.boolean().optional(),
3947
4005
  runner: z26.enum(["in-process", "cli"]).optional(),
3948
4006
  sqlite: z26.object({
@@ -5590,7 +5648,7 @@ ${this.originalError.stack}`;
5590
5648
  });
5591
5649
 
5592
5650
  // libs/sdk/src/errors/task.error.ts
5593
- var TaskNotFoundError, TaskAlreadyTerminalError, TaskAugmentationNotSupportedError, TaskAugmentationRequiredError, TaskStoreNotInitializedError;
5651
+ var TaskNotFoundError, TaskAlreadyTerminalError, TaskAugmentationNotSupportedError, TaskAugmentationRequiredError, TaskConcurrencyLimitError, TaskStoreNotInitializedError;
5594
5652
  var init_task_error = __esm({
5595
5653
  "libs/sdk/src/errors/task.error.ts"() {
5596
5654
  "use strict";
@@ -5637,6 +5695,17 @@ var init_task_error = __esm({
5637
5695
  return { code: this.mcpErrorCode, message: this.getPublicMessage() };
5638
5696
  }
5639
5697
  };
5698
+ TaskConcurrencyLimitError = class extends PublicMcpError {
5699
+ maxConcurrent;
5700
+ constructor(maxConcurrent) {
5701
+ super(
5702
+ `Too many tasks in progress for this caller (at most ${maxConcurrent} at once). Wait for one to finish, or cancel one.`,
5703
+ "CONCURRENCY_LIMIT",
5704
+ 429
5705
+ );
5706
+ this.maxConcurrent = maxConcurrent;
5707
+ }
5708
+ };
5640
5709
  TaskStoreNotInitializedError = class extends InternalMcpError {
5641
5710
  constructor() {
5642
5711
  super("Task store is not initialized", "TASK_STORE_NOT_INITIALIZED");
@@ -6715,6 +6784,7 @@ __export(errors_exports, {
6715
6784
  TaskAlreadyTerminalError: () => TaskAlreadyTerminalError,
6716
6785
  TaskAugmentationNotSupportedError: () => TaskAugmentationNotSupportedError,
6717
6786
  TaskAugmentationRequiredError: () => TaskAugmentationRequiredError,
6787
+ TaskConcurrencyLimitError: () => TaskConcurrencyLimitError,
6718
6788
  TaskNotFoundError: () => TaskNotFoundError,
6719
6789
  TaskStoreNotInitializedError: () => TaskStoreNotInitializedError,
6720
6790
  TokenLeakDetectedError: () => TokenLeakDetectedError,
@@ -6956,7 +7026,7 @@ var init_dynamic_import_utils = __esm({
6956
7026
  // libs/sdk/src/common/availability/availability.utils.ts
6957
7027
  import {
6958
7028
  checkEntryAvailability,
6959
- getRuntimeContext as getRuntimeContext2,
7029
+ getRuntimeContext as getRuntimeContext3,
6960
7030
  isEntryAvailable
6961
7031
  } from "@frontmcp/utils";
6962
7032
  function callSurfaceOf(ctx) {
@@ -6969,15 +7039,15 @@ function isOfferedOnSurface(availability, surface) {
6969
7039
  }
6970
7040
  function availabilityForCall(availability, surface) {
6971
7041
  if (!isOfferedOnSurface(availability, surface)) return "not-offered";
6972
- return isEntryAvailable(availability, getRuntimeContext2()) ? "available" : "unavailable";
7042
+ return isEntryAvailable(availability, getRuntimeContext3()) ? "available" : "unavailable";
6973
7043
  }
6974
7044
  function entryUnavailableError(entryType, entryName, availability, surface) {
6975
- const ctx = getRuntimeContext2();
7045
+ const ctx = getRuntimeContext3();
6976
7046
  const { missingAxes } = checkEntryAvailability(availability, ctx, surface ? { surface } : void 0);
6977
7047
  return new EntryUnavailableError(entryType, entryName, availability, { ...ctx, surface }, missingAxes);
6978
7048
  }
6979
7049
  function logAvailabilityFiltering(registryKind, entries, logger) {
6980
- const ctx = getRuntimeContext2();
7050
+ const ctx = getRuntimeContext3();
6981
7051
  const constrained = [];
6982
7052
  const filtered = [];
6983
7053
  const emptyConstraints = [];
@@ -7407,35 +7477,25 @@ var init_skill_instructions_helper = __esm({
7407
7477
  }
7408
7478
  });
7409
7479
 
7410
- // libs/sdk/src/task/task.types.ts
7411
- function toWireShape(record) {
7412
- const wire = {
7413
- taskId: record.taskId,
7414
- status: record.status,
7415
- ttl: record.ttlMs,
7416
- createdAt: record.createdAt,
7417
- lastUpdatedAt: record.lastUpdatedAt
7418
- };
7419
- if (record.pollIntervalMs !== void 0) wire.pollInterval = record.pollIntervalMs;
7420
- if (record.statusMessage !== void 0) wire.statusMessage = record.statusMessage;
7421
- return wire;
7480
+ // libs/sdk/src/task/helpers/process-liveness.ts
7481
+ import { getHostname } from "@frontmcp/utils";
7482
+ function isLocalWorker(executor) {
7483
+ return executor.hostname === void 0 || executor.hostname === getHostname();
7422
7484
  }
7423
- function isTerminal(status) {
7424
- return status === "completed" || status === "failed" || status === "cancelled";
7485
+ function isAlive(pid) {
7486
+ if (!Number.isFinite(pid) || pid <= 0) return false;
7487
+ try {
7488
+ process.kill(pid, 0);
7489
+ return true;
7490
+ } catch (err) {
7491
+ const code = err?.code;
7492
+ if (code === "EPERM") return true;
7493
+ return false;
7494
+ }
7425
7495
  }
7426
- var TASK_DEFAULTS, RELATED_TASK_META_KEY;
7427
- var init_task_types = __esm({
7428
- "libs/sdk/src/task/task.types.ts"() {
7496
+ var init_process_liveness = __esm({
7497
+ "libs/sdk/src/task/helpers/process-liveness.ts"() {
7429
7498
  "use strict";
7430
- TASK_DEFAULTS = {
7431
- defaultTtlMs: 36e5,
7432
- // 1 hour
7433
- maxTtlMs: 864e5,
7434
- // 24 hours
7435
- defaultPollIntervalMs: 2e3,
7436
- maxConcurrentPerSession: 16
7437
- };
7438
- RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task";
7439
7499
  }
7440
7500
  });
7441
7501
 
@@ -7449,6 +7509,9 @@ import {
7449
7509
  function recordKey(sessionId, taskId) {
7450
7510
  return `${sessionId}:${taskId}`;
7451
7511
  }
7512
+ function slotKey(sessionId, slot) {
7513
+ return `${sessionId}:${slot}`;
7514
+ }
7452
7515
  function encodeCursor(offset) {
7453
7516
  return base64urlEncode(new TextEncoder().encode(JSON.stringify({ offset })));
7454
7517
  }
@@ -7463,17 +7526,21 @@ function decodeCursor(cursor) {
7463
7526
  }
7464
7527
  return 0;
7465
7528
  }
7466
- var TERMINAL_CHANNEL_PREFIX, CANCEL_CHANNEL_PREFIX, RECORDS_NAMESPACE, DEFAULT_PAGE_SIZE, StorageTaskStore;
7529
+ var TERMINAL_CHANNEL_PREFIX, CANCEL_CHANNEL_PREFIX, RECORDS_NAMESPACE, SLOTS_NAMESPACE, DEFAULT_PAGE_SIZE, StorageTaskStore;
7467
7530
  var init_storage_task_store = __esm({
7468
7531
  "libs/sdk/src/task/store/storage-task.store.ts"() {
7469
7532
  "use strict";
7533
+ init_process_liveness();
7534
+ init_task_types();
7470
7535
  TERMINAL_CHANNEL_PREFIX = "terminal:";
7471
7536
  CANCEL_CHANNEL_PREFIX = "cancel:";
7472
7537
  RECORDS_NAMESPACE = "records";
7538
+ SLOTS_NAMESPACE = "slots";
7473
7539
  DEFAULT_PAGE_SIZE = 50;
7474
7540
  StorageTaskStore = class {
7475
7541
  storage;
7476
7542
  records;
7543
+ slots;
7477
7544
  logger;
7478
7545
  terminalCallbacks = /* @__PURE__ */ new Map();
7479
7546
  terminalSubs = /* @__PURE__ */ new Map();
@@ -7483,6 +7550,7 @@ var init_storage_task_store = __esm({
7483
7550
  this.storage = storage;
7484
7551
  this.logger = logger;
7485
7552
  this.records = new TypedStorage(storage.namespace(RECORDS_NAMESPACE));
7553
+ this.slots = storage.namespace(SLOTS_NAMESPACE);
7486
7554
  }
7487
7555
  async create(record) {
7488
7556
  const ttlSeconds = expiresAtToTTL(record.expiresAt);
@@ -7496,6 +7564,24 @@ var init_storage_task_store = __esm({
7496
7564
  await this.records.set(key, record, { ttlSeconds });
7497
7565
  this.logger?.debug("[StorageTaskStore] created", { taskId: record.taskId, ttlSeconds });
7498
7566
  }
7567
+ /** A task holds one of its owner's `maxActive` slot keys, claimed by a write-if-absent, until it finishes. */
7568
+ async createWithinLimit(record, maxActive) {
7569
+ const ttlSeconds = expiresAtToTTL(record.expiresAt);
7570
+ if (ttlSeconds <= 0) {
7571
+ await this.create(record);
7572
+ return true;
7573
+ }
7574
+ const slot = await this.acquireSlot(record, maxActive, ttlSeconds);
7575
+ if (slot === void 0) return false;
7576
+ const slotted = { ...record, concurrencySlot: slot };
7577
+ try {
7578
+ await this.create(slotted);
7579
+ } catch (err) {
7580
+ await this.releaseSlot(slotted);
7581
+ throw err;
7582
+ }
7583
+ return true;
7584
+ }
7499
7585
  async get(taskId, sessionId) {
7500
7586
  const record = await this.records.get(recordKey(sessionId, taskId));
7501
7587
  if (!record) return null;
@@ -7524,10 +7610,65 @@ var init_storage_task_store = __esm({
7524
7610
  return null;
7525
7611
  }
7526
7612
  await this.records.set(recordKey(sessionId, taskId), merged, { ttlSeconds });
7613
+ if (isTerminal(merged.status)) await this.releaseSlot(merged);
7527
7614
  return merged;
7528
7615
  }
7529
7616
  async delete(taskId, sessionId) {
7617
+ const existing = await this.records.get(recordKey(sessionId, taskId));
7530
7618
  await this.records.delete(recordKey(sessionId, taskId));
7619
+ if (existing) await this.releaseSlot(existing);
7620
+ }
7621
+ async acquireSlot(record, maxActive, ttlSeconds) {
7622
+ const owner = record.sessionId;
7623
+ const slotKeys = Array.from({ length: maxActive }, (_, slot) => slotKey(owner, slot));
7624
+ const holders = await this.slots.mget(slotKeys);
7625
+ const claimed = await this.claimFreeSlot(owner, holders, record.taskId, ttlSeconds);
7626
+ if (claimed !== void 0 || !await this.reclaimSlots(owner, holders)) return claimed;
7627
+ return this.claimFreeSlot(owner, await this.slots.mget(slotKeys), record.taskId, ttlSeconds);
7628
+ }
7629
+ async claimFreeSlot(owner, holders, taskId, ttlSeconds) {
7630
+ for (const [slot, holder] of holders.entries()) {
7631
+ if (holder !== null) continue;
7632
+ const key = slotKey(owner, slot);
7633
+ await this.slots.set(key, taskId, { ttlSeconds, ifNotExists: true });
7634
+ if (await this.slots.get(key) === taskId) return slot;
7635
+ }
7636
+ return void 0;
7637
+ }
7638
+ /** Free slots held by finished tasks or by tasks whose CLI worker died on this host (marked failed); others stay. */
7639
+ async reclaimSlots(owner, holders) {
7640
+ let reclaimed = false;
7641
+ for (const holderTaskId of holders) {
7642
+ if (holderTaskId === null) continue;
7643
+ const holder = await this.records.get(recordKey(owner, holderTaskId));
7644
+ if (!holder) continue;
7645
+ if (isTerminal(holder.status)) {
7646
+ await this.releaseSlot(holder);
7647
+ reclaimed = true;
7648
+ continue;
7649
+ }
7650
+ const workerPid = holder.executor?.host === "cli" && isLocalWorker(holder.executor) ? holder.executor.pid : void 0;
7651
+ if (workerPid === void 0 || isAlive(workerPid)) continue;
7652
+ const failed = await this.update(holderTaskId, owner, {
7653
+ status: "failed",
7654
+ statusMessage: "Task runner exited before completing the task"
7655
+ });
7656
+ if (failed) await this.publishTerminal(failed);
7657
+ reclaimed = true;
7658
+ }
7659
+ return reclaimed;
7660
+ }
7661
+ /** Best-effort: a slot left behind is reclaimed the next time its owner reaches the cap. */
7662
+ async releaseSlot(record) {
7663
+ if (record.concurrencySlot === void 0) return;
7664
+ try {
7665
+ await this.slots.deleteIfEquals(slotKey(record.sessionId, record.concurrencySlot), record.taskId);
7666
+ } catch (err) {
7667
+ this.logger?.warn("[StorageTaskStore] failed to release a concurrency slot", {
7668
+ taskId: record.taskId,
7669
+ error: err instanceof Error ? err.message : String(err)
7670
+ });
7671
+ }
7531
7672
  }
7532
7673
  async list(sessionId, opts = {}) {
7533
7674
  const pageSize = Math.max(1, Math.min(opts.pageSize ?? DEFAULT_PAGE_SIZE, 500));
@@ -7759,7 +7900,7 @@ var require_dist = __commonJS({
7759
7900
  withBusyRetry: () => withBusyRetry
7760
7901
  });
7761
7902
  module.exports = __toCommonJS2(index_exports);
7762
- var import_utils133 = __require("@frontmcp/utils");
7903
+ var import_utils137 = __require("@frontmcp/utils");
7763
7904
  var SqliteDecryptionError = class extends Error {
7764
7905
  code = "SQLITE_DECRYPTION_FAILED";
7765
7906
  constructor() {
@@ -7774,25 +7915,25 @@ var require_dist = __commonJS({
7774
7915
  var KEY_LENGTH = 32;
7775
7916
  function deriveEncryptionKey(secret) {
7776
7917
  const ikm = new TextEncoder().encode(secret);
7777
- return (0, import_utils133.hkdfSha256)(ikm, HKDF_SALT, HKDF_INFO, KEY_LENGTH);
7918
+ return (0, import_utils137.hkdfSha256)(ikm, HKDF_SALT, HKDF_INFO, KEY_LENGTH);
7778
7919
  }
7779
7920
  var SEPARATOR = ":";
7780
7921
  function encryptValue(key, plaintext) {
7781
- const iv = (0, import_utils133.randomBytes)(12);
7922
+ const iv = (0, import_utils137.randomBytes)(12);
7782
7923
  const plaintextBytes = new TextEncoder().encode(plaintext);
7783
- const { ciphertext, tag } = (0, import_utils133.encryptAesGcm)(key, plaintextBytes, iv);
7784
- return [(0, import_utils133.base64urlEncode)(iv), (0, import_utils133.base64urlEncode)(tag), (0, import_utils133.base64urlEncode)(ciphertext)].join(SEPARATOR);
7924
+ const { ciphertext, tag } = (0, import_utils137.encryptAesGcm)(key, plaintextBytes, iv);
7925
+ return [(0, import_utils137.base64urlEncode)(iv), (0, import_utils137.base64urlEncode)(tag), (0, import_utils137.base64urlEncode)(ciphertext)].join(SEPARATOR);
7785
7926
  }
7786
7927
  function decryptValue(key, encrypted) {
7787
7928
  const parts = encrypted.split(SEPARATOR);
7788
7929
  if (parts.length !== 3) {
7789
7930
  throw new Error("Invalid encrypted value format");
7790
7931
  }
7791
- const iv = (0, import_utils133.base64urlDecode)(parts[0]);
7792
- const tag = (0, import_utils133.base64urlDecode)(parts[1]);
7793
- const ciphertext = (0, import_utils133.base64urlDecode)(parts[2]);
7932
+ const iv = (0, import_utils137.base64urlDecode)(parts[0]);
7933
+ const tag = (0, import_utils137.base64urlDecode)(parts[1]);
7934
+ const ciphertext = (0, import_utils137.base64urlDecode)(parts[2]);
7794
7935
  try {
7795
- return new TextDecoder().decode((0, import_utils133.decryptAesGcm)(key, ciphertext, iv, tag));
7936
+ return new TextDecoder().decode((0, import_utils137.decryptAesGcm)(key, ciphertext, iv, tag));
7796
7937
  } catch {
7797
7938
  throw new SqliteDecryptionError();
7798
7939
  }
@@ -8308,6 +8449,7 @@ var require_dist = __commonJS({
8308
8449
  }
8309
8450
  };
8310
8451
  var import_node_events2 = __require("node:events");
8452
+ var import_utils510 = __require("@frontmcp/utils");
8311
8453
  var defaultLivenessProbe = (pid) => {
8312
8454
  try {
8313
8455
  process.kill(pid, 0);
@@ -8374,6 +8516,13 @@ var require_dist = __commonJS({
8374
8516
  insert: this.db.prepare(
8375
8517
  "INSERT INTO mcp_tasks (task_id, session_id, status, expires_at, created_at, updated_at, executor_pid, record_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
8376
8518
  ),
8519
+ // One statement, so the count and the insert are atomic across every process sharing the file.
8520
+ insertWithinLimit: this.db.prepare(
8521
+ "INSERT INTO mcp_tasks (task_id, session_id, status, expires_at, created_at, updated_at, executor_pid, record_json) SELECT ?, ?, ?, ?, ?, ?, ?, ? WHERE (SELECT COUNT(*) FROM mcp_tasks WHERE session_id = ? AND status IN ('working', 'input_required') AND expires_at > ?) < ?"
8522
+ ),
8523
+ unfinishedWithWorker: this.db.prepare(
8524
+ "SELECT * FROM mcp_tasks WHERE session_id = ? AND status IN ('working', 'input_required') AND expires_at > ? AND executor_pid IS NOT NULL"
8525
+ ),
8377
8526
  get: this.db.prepare("SELECT * FROM mcp_tasks WHERE task_id = ? AND session_id = ?"),
8378
8527
  update: this.db.prepare(
8379
8528
  "UPDATE mcp_tasks SET status = ?, expires_at = ?, updated_at = ?, executor_pid = ?, record_json = ? WHERE task_id = ? AND session_id = ?"
@@ -8396,16 +8545,17 @@ var require_dist = __commonJS({
8396
8545
  this.logger?.warn?.("[SqliteTaskStore] create: record already expired", { taskId: record.taskId });
8397
8546
  return;
8398
8547
  }
8399
- this.prepared().insert.run(
8400
- record.taskId,
8401
- record.sessionId,
8402
- record.status,
8403
- record.expiresAt,
8404
- new Date(record.createdAt).getTime(),
8405
- new Date(record.lastUpdatedAt).getTime(),
8406
- record.executor?.pid ?? null,
8407
- this.serializeRecord(record)
8408
- );
8548
+ this.prepared().insert.run(...this.rowValues(record));
8549
+ }
8550
+ /** Insert unless the owner has `maxActive` unfinished rows, after failing the ones whose CLI worker died. */
8551
+ async createWithinLimit(record, maxActive) {
8552
+ if (record.expiresAt <= Date.now()) {
8553
+ await this.create(record);
8554
+ return true;
8555
+ }
8556
+ if (this.insertWithinLimit(record, maxActive)) return true;
8557
+ if (!await this.failOrphanedTasks(record.sessionId)) return false;
8558
+ return this.insertWithinLimit(record, maxActive);
8409
8559
  }
8410
8560
  async get(taskId, sessionId) {
8411
8561
  const row = this.prepared().get.get(taskId, sessionId);
@@ -8415,15 +8565,9 @@ var require_dist = __commonJS({
8415
8565
  return null;
8416
8566
  }
8417
8567
  const record = this.rowToRecord(row);
8418
- if ((record.status === "working" || record.status === "input_required") && record.executor?.host === "cli" && typeof record.executor.pid === "number" && !this.liveness(record.executor.pid)) {
8419
- const patched = await this.update(taskId, sessionId, {
8420
- status: "failed",
8421
- statusMessage: "Task runner exited before completing the task"
8422
- });
8423
- if (patched) {
8424
- await this.publishTerminal(patched);
8425
- return patched;
8426
- }
8568
+ if (this.isOrphaned(record)) {
8569
+ const failed = await this.failOrphan(record);
8570
+ if (failed) return failed;
8427
8571
  }
8428
8572
  return record;
8429
8573
  }
@@ -8467,18 +8611,9 @@ var require_dist = __commonJS({
8467
8611
  const rows = this.prepared().listBySession.all(sessionId, Date.now(), pageSize, offset);
8468
8612
  const tasks = [];
8469
8613
  for (const row of rows) {
8470
- let record = this.rowToRecord(row);
8471
- if ((record.status === "working" || record.status === "input_required") && record.executor?.host === "cli" && typeof record.executor.pid === "number" && !this.liveness(record.executor.pid)) {
8472
- const patched = await this.update(record.taskId, sessionId, {
8473
- status: "failed",
8474
- statusMessage: "Task runner exited before completing the task"
8475
- });
8476
- if (patched) {
8477
- await this.publishTerminal(patched);
8478
- record = patched;
8479
- }
8480
- }
8481
- tasks.push(record);
8614
+ const record = this.rowToRecord(row);
8615
+ const failed = this.isOrphaned(record) ? await this.failOrphan(record) : null;
8616
+ tasks.push(failed ?? record);
8482
8617
  }
8483
8618
  const total = this.prepared().countBySession.get(sessionId, Date.now()).n;
8484
8619
  const page = { tasks };
@@ -8533,6 +8668,50 @@ var require_dist = __commonJS({
8533
8668
  getDatabase() {
8534
8669
  return this.db;
8535
8670
  }
8671
+ insertWithinLimit(record, maxActive) {
8672
+ const inserted = this.prepared().insertWithinLimit.run(
8673
+ ...this.rowValues(record),
8674
+ record.sessionId,
8675
+ Date.now(),
8676
+ maxActive
8677
+ );
8678
+ return inserted.changes === 1;
8679
+ }
8680
+ /** Mark the owner's tasks whose CLI worker died as failed. Returns whether any were. */
8681
+ async failOrphanedTasks(sessionId) {
8682
+ const rows = this.prepared().unfinishedWithWorker.all(sessionId, Date.now());
8683
+ let failedAny = false;
8684
+ for (const row of rows) {
8685
+ const record = this.rowToRecord(row);
8686
+ if (this.isOrphaned(record) && await this.failOrphan(record)) failedAny = true;
8687
+ }
8688
+ return failedAny;
8689
+ }
8690
+ /** A worker on another host is never probed: its PID means nothing here. A record naming no host is probed. */
8691
+ isOrphaned(record) {
8692
+ return (record.status === "working" || record.status === "input_required") && record.executor?.host === "cli" && typeof record.executor.pid === "number" && (record.executor.hostname === void 0 || record.executor.hostname === (0, import_utils510.getHostname)()) && !this.liveness(record.executor.pid);
8693
+ }
8694
+ /** Publishes the terminal event so `tasks/result` waiters blocked on `subscribeTerminal` wake up now. */
8695
+ async failOrphan(record) {
8696
+ const failed = await this.update(record.taskId, record.sessionId, {
8697
+ status: "failed",
8698
+ statusMessage: "Task runner exited before completing the task"
8699
+ });
8700
+ if (failed) await this.publishTerminal(failed);
8701
+ return failed;
8702
+ }
8703
+ rowValues(record) {
8704
+ return [
8705
+ record.taskId,
8706
+ record.sessionId,
8707
+ record.status,
8708
+ record.expiresAt,
8709
+ new Date(record.createdAt).getTime(),
8710
+ new Date(record.lastUpdatedAt).getTime(),
8711
+ record.executor?.pid ?? null,
8712
+ this.serializeRecord(record)
8713
+ ];
8714
+ }
8536
8715
  rowToRecord(row) {
8537
8716
  const plaintext = this.encryptionKey ? decryptValue(this.encryptionKey, row.record_json) : row.record_json;
8538
8717
  return JSON.parse(plaintext);
@@ -8996,6 +9175,91 @@ var init_task_id = __esm({
8996
9175
  }
8997
9176
  });
8998
9177
 
9178
+ // libs/sdk/src/transport/mcp-handlers/mcp-error.utils.ts
9179
+ import { McpError as McpError2 } from "@frontmcp/protocol";
9180
+ import { isProduction as isProduction3 } from "@frontmcp/utils";
9181
+ function hasJsonRpcError(err) {
9182
+ return typeof err?.toJsonRpcError === "function";
9183
+ }
9184
+ function jsonRpcCodeForStatus(statusCode) {
9185
+ if (statusCode === 401) return MCP_ERROR_CODES.UNAUTHORIZED;
9186
+ if (statusCode === 403) return MCP_ERROR_CODES.FORBIDDEN;
9187
+ return statusCode < 500 ? MCP_ERROR_CODES.INVALID_PARAMS : MCP_ERROR_CODES.INTERNAL_ERROR;
9188
+ }
9189
+ function errorBehindFlowControl(err) {
9190
+ if (!(err instanceof FlowControl)) return err;
9191
+ const original = err.originalError;
9192
+ if (err.type === "fail" && original !== void 0) return original;
9193
+ return new InternalMcpError(`Flow ended with: ${err.type}`);
9194
+ }
9195
+ function toReportedError(err) {
9196
+ const failure = errorBehindFlowControl(err);
9197
+ return failure instanceof McpError2 ? failure : toMcpError(failure);
9198
+ }
9199
+ function toSdkMcpError(err) {
9200
+ const error = toReportedError(err);
9201
+ if (error instanceof McpError2) return error;
9202
+ if (hasJsonRpcError(error)) {
9203
+ const jsonRpc = error.toJsonRpcError();
9204
+ return new McpError2(jsonRpc.code, jsonRpc.message, { ...jsonRpc.data, errorId: error.errorId });
9205
+ }
9206
+ const data = { errorId: error.errorId, code: error.code };
9207
+ if (error.isPublic) {
9208
+ return new McpError2(jsonRpcCodeForStatus(error.statusCode), error.getPublicMessage(), data);
9209
+ }
9210
+ const message = isProduction3() ? error.getPublicMessage() : error.message;
9211
+ return new McpError2(MCP_ERROR_CODES.INTERNAL_ERROR, message, data);
9212
+ }
9213
+ var init_mcp_error_utils = __esm({
9214
+ "libs/sdk/src/transport/mcp-handlers/mcp-error.utils.ts"() {
9215
+ "use strict";
9216
+ init_common();
9217
+ init_errors();
9218
+ }
9219
+ });
9220
+
9221
+ // libs/sdk/src/transport/mcp-handlers/call-tool-error.utils.ts
9222
+ import { CallToolResultSchema } from "@frontmcp/protocol";
9223
+ function toolCallErrorResult(error, options) {
9224
+ const { errorHandler, toolName, logger } = options;
9225
+ if (error instanceof FlowControl) {
9226
+ if (error.type === "respond") {
9227
+ const parsed = CallToolResultSchema.safeParse(error.output);
9228
+ if (parsed.success) return parsed.data;
9229
+ logger?.error("FlowControl.respond has invalid output", {
9230
+ tool: toolName,
9231
+ validationErrors: parsed.error.issues
9232
+ });
9233
+ return formatMcpErrorResponse(new InternalMcpError("FlowControl output is not a valid CallToolResult"));
9234
+ }
9235
+ const original = error.originalError;
9236
+ if (error.type === "fail" && original !== void 0) {
9237
+ return errorHandler.handle(original, { toolName });
9238
+ }
9239
+ logger?.warn(`FlowControl ended with type: ${error.type}`, {
9240
+ tool: toolName,
9241
+ type: error.type,
9242
+ output: error.output
9243
+ });
9244
+ return formatMcpErrorResponse(new InternalMcpError(`Flow ended with: ${error.type}`));
9245
+ }
9246
+ if (error instanceof InputRequiredSignal || error instanceof MissingClientCapabilityError) {
9247
+ throw error;
9248
+ }
9249
+ if (error instanceof TaskAugmentationNotSupportedError || error instanceof TaskAugmentationRequiredError || error instanceof ToolCredentialsRequiredError) {
9250
+ throw toSdkMcpError(error);
9251
+ }
9252
+ return errorHandler.handle(error, { toolName });
9253
+ }
9254
+ var init_call_tool_error_utils = __esm({
9255
+ "libs/sdk/src/transport/mcp-handlers/call-tool-error.utils.ts"() {
9256
+ "use strict";
9257
+ init_common();
9258
+ init_errors();
9259
+ init_mcp_error_utils();
9260
+ }
9261
+ });
9262
+
8999
9263
  // libs/sdk/src/task/helpers/task-runner.ts
9000
9264
  import { runRequestExclusive } from "@frontmcp/utils";
9001
9265
  function runTaskInBackground(params) {
@@ -9048,7 +9312,15 @@ async function executeTask(params) {
9048
9312
  if (paused) notifier.sendStatus(paused);
9049
9313
  return;
9050
9314
  }
9051
- outcomeErr = toJsonRpcError(err);
9315
+ try {
9316
+ outcomeOk = toolCallErrorResult(err, {
9317
+ errorHandler: new ErrorHandler({ logger }),
9318
+ toolName: String(cleanedRequestParams["name"] ?? "unknown"),
9319
+ logger
9320
+ });
9321
+ } catch (protocolError) {
9322
+ outcomeErr = toJsonRpcError(protocolError);
9323
+ }
9052
9324
  }
9053
9325
  const current = await store.get(taskId, sessionId);
9054
9326
  if (!current) {
@@ -9079,10 +9351,11 @@ async function executeTask(params) {
9079
9351
  });
9080
9352
  if (!controller.signal.aborted) controller.abort("task-runner error");
9081
9353
  try {
9354
+ const failure = toJsonRpcError(err);
9082
9355
  const failed = await store.update(taskId, sessionId, {
9083
9356
  status: "failed",
9084
- statusMessage: err instanceof Error ? err.message : "Task runner failed",
9085
- outcome: { kind: "error", error: toJsonRpcError(err) }
9357
+ statusMessage: failure.message,
9358
+ outcome: { kind: "error", error: failure }
9086
9359
  });
9087
9360
  if (failed) {
9088
9361
  try {
@@ -9104,30 +9377,16 @@ async function executeTask(params) {
9104
9377
  }
9105
9378
  }
9106
9379
  function toJsonRpcError(err) {
9107
- if (err && typeof err === "object") {
9108
- const anyErr = err;
9109
- if (typeof anyErr.toJsonRpcError === "function") {
9110
- return anyErr.toJsonRpcError();
9111
- }
9112
- if (typeof anyErr.mcpErrorCode === "number") {
9113
- return {
9114
- code: anyErr.mcpErrorCode,
9115
- message: typeof anyErr.message === "string" ? anyErr.message : "Task execution error"
9116
- };
9117
- }
9118
- if (typeof anyErr.code === "number" && typeof anyErr.message === "string") {
9119
- return { code: anyErr.code, message: anyErr.message };
9120
- }
9121
- }
9122
- return {
9123
- code: -32603,
9124
- message: err instanceof Error ? err.message : "Internal error"
9125
- };
9380
+ const sdkError = toSdkMcpError(err);
9381
+ const message = sdkError.message.replace(/^MCP error -?\d+: /, "");
9382
+ return sdkError.data === void 0 ? { code: sdkError.code, message } : { code: sdkError.code, message, data: sdkError.data };
9126
9383
  }
9127
9384
  var init_task_runner = __esm({
9128
9385
  "libs/sdk/src/task/helpers/task-runner.ts"() {
9129
9386
  "use strict";
9130
9387
  init_errors();
9388
+ init_call_tool_error_utils();
9389
+ init_mcp_error_utils();
9131
9390
  init_task_types();
9132
9391
  }
9133
9392
  });
@@ -9166,26 +9425,8 @@ var init_in_process_task_runner = __esm({
9166
9425
  }
9167
9426
  });
9168
9427
 
9169
- // libs/sdk/src/task/helpers/process-liveness.ts
9170
- function isAlive(pid) {
9171
- if (!Number.isFinite(pid) || pid <= 0) return false;
9172
- try {
9173
- process.kill(pid, 0);
9174
- return true;
9175
- } catch (err) {
9176
- const code = err?.code;
9177
- if (code === "EPERM") return true;
9178
- return false;
9179
- }
9180
- }
9181
- var init_process_liveness = __esm({
9182
- "libs/sdk/src/task/helpers/process-liveness.ts"() {
9183
- "use strict";
9184
- }
9185
- });
9186
-
9187
9428
  // libs/sdk/src/task/helpers/cli-task-runner.ts
9188
- import { getSpawnFn } from "@frontmcp/utils";
9429
+ import { getHostname as getHostname2, getSpawnFn } from "@frontmcp/utils";
9189
9430
  var RUN_TASK_SUBCOMMAND, RUN_TASK_ENV_VAR, CliTaskRunner;
9190
9431
  var init_cli_task_runner = __esm({
9191
9432
  "libs/sdk/src/task/helpers/cli-task-runner.ts"() {
@@ -9231,7 +9472,8 @@ var init_cli_task_runner = __esm({
9231
9472
  executor: {
9232
9473
  host: "cli",
9233
9474
  pid: child.pid,
9234
- spawnedAt: (/* @__PURE__ */ new Date()).toISOString()
9475
+ spawnedAt: (/* @__PURE__ */ new Date()).toISOString(),
9476
+ hostname: getHostname2()
9235
9477
  }
9236
9478
  });
9237
9479
  }
@@ -9261,7 +9503,16 @@ var init_cli_task_runner = __esm({
9261
9503
  }
9262
9504
  }
9263
9505
  async cancel(record) {
9264
- const pid = record.executor?.pid;
9506
+ const executor = record.executor;
9507
+ const pid = executor?.pid;
9508
+ if (executor && !isLocalWorker(executor)) {
9509
+ this.deps.logger?.debug?.("[CliTaskRunner] cancel: the worker runs on another host; not signalling it", {
9510
+ taskId: record.taskId,
9511
+ pid,
9512
+ hostname: executor.hostname
9513
+ });
9514
+ return;
9515
+ }
9265
9516
  if (!pid || !isAlive(pid)) {
9266
9517
  this.deps.logger?.debug?.("[CliTaskRunner] cancel: worker already dead", {
9267
9518
  taskId: record.taskId,
@@ -9846,54 +10097,8 @@ var init_build_scoped_server_options = __esm({
9846
10097
  }
9847
10098
  });
9848
10099
 
9849
- // libs/sdk/src/transport/mcp-handlers/mcp-error.utils.ts
9850
- import { McpError as McpError2 } from "@frontmcp/protocol";
9851
- import { isProduction as isProduction3 } from "@frontmcp/utils";
9852
- function hasJsonRpcError(err) {
9853
- return typeof err?.toJsonRpcError === "function";
9854
- }
9855
- function jsonRpcCodeForStatus(statusCode) {
9856
- if (statusCode === 401) return MCP_ERROR_CODES.UNAUTHORIZED;
9857
- if (statusCode === 403) return MCP_ERROR_CODES.FORBIDDEN;
9858
- return statusCode < 500 ? MCP_ERROR_CODES.INVALID_PARAMS : MCP_ERROR_CODES.INTERNAL_ERROR;
9859
- }
9860
- function errorBehindFlowControl(err) {
9861
- if (!(err instanceof FlowControl)) return err;
9862
- const original = err.originalError;
9863
- if (err.type === "fail" && original !== void 0) return original;
9864
- return new InternalMcpError(`Flow ended with: ${err.type}`);
9865
- }
9866
- function toReportedError(err) {
9867
- const failure = errorBehindFlowControl(err);
9868
- return failure instanceof McpError2 ? failure : toMcpError(failure);
9869
- }
9870
- function toSdkMcpError(err) {
9871
- const error = toReportedError(err);
9872
- if (error instanceof McpError2) return error;
9873
- if (hasJsonRpcError(error)) {
9874
- const jsonRpc = error.toJsonRpcError();
9875
- return new McpError2(jsonRpc.code, jsonRpc.message, { ...jsonRpc.data, errorId: error.errorId });
9876
- }
9877
- const data = { errorId: error.errorId, code: error.code };
9878
- if (error.isPublic) {
9879
- return new McpError2(jsonRpcCodeForStatus(error.statusCode), error.getPublicMessage(), data);
9880
- }
9881
- const message = isProduction3() ? error.getPublicMessage() : error.message;
9882
- return new McpError2(MCP_ERROR_CODES.INTERNAL_ERROR, message, data);
9883
- }
9884
- var init_mcp_error_utils = __esm({
9885
- "libs/sdk/src/transport/mcp-handlers/mcp-error.utils.ts"() {
9886
- "use strict";
9887
- init_common();
9888
- init_errors();
9889
- }
9890
- });
9891
-
9892
10100
  // libs/sdk/src/transport/mcp-handlers/call-tool-request.handler.ts
9893
- import {
9894
- CallToolRequestSchema,
9895
- CallToolResultSchema
9896
- } from "@frontmcp/protocol";
10101
+ import { CallToolRequestSchema } from "@frontmcp/protocol";
9897
10102
  function callToolRequestHandler({
9898
10103
  scope
9899
10104
  }) {
@@ -9911,37 +10116,7 @@ function callToolRequestHandler({
9911
10116
  logger.verbose("tools/call completed", { tool: toolName, durationMs: Date.now() - start });
9912
10117
  return result;
9913
10118
  } catch (e) {
9914
- if (e instanceof FlowControl) {
9915
- if (e.type === "respond") {
9916
- const parseResult = CallToolResultSchema.safeParse(e.output);
9917
- if (parseResult.success) {
9918
- return parseResult.data;
9919
- }
9920
- logger.error("FlowControl.respond has invalid output", {
9921
- tool: toolName,
9922
- validationErrors: parseResult.error.issues
9923
- });
9924
- return formatMcpErrorResponse(new InternalMcpError("FlowControl output is not a valid CallToolResult"));
9925
- }
9926
- if (e.type === "fail") {
9927
- const original = e.originalError;
9928
- if (original !== void 0) {
9929
- return errorHandler.handle(original, { toolName });
9930
- }
9931
- }
9932
- logger.warn(`FlowControl ended with type: ${e.type}`, { tool: toolName, type: e.type, output: e.output });
9933
- return formatMcpErrorResponse(new InternalMcpError(`Flow ended with: ${e.type}`));
9934
- }
9935
- if (e instanceof InputRequiredSignal || e instanceof MissingClientCapabilityError) {
9936
- throw e;
9937
- }
9938
- if (e instanceof TaskAugmentationNotSupportedError || e instanceof TaskAugmentationRequiredError) {
9939
- throw toSdkMcpError(e);
9940
- }
9941
- if (e instanceof ToolCredentialsRequiredError) {
9942
- throw toSdkMcpError(e);
9943
- }
9944
- return errorHandler.handle(e, { toolName });
10119
+ return toolCallErrorResult(e, { errorHandler, toolName, logger });
9945
10120
  }
9946
10121
  }
9947
10122
  };
@@ -9949,9 +10124,8 @@ function callToolRequestHandler({
9949
10124
  var init_call_tool_request_handler = __esm({
9950
10125
  "libs/sdk/src/transport/mcp-handlers/call-tool-request.handler.ts"() {
9951
10126
  "use strict";
9952
- init_common();
9953
10127
  init_errors();
9954
- init_mcp_error_utils();
10128
+ init_call_tool_error_utils();
9955
10129
  init_mcp_surface();
9956
10130
  }
9957
10131
  });
@@ -11008,11 +11182,52 @@ var init_notification = __esm({
11008
11182
  }
11009
11183
  });
11010
11184
 
11185
+ // libs/sdk/src/transport/mcp-20260728/protocol-20260728.constants.ts
11186
+ import { PROTOCOL_2026_07_28 } from "@frontmcp/protocol";
11187
+ var FRONTMCP_SUPPORTED_PROTOCOL_VERSIONS, INITIALIZE_PROTOCOL_VERSIONS, LEGACY_PROTOCOL_VERSIONS, PROTOCOL_20260728_ONLY_METHODS, MCP_HEADERS, NAME_FROM_PARAMS_NAME, NAME_FROM_PARAMS_URI, DEFAULT_CACHE_TTL_MS, CACHEABLE_METHODS, ADVERTISED_EXTENSIONS;
11188
+ var init_protocol_20260728_constants = __esm({
11189
+ "libs/sdk/src/transport/mcp-20260728/protocol-20260728.constants.ts"() {
11190
+ "use strict";
11191
+ FRONTMCP_SUPPORTED_PROTOCOL_VERSIONS = [
11192
+ PROTOCOL_2026_07_28,
11193
+ "2025-11-25",
11194
+ "2025-06-18",
11195
+ "2025-03-26",
11196
+ "2024-11-05"
11197
+ ];
11198
+ INITIALIZE_PROTOCOL_VERSIONS = FRONTMCP_SUPPORTED_PROTOCOL_VERSIONS.filter(
11199
+ (version) => version !== PROTOCOL_2026_07_28
11200
+ );
11201
+ LEGACY_PROTOCOL_VERSIONS = ["2024-10-07", "2024-11-05", "2025-03-26", "2025-06-18", "2025-11-25"];
11202
+ PROTOCOL_20260728_ONLY_METHODS = ["server/discover", "subscriptions/listen"];
11203
+ MCP_HEADERS = {
11204
+ protocolVersion: "mcp-protocol-version",
11205
+ method: "mcp-method",
11206
+ name: "mcp-name",
11207
+ /** Prefix for `x-mcp-header`-derived parameter headers. */
11208
+ paramPrefix: "mcp-param-"
11209
+ };
11210
+ NAME_FROM_PARAMS_NAME = ["tools/call", "prompts/get"];
11211
+ NAME_FROM_PARAMS_URI = ["resources/read"];
11212
+ DEFAULT_CACHE_TTL_MS = {
11213
+ "server/discover": 3e5,
11214
+ "tools/list": 6e4,
11215
+ "prompts/list": 6e4,
11216
+ "resources/list": 6e4,
11217
+ "resources/templates/list": 6e4,
11218
+ "resources/read": 0
11219
+ };
11220
+ CACHEABLE_METHODS = Object.keys(DEFAULT_CACHE_TTL_MS);
11221
+ ADVERTISED_EXTENSIONS = {
11222
+ "io.modelcontextprotocol/tasks": {}
11223
+ };
11224
+ }
11225
+ });
11226
+
11011
11227
  // libs/sdk/src/transport/mcp-handlers/initialize-request.handler.ts
11012
11228
  import {
11013
11229
  InitializeRequestSchema,
11014
- LATEST_PROTOCOL_VERSION,
11015
- SUPPORTED_PROTOCOL_VERSIONS
11230
+ LATEST_PROTOCOL_VERSION
11016
11231
  } from "@frontmcp/protocol";
11017
11232
  function persistInitPayload(sessionId, initPayload, ctx) {
11018
11233
  updateSessionPayload(sessionId, initPayload);
@@ -11122,7 +11337,7 @@ function initializeRequestHandler({
11122
11337
  }
11123
11338
  }
11124
11339
  const requestedVersion = request.params.protocolVersion;
11125
- const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION;
11340
+ const protocolVersion = INITIALIZE_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION;
11126
11341
  const configuredInfo = scope.metadata?.info ?? { name: "FrontMcpServer", version: "0.0.1" };
11127
11342
  const composed = await composeInstructions?.(ctx);
11128
11343
  const instructions = composed !== void 0 ? composed : serverOptions.instructions;
@@ -11148,6 +11363,7 @@ var init_initialize_request_handler = __esm({
11148
11363
  init_session_id_utils();
11149
11364
  init_errors();
11150
11365
  init_notification();
11366
+ init_protocol_20260728_constants();
11151
11367
  }
11152
11368
  });
11153
11369
 
@@ -13501,6 +13717,32 @@ var init_flow_context_providers = __esm({
13501
13717
  }
13502
13718
  });
13503
13719
 
13720
+ // libs/sdk/src/skill/skill-mode.utils.ts
13721
+ function detectSkillsOnlyMode(query) {
13722
+ if (!query) return false;
13723
+ const mode = query["mode"];
13724
+ if (mode === "skills_only") {
13725
+ return true;
13726
+ }
13727
+ if (Array.isArray(mode) && mode.includes("skills_only")) {
13728
+ return true;
13729
+ }
13730
+ return false;
13731
+ }
13732
+ function isSkillsOnlySession(sessionPayload) {
13733
+ return sessionPayload?.skillsOnlyMode === true;
13734
+ }
13735
+ function isSkillsOnlyRequest(authInfo, context) {
13736
+ return isSkillsOnlySession(authInfo?.sessionIdPayload) || context?.has(SKILLS_ONLY_REQUEST) === true;
13737
+ }
13738
+ var SKILLS_ONLY_REQUEST;
13739
+ var init_skill_mode_utils = __esm({
13740
+ "libs/sdk/src/skill/skill-mode.utils.ts"() {
13741
+ "use strict";
13742
+ SKILLS_ONLY_REQUEST = /* @__PURE__ */ Symbol.for("frontmcp:skills:skills-only-request");
13743
+ }
13744
+ });
13745
+
13504
13746
  // libs/sdk/src/front-mcp/front-mcp.tokens.ts
13505
13747
  var FrontMcpConfig;
13506
13748
  var init_front_mcp_tokens2 = __esm({
@@ -14171,7 +14413,7 @@ import { WIDGET_CALL_META_KEY } from "@frontmcp/uipack/bridge-runtime";
14171
14413
  import {
14172
14414
  awaitOutsideRequest as awaitOutsideRequest3,
14173
14415
  findNonFiniteNumber,
14174
- getRuntimeContext as getRuntimeContext3,
14416
+ getRuntimeContext as getRuntimeContext4,
14175
14417
  isDebug,
14176
14418
  isDevelopment,
14177
14419
  randomUUID as randomUUID7
@@ -14213,6 +14455,7 @@ var init_call_tool_flow = __esm({
14213
14455
  init_resolved_entries();
14214
14456
  init_hooks_utils();
14215
14457
  init_flow_context_providers();
14458
+ init_skill_mode_utils();
14216
14459
  init_task_id();
14217
14460
  init_task_notifier();
14218
14461
  init_task_types();
@@ -14266,6 +14509,8 @@ var init_call_tool_flow = __esm({
14266
14509
  plan5 = {
14267
14510
  pre: [
14268
14511
  "parseInput",
14512
+ // `?mode=skills_only`: a client's call is answered as for an unknown tool
14513
+ "checkSkillsOnlyMode",
14269
14514
  "ensureRemoteCapabilities",
14270
14515
  "findTool",
14271
14516
  "checkPublicAccess",
@@ -14341,6 +14586,14 @@ var init_call_tool_flow = __esm({
14341
14586
  });
14342
14587
  this.logger.verbose("parseInput:done");
14343
14588
  }
14589
+ async checkSkillsOnlyMode() {
14590
+ const callerCtx = this.input.ctx;
14591
+ if (callerCtx?.internalCall || callerCtx?.agentPrivateCall || getRunningTool()) return;
14592
+ if (!isSkillsOnlyRequest(this.state.authInfo, this.tryGetContext())) return;
14593
+ const { name: name45 } = this.state.required.input;
14594
+ this.logger.verbose(`checkSkillsOnlyMode: refusing tool "${name45}" in skills-only mode`);
14595
+ throw new ToolNotFoundError(name45);
14596
+ }
14344
14597
  async ensureRemoteCapabilities() {
14345
14598
  this.logger.verbose("ensureRemoteCapabilities:start");
14346
14599
  const remoteAppCount = await loadRemoteAppCapabilities(
@@ -14366,7 +14619,7 @@ var init_call_tool_flow = __esm({
14366
14619
  const unavailable = allUnfiltered.find((t) => exactNames.includes(t.fullName) || exactNames.includes(t.name));
14367
14620
  if (unavailable && isOfferedOnSurface(unavailable.metadata.availableWhen, callSurface)) {
14368
14621
  const error = entryUnavailableError("Tool", name45, unavailable.metadata.availableWhen, callSurface);
14369
- const ctx = getRuntimeContext3();
14622
+ const ctx = getRuntimeContext4();
14370
14623
  this.logger.warn(
14371
14624
  `findTool: tool "${name45}" exists but is unavailable \u2014 constraint=${JSON.stringify(unavailable.metadata.availableWhen)}, missingAxes=${JSON.stringify(error.missingAxes)}, current=[os=${ctx.os}, runtime=${ctx.runtime}, deployment=${ctx.deployment}, provider=${ctx.provider}, target=${ctx.target}, surface=${callSurface ?? "none"}, env=${ctx.env}]`
14372
14625
  );
@@ -14387,7 +14640,7 @@ var init_call_tool_flow = __esm({
14387
14640
  }
14388
14641
  this.logger = this.logger.child(`CallToolFlow(${name45})`);
14389
14642
  this.state.set("tool", tool);
14390
- this.logger.info(`findTool: tool "${name45}" found`);
14643
+ this.logger.verbose(`findTool: tool "${name45}" found`);
14391
14644
  this.logger.verbose("findTool:done");
14392
14645
  }
14393
14646
  async createTaskIfRequested() {
@@ -14452,7 +14705,10 @@ var init_call_tool_flow = __esm({
14452
14705
  if (this.state.progressToken !== void 0) {
14453
14706
  record.progressToken = this.state.progressToken;
14454
14707
  }
14455
- await store.create(record);
14708
+ const maxActive = config.maxConcurrentPerSession ?? TASK_DEFAULTS.maxConcurrentPerSession;
14709
+ if (!await store.createWithinLimit(record, maxActive)) {
14710
+ throw new TaskConcurrencyLimitError(maxActive);
14711
+ }
14456
14712
  const notifier = new TaskNotifier(this.scope.notifications, this.logger);
14457
14713
  notifier.sendStatus(record);
14458
14714
  const runner = registry.runner;
@@ -15154,7 +15410,7 @@ ${JSON.stringify(error.schema, null, 2)}
15154
15410
  result._meta = { ...result._meta, ...uiMeta };
15155
15411
  }
15156
15412
  }
15157
- this.logger.info("finalize: sending response", {
15413
+ this.logger.verbose("finalize: sending response", {
15158
15414
  tool: tool.metadata.name,
15159
15415
  hasContent: Array.isArray(result.content) && result.content.length > 0,
15160
15416
  contentParts: Array.isArray(result.content) ? result.content.length : 0,
@@ -15174,6 +15430,9 @@ ${JSON.stringify(error.schema, null, 2)}
15174
15430
  __decorateClass([
15175
15431
  Stage5("parseInput")
15176
15432
  ], CallToolFlow.prototype, "parseInput", 1);
15433
+ __decorateClass([
15434
+ Stage5("checkSkillsOnlyMode")
15435
+ ], CallToolFlow.prototype, "checkSkillsOnlyMode", 1);
15177
15436
  __decorateClass([
15178
15437
  Stage5("ensureRemoteCapabilities")
15179
15438
  ], CallToolFlow.prototype, "ensureRemoteCapabilities", 1);
@@ -16157,6 +16416,7 @@ var init_direct_server = __esm({
16157
16416
 
16158
16417
  // libs/sdk/src/direct/create.ts
16159
16418
  import "reflect-metadata";
16419
+ import { setMachineIdOverride } from "@frontmcp/utils";
16160
16420
  function buildConfig(config) {
16161
16421
  const {
16162
16422
  appName,
@@ -16184,6 +16444,7 @@ function buildConfig(config) {
16184
16444
  Reflect.defineMetadata(FrontMcpLocalAppTokens.type, true, syntheticApp);
16185
16445
  const appMeta = {
16186
16446
  name: name45,
16447
+ standalone: false,
16187
16448
  tools,
16188
16449
  resources,
16189
16450
  prompts,
@@ -16193,7 +16454,6 @@ function buildConfig(config) {
16193
16454
  authProviders,
16194
16455
  agents,
16195
16456
  skills,
16196
- auth,
16197
16457
  jobs: jobDefinitions,
16198
16458
  workflows: workflowDefinitions
16199
16459
  };
@@ -16203,13 +16463,8 @@ function buildConfig(config) {
16203
16463
  Reflect.defineMetadata(token, appMeta[key], syntheticApp);
16204
16464
  }
16205
16465
  }
16206
- return { ...serverOptions, apps: [syntheticApp], serve: false };
16207
- }
16208
- function loadUtils() {
16209
- return importWithRequireFallback(
16210
- () => import("@frontmcp/utils"),
16211
- () => __require("@frontmcp/utils")
16212
- );
16466
+ const logging = serverOptions.logging ?? { level: logLevelFromEnv() ?? 3 /* Warn */ };
16467
+ return { ...serverOptions, ...auth !== void 0 && { auth }, logging, apps: [syntheticApp], serve: false };
16213
16468
  }
16214
16469
  async function create(config) {
16215
16470
  const { cacheKey } = config;
@@ -16223,7 +16478,6 @@ async function create(config) {
16223
16478
  const machineIdWasSet = config.machineId !== void 0;
16224
16479
  try {
16225
16480
  if (machineIdWasSet) {
16226
- const { setMachineIdOverride } = await loadUtils();
16227
16481
  setMachineIdOverride(config.machineId);
16228
16482
  }
16229
16483
  const fullConfig = buildConfig(config);
@@ -16236,7 +16490,6 @@ async function create(config) {
16236
16490
  instanceCache2.delete(cacheKey);
16237
16491
  }
16238
16492
  if (machineIdWasSet) {
16239
- const { setMachineIdOverride } = await loadUtils();
16240
16493
  setMachineIdOverride(void 0);
16241
16494
  }
16242
16495
  return originalDispose();
@@ -16248,7 +16501,6 @@ async function create(config) {
16248
16501
  instanceCache2.delete(cacheKey);
16249
16502
  }
16250
16503
  if (machineIdWasSet) {
16251
- const { setMachineIdOverride } = await loadUtils();
16252
16504
  setMachineIdOverride(void 0);
16253
16505
  }
16254
16506
  throw error;
@@ -16267,7 +16519,7 @@ var init_create = __esm({
16267
16519
  "libs/sdk/src/direct/create.ts"() {
16268
16520
  "use strict";
16269
16521
  init_tokens();
16270
- init_dynamic_import_utils();
16522
+ init_schema4();
16271
16523
  instanceCache2 = /* @__PURE__ */ new Map();
16272
16524
  }
16273
16525
  });
@@ -16334,7 +16586,7 @@ var init_health_probes = __esm({
16334
16586
  });
16335
16587
 
16336
16588
  // libs/sdk/src/health/health.service.ts
16337
- import { getRuntimeContext as getRuntimeContext4, sha256Hex as sha256Hex2 } from "@frontmcp/utils";
16589
+ import { getRuntimeContext as getRuntimeContext5, sha256Hex as sha256Hex2 } from "@frontmcp/utils";
16338
16590
  var processStartTime, HealthService;
16339
16591
  var init_health_service = __esm({
16340
16592
  "libs/sdk/src/health/health.service.ts"() {
@@ -16407,7 +16659,7 @@ var init_health_service = __esm({
16407
16659
  * Get liveness response. Synchronous, no I/O.
16408
16660
  */
16409
16661
  getHealthz() {
16410
- const ctx = getRuntimeContext4();
16662
+ const ctx = getRuntimeContext5();
16411
16663
  return {
16412
16664
  status: "ok",
16413
16665
  server: {
@@ -16528,7 +16780,7 @@ var init_health_service = __esm({
16528
16780
  if (this.config.includeDetails !== void 0) {
16529
16781
  return this.config.includeDetails;
16530
16782
  }
16531
- const ctx = getRuntimeContext4();
16783
+ const ctx = getRuntimeContext5();
16532
16784
  return ctx.env !== "production";
16533
16785
  }
16534
16786
  };
@@ -16536,12 +16788,16 @@ var init_health_service = __esm({
16536
16788
  });
16537
16789
 
16538
16790
  // libs/sdk/src/health/health.routes.ts
16539
- import { getRuntimeContext as getRuntimeContext5 } from "@frontmcp/utils";
16791
+ import { getRuntimeContext as getRuntimeContext6 } from "@frontmcp/utils";
16792
+ function servedHealthPaths(config = {}) {
16793
+ if (config.enabled === false) return [];
16794
+ return [config.healthzPath ?? "/healthz", config.readyzPath ?? "/readyz"];
16795
+ }
16540
16796
  function isReadyzEnabled(config) {
16541
16797
  if (config.readyz?.enabled !== void 0) {
16542
16798
  return config.readyz.enabled;
16543
16799
  }
16544
- const ctx = getRuntimeContext5();
16800
+ const ctx = getRuntimeContext6();
16545
16801
  return ctx.runtime !== "edge" && ctx.deployment !== "serverless";
16546
16802
  }
16547
16803
  function registerHealthRoutes(server, healthService, config) {
@@ -20046,45 +20302,6 @@ var init_record_builders = __esm({
20046
20302
  }
20047
20303
  });
20048
20304
 
20049
- // libs/sdk/src/transport/mcp-20260728/protocol-20260728.constants.ts
20050
- import { PROTOCOL_2026_07_28 } from "@frontmcp/protocol";
20051
- var FRONTMCP_SUPPORTED_PROTOCOL_VERSIONS, LEGACY_PROTOCOL_VERSIONS, PROTOCOL_20260728_ONLY_METHODS, MCP_HEADERS, NAME_FROM_PARAMS_NAME, NAME_FROM_PARAMS_URI, DEFAULT_CACHE_TTL_MS, CACHEABLE_METHODS, ADVERTISED_EXTENSIONS;
20052
- var init_protocol_20260728_constants = __esm({
20053
- "libs/sdk/src/transport/mcp-20260728/protocol-20260728.constants.ts"() {
20054
- "use strict";
20055
- FRONTMCP_SUPPORTED_PROTOCOL_VERSIONS = [
20056
- PROTOCOL_2026_07_28,
20057
- "2025-11-25",
20058
- "2025-06-18",
20059
- "2025-03-26",
20060
- "2024-11-05"
20061
- ];
20062
- LEGACY_PROTOCOL_VERSIONS = ["2024-10-07", "2024-11-05", "2025-03-26", "2025-06-18", "2025-11-25"];
20063
- PROTOCOL_20260728_ONLY_METHODS = ["server/discover", "subscriptions/listen"];
20064
- MCP_HEADERS = {
20065
- protocolVersion: "mcp-protocol-version",
20066
- method: "mcp-method",
20067
- name: "mcp-name",
20068
- /** Prefix for `x-mcp-header`-derived parameter headers. */
20069
- paramPrefix: "mcp-param-"
20070
- };
20071
- NAME_FROM_PARAMS_NAME = ["tools/call", "prompts/get"];
20072
- NAME_FROM_PARAMS_URI = ["resources/read"];
20073
- DEFAULT_CACHE_TTL_MS = {
20074
- "server/discover": 3e5,
20075
- "tools/list": 6e4,
20076
- "prompts/list": 6e4,
20077
- "resources/list": 6e4,
20078
- "resources/templates/list": 6e4,
20079
- "resources/read": 0
20080
- };
20081
- CACHEABLE_METHODS = Object.keys(DEFAULT_CACHE_TTL_MS);
20082
- ADVERTISED_EXTENSIONS = {
20083
- "io.modelcontextprotocol/tasks": {}
20084
- };
20085
- }
20086
- });
20087
-
20088
20305
  // libs/sdk/src/transport/mcp-20260728/header-codec.ts
20089
20306
  function isSentinelEncoded(value) {
20090
20307
  return value.startsWith(SENTINEL_PREFIX) && value.endsWith(SENTINEL_SUFFIX) && value.length >= SENTINEL_PREFIX.length + SENTINEL_SUFFIX.length;
@@ -21043,16 +21260,17 @@ function clientSupportsTasks(clientCapabilities) {
21043
21260
  return TASKS_EXTENSION_ID in extensions;
21044
21261
  }
21045
21262
  function taskToWire20260728(record) {
21263
+ const status = record.status === "failed" && record.outcome?.kind === "ok" ? "completed" : record.status;
21046
21264
  const wire = {
21047
21265
  taskId: record.taskId,
21048
- status: record.status,
21266
+ status,
21049
21267
  createdAt: record.createdAt,
21050
21268
  lastUpdatedAt: record.lastUpdatedAt,
21051
21269
  ttlMs: record.ttlMs
21052
21270
  };
21053
21271
  if (record.pollIntervalMs !== void 0) wire["pollIntervalMs"] = record.pollIntervalMs;
21054
21272
  if (record.statusMessage !== void 0) wire["statusMessage"] = record.statusMessage;
21055
- if (record.status === "completed" && record.outcome?.kind === "ok") {
21273
+ if (status === "completed" && record.outcome?.kind === "ok") {
21056
21274
  wire["result"] = record.outcome.data;
21057
21275
  }
21058
21276
  if (record.status === "failed" && record.outcome?.kind === "error") {
@@ -21079,7 +21297,7 @@ function resolveTaskOwner(principal) {
21079
21297
  return { ok: true, owner: `principal:${principal}` };
21080
21298
  }
21081
21299
  async function dispatchTasksMethod(options) {
21082
- const { scope, method, params, owner, resume } = options;
21300
+ const { scope, method, params, owner, authInfo, resume } = options;
21083
21301
  const store = scope.taskStore;
21084
21302
  if (!store) {
21085
21303
  return { kind: "error", status: 200, error: { code: -32603, message: "Task store is not configured" } };
@@ -21094,14 +21312,17 @@ async function dispatchTasksMethod(options) {
21094
21312
  return { kind: "result", result: taskToWire20260728(record) };
21095
21313
  }
21096
21314
  if (method === "tasks/cancel") {
21097
- if (TERMINAL_TASK_STATUSES.includes(record.status)) {
21098
- return { kind: "result", result: {} };
21315
+ if (TERMINAL_TASK_STATUSES.includes(record.status)) return { kind: "result", result: {} };
21316
+ try {
21317
+ await scope.runFlowForOutput("tasks:cancel", {
21318
+ request: { method: "tasks/cancel", params: { taskId } },
21319
+ ctx: { authInfo }
21320
+ });
21321
+ } catch (error) {
21322
+ if (error instanceof TaskAlreadyTerminalError) return { kind: "result", result: {} };
21323
+ if (error instanceof TaskNotFoundError) return { kind: "error", status: 200, error: TASK_NOT_FOUND };
21324
+ throw error;
21099
21325
  }
21100
- await store.update(taskId, owner, {
21101
- status: "cancelled",
21102
- statusMessage: "The task was cancelled by the client."
21103
- });
21104
- await store.publishCancel(taskId, owner);
21105
21326
  return { kind: "result", result: {} };
21106
21327
  }
21107
21328
  const inputResponses = params["inputResponses"];
@@ -21136,6 +21357,7 @@ var TASKS_EXTENSION_ID, TASKS_EXTENSION_METHODS, TERMINAL_TASK_STATUSES, TASK_NO
21136
21357
  var init_tasks_extension = __esm({
21137
21358
  "libs/sdk/src/transport/mcp-20260728/tasks-extension.ts"() {
21138
21359
  "use strict";
21360
+ init_errors();
21139
21361
  TASKS_EXTENSION_ID = "io.modelcontextprotocol/tasks";
21140
21362
  TASKS_EXTENSION_METHODS = ["tasks/get", "tasks/update", "tasks/cancel"];
21141
21363
  TERMINAL_TASK_STATUSES = ["completed", "failed", "cancelled"];
@@ -21281,15 +21503,17 @@ async function dispatch20260728(options) {
21281
21503
  if (!ownership.ok) {
21282
21504
  return { kind: "error", status: 200, error: { code: -32602, message: ownership.reason } };
21283
21505
  }
21506
+ const ownerAuthInfo = { ...authInfo ?? {}, sessionId: ownership.owner };
21284
21507
  const outcome = await dispatchTasksMethod({
21285
21508
  scope,
21286
21509
  method,
21287
21510
  params,
21288
21511
  owner: ownership.owner,
21512
+ authInfo: ownerAuthInfo,
21289
21513
  resume: (record) => resumeTask({
21290
21514
  scope,
21291
21515
  record,
21292
- authInfo: { ...authInfo ?? {}, sessionId: ownership.owner },
21516
+ authInfo: ownerAuthInfo,
21293
21517
  clientCapabilities,
21294
21518
  frontmcpContext,
21295
21519
  clientDeclaredRevision
@@ -23669,7 +23893,7 @@ var init_get_prompt_flow = __esm({
23669
23893
  async findPrompt() {
23670
23894
  this.logger.verbose("findPrompt:start");
23671
23895
  const { name: name45 } = this.state.required.input;
23672
- this.logger.info(`findPrompt: looking for prompt with name "${name45}"`);
23896
+ this.logger.verbose(`findPrompt: looking for prompt with name "${name45}"`);
23673
23897
  const prompt = resolvedPrompts.take(this.rawInput, name45) ?? findPromptForGet(this.scope.prompts, name45);
23674
23898
  if (!prompt) {
23675
23899
  this.logger.warn(`findPrompt: prompt "${name45}" not found`);
@@ -23689,7 +23913,7 @@ var init_get_prompt_flow = __esm({
23689
23913
  this.state.set("promptOwnerId", prompt.owner?.id);
23690
23914
  this.logger = this.logger.child(`GetPromptFlow(${name45})`);
23691
23915
  this.state.set("prompt", prompt);
23692
- this.logger.info(`findPrompt: prompt "${prompt.name}" found`);
23916
+ this.logger.verbose(`findPrompt: prompt "${prompt.name}" found`);
23693
23917
  this.logger.verbose("findPrompt:done");
23694
23918
  }
23695
23919
  async checkPublicAccess() {
@@ -23964,7 +24188,7 @@ var init_prompts_list_flow = __esm({
23964
24188
  this.logger.verbose("ensureRemoteCapabilities:done");
23965
24189
  }
23966
24190
  async findPrompts() {
23967
- this.logger.info("findPrompts:start");
24191
+ this.logger.verbose("findPrompts:start");
23968
24192
  try {
23969
24193
  const prompts = [];
23970
24194
  const seenPromptIds = /* @__PURE__ */ new Set();
@@ -23978,7 +24202,9 @@ var init_prompts_list_flow = __esm({
23978
24202
  prompts.push({ ownerName: prompt.owner.id, prompt });
23979
24203
  }
23980
24204
  }
23981
- this.logger.info(`findPrompts: total prompts collected=${prompts.length} (deduped from ${scopePrompts.length})`);
24205
+ this.logger.verbose(
24206
+ `findPrompts: total prompts collected=${prompts.length} (deduped from ${scopePrompts.length})`
24207
+ );
23982
24208
  if (prompts.length === 0) {
23983
24209
  this.logger.warn("findPrompts: no prompts found");
23984
24210
  }
@@ -24041,7 +24267,7 @@ var init_prompts_list_flow = __esm({
24041
24267
  const extra = conflicts.size > 5 ? `, +${conflicts.size - 5} more` : "";
24042
24268
  this.logger.warn(`resolveConflicts: ${conflicts.size} name conflict(s) detected: ${preview}${extra}`);
24043
24269
  } else {
24044
- this.logger.info("resolveConflicts: no name conflicts detected");
24270
+ this.logger.verbose("resolveConflicts: no name conflicts detected");
24045
24271
  }
24046
24272
  const resolved = found.map(({ ownerName, prompt }) => {
24047
24273
  const baseName = prompt.metadata.name;
@@ -24068,9 +24294,9 @@ var init_prompts_list_flow = __esm({
24068
24294
  }));
24069
24295
  const preview = this.sample(prompts.map((p) => p.name)).join(", ");
24070
24296
  const extra = prompts.length > 5 ? `, +${prompts.length - 5} more` : "";
24071
- this.logger.info(`parsePrompts: prepared ${prompts.length} prompt descriptor(s): ${preview}${extra}`);
24297
+ this.logger.verbose(`parsePrompts: prepared ${prompts.length} prompt descriptor(s): ${preview}${extra}`);
24072
24298
  this.respond({ prompts });
24073
- this.logger.info("parsePrompts: response sent");
24299
+ this.logger.verbose("parsePrompts: response sent");
24074
24300
  this.logger.verbose("parsePrompts:done");
24075
24301
  } catch (error) {
24076
24302
  if (error instanceof FlowControl) throw error;
@@ -24283,7 +24509,7 @@ var init_prompt_types = __esm({
24283
24509
 
24284
24510
  // libs/sdk/src/prompt/prompt.registry.ts
24285
24511
  import { getMetadata as getMetadata9, tokenName as tokenName3 } from "@frontmcp/di";
24286
- import { ensureMaxLen, getRuntimeContext as getRuntimeContext6, isEntryAvailable as isEntryAvailable2, sepFor as sepFor2 } from "@frontmcp/utils";
24512
+ import { ensureMaxLen, getRuntimeContext as getRuntimeContext7, isEntryAvailable as isEntryAvailable2, sepFor as sepFor2 } from "@frontmcp/utils";
24287
24513
  function dedupLineage(l) {
24288
24514
  const out = [];
24289
24515
  for (const o of l) {
@@ -24500,7 +24726,7 @@ var init_prompt_registry = __esm({
24500
24726
  * Get all prompts
24501
24727
  */
24502
24728
  getPrompts(includeHidden = false) {
24503
- const ctx = getRuntimeContext6();
24729
+ const ctx = getRuntimeContext7();
24504
24730
  const all = this.listAllIndexed();
24505
24731
  return all.filter((r) => {
24506
24732
  const meta = r.instance.metadata;
@@ -24954,9 +25180,9 @@ var init_read_resource_flow = __esm({
24954
25180
  async findResource() {
24955
25181
  this.logger.verbose("findResource:start");
24956
25182
  const { uri } = this.state.required.input;
24957
- this.logger.info(`findResource: looking for resource with URI "${uri}"`);
25183
+ this.logger.verbose(`findResource: looking for resource with URI "${uri}"`);
24958
25184
  if (isUIResourceUri(uri)) {
24959
- this.logger.info(`findResource: detected UI resource URI "${uri}"`);
25185
+ this.logger.verbose(`findResource: detected UI resource URI "${uri}"`);
24960
25186
  const { sessionId, authInfo } = this.state;
24961
25187
  const platformType = authInfo?.sessionIdPayload?.platformType ?? this.tryGetContext()?.platformType ?? (sessionId ? this.scope.notifications.getPlatformType(sessionId) : void 0);
24962
25188
  this.logger.verbose(`findResource: platform type for session: ${platformType ?? "unknown"}`);
@@ -24972,7 +25198,7 @@ var init_read_resource_flow = __esm({
24972
25198
  }
24973
25199
  this.state.set("isUIResource", true);
24974
25200
  this.state.set("uiResourceResult", uiResult.result);
24975
- this.logger.info(`findResource: UI resource "${uri}" resolved from cache`);
25201
+ this.logger.verbose(`findResource: UI resource "${uri}" resolved from cache`);
24976
25202
  this.logger.verbose("findResource:done");
24977
25203
  return;
24978
25204
  }
@@ -25004,7 +25230,9 @@ var init_read_resource_flow = __esm({
25004
25230
  this.logger = this.logger.child(`ReadResourceFlow(${uri})`);
25005
25231
  this.state.set("resource", match.instance);
25006
25232
  this.state.set("params", match.params);
25007
- this.logger.info(`findResource: resource "${match.instance.name}" found (template: ${match.instance.isTemplate})`);
25233
+ this.logger.verbose(
25234
+ `findResource: resource "${match.instance.name}" found (template: ${match.instance.isTemplate})`
25235
+ );
25008
25236
  this.logger.verbose("findResource:done");
25009
25237
  }
25010
25238
  async checkEntryAuthorities() {
@@ -25275,7 +25503,7 @@ var init_resource_templates_list_flow = __esm({
25275
25503
  this.logger.verbose("ensureRemoteCapabilities:done");
25276
25504
  }
25277
25505
  async findTemplates() {
25278
- this.logger.info("findTemplates:start");
25506
+ this.logger.verbose("findTemplates:start");
25279
25507
  try {
25280
25508
  const templates = [];
25281
25509
  const callSurface = callSurfaceOf(this.rawInput?.ctx);
@@ -25285,7 +25513,7 @@ var init_resource_templates_list_flow = __esm({
25285
25513
  if (template.uriTemplate && this.scope.resources.findByUriTemplate(template.uriTemplate) !== template) continue;
25286
25514
  templates.push({ ownerName: template.owner.id, template });
25287
25515
  }
25288
- this.logger.info(`findTemplates: total templates collected=${templates.length}`);
25516
+ this.logger.verbose(`findTemplates: total templates collected=${templates.length}`);
25289
25517
  if (templates.length === 0) {
25290
25518
  this.logger.warn("findTemplates: no resource templates found");
25291
25519
  }
@@ -25335,7 +25563,7 @@ var init_resource_templates_list_flow = __esm({
25335
25563
  const extra = conflicts.size > 5 ? `, +${conflicts.size - 5} more` : "";
25336
25564
  this.logger.warn(`resolveConflicts: ${conflicts.size} name conflict(s) detected: ${preview}${extra}`);
25337
25565
  } else {
25338
- this.logger.info("resolveConflicts: no name conflicts detected");
25566
+ this.logger.verbose("resolveConflicts: no name conflicts detected");
25339
25567
  }
25340
25568
  const resolved = found.map(({ ownerName, template }) => {
25341
25569
  const baseName = template.metadata.name;
@@ -25374,11 +25602,11 @@ var init_resource_templates_list_flow = __esm({
25374
25602
  });
25375
25603
  const preview = this.sample(resourceTemplates.map((t) => t.name)).join(", ");
25376
25604
  const extra = resourceTemplates.length > 5 ? `, +${resourceTemplates.length - 5} more` : "";
25377
- this.logger.info(
25605
+ this.logger.verbose(
25378
25606
  `parseTemplates: prepared ${resourceTemplates.length} template descriptor(s): ${preview}${extra}`
25379
25607
  );
25380
25608
  this.respond({ resourceTemplates });
25381
- this.logger.info("parseTemplates: response sent");
25609
+ this.logger.verbose("parseTemplates: response sent");
25382
25610
  this.logger.verbose("parseTemplates:done");
25383
25611
  } catch (error) {
25384
25612
  if (error instanceof FlowControl) throw error;
@@ -25513,7 +25741,7 @@ var init_resources_list_flow = __esm({
25513
25741
  this.logger.verbose("ensureRemoteCapabilities:done");
25514
25742
  }
25515
25743
  async findResources() {
25516
- this.logger.info("findResources:start");
25744
+ this.logger.verbose("findResources:start");
25517
25745
  try {
25518
25746
  const resources = [];
25519
25747
  const seenResourceIds = /* @__PURE__ */ new Set();
@@ -25528,7 +25756,7 @@ var init_resources_list_flow = __esm({
25528
25756
  resources.push({ ownerName: resource.owner.id, resource });
25529
25757
  }
25530
25758
  }
25531
- this.logger.info(
25759
+ this.logger.verbose(
25532
25760
  `findResources: total resources collected=${resources.length} (deduped from ${scopeResources.length})`
25533
25761
  );
25534
25762
  if (resources.length === 0) {
@@ -25580,7 +25808,7 @@ var init_resources_list_flow = __esm({
25580
25808
  const extra = conflicts.size > 5 ? `, +${conflicts.size - 5} more` : "";
25581
25809
  this.logger.warn(`resolveConflicts: ${conflicts.size} name conflict(s) detected: ${preview}${extra}`);
25582
25810
  } else {
25583
- this.logger.info("resolveConflicts: no name conflicts detected");
25811
+ this.logger.verbose("resolveConflicts: no name conflicts detected");
25584
25812
  }
25585
25813
  const resolved = found.map(({ ownerName, resource }) => {
25586
25814
  const baseName = resource.metadata.name;
@@ -25635,9 +25863,9 @@ var init_resources_list_flow = __esm({
25635
25863
  });
25636
25864
  const preview = this.sample(resources.map((r) => r.name)).join(", ");
25637
25865
  const extra = resources.length > 5 ? `, +${resources.length - 5} more` : "";
25638
- this.logger.info(`parseResources: prepared ${resources.length} resource descriptor(s): ${preview}${extra}`);
25866
+ this.logger.verbose(`parseResources: prepared ${resources.length} resource descriptor(s): ${preview}${extra}`);
25639
25867
  this.respond({ resources });
25640
- this.logger.info("parseResources: response sent");
25868
+ this.logger.verbose("parseResources: response sent");
25641
25869
  this.logger.verbose("parseResources:done");
25642
25870
  } catch (error) {
25643
25871
  if (error instanceof FlowControl) throw error;
@@ -26149,7 +26377,7 @@ var init_resource_types = __esm({
26149
26377
 
26150
26378
  // libs/sdk/src/resource/resource.registry.ts
26151
26379
  import { getMetadata as getMetadata10, tokenName as tokenName4 } from "@frontmcp/di";
26152
- import { ensureMaxLen as ensureMaxLen2, getRuntimeContext as getRuntimeContext7, isEntryAvailable as isEntryAvailable3, sepFor as sepFor3 } from "@frontmcp/utils";
26380
+ import { ensureMaxLen as ensureMaxLen2, getRuntimeContext as getRuntimeContext8, isEntryAvailable as isEntryAvailable3, sepFor as sepFor3 } from "@frontmcp/utils";
26153
26381
  function dedupLineage2(l) {
26154
26382
  const out = [];
26155
26383
  for (const o of l) {
@@ -26374,7 +26602,7 @@ var init_resource_registry = __esm({
26374
26602
  * Get all static resources (not templates)
26375
26603
  */
26376
26604
  getResources(includeHidden = false) {
26377
- const ctx = getRuntimeContext7();
26605
+ const ctx = getRuntimeContext8();
26378
26606
  const all = this.listAllIndexed();
26379
26607
  return all.filter((r) => !r.isTemplate).filter((r) => {
26380
26608
  const meta = r.instance.metadata;
@@ -26387,7 +26615,7 @@ var init_resource_registry = __esm({
26387
26615
  * Get all resource templates
26388
26616
  */
26389
26617
  getResourceTemplates() {
26390
- const ctx = getRuntimeContext7();
26618
+ const ctx = getRuntimeContext8();
26391
26619
  const all = this.listAllIndexed();
26392
26620
  return all.filter((r) => r.isTemplate).filter((r) => isEntryAvailable3(r.instance.metadata.availableWhen, ctx)).map((r) => r.instance);
26393
26621
  }
@@ -26741,13 +26969,16 @@ var init_resource_registry = __esm({
26741
26969
  this.bump("reset");
26742
26970
  }
26743
26971
  /**
26744
- * Unregister a resource instance previously added via `registerResourceInstance`.
26972
+ * Unregister a resource previously added via `registerResourceInstance` or `registerDynamicResource`.
26745
26973
  * Returns true if the token was found and removed, false otherwise.
26746
26974
  *
26747
26975
  * Used by remote apps to drop the proxies of a previous capability discovery
26748
- * before registering the fresh ones.
26976
+ * before registering the fresh ones, and for the `skill://` resource of a removed skill.
26749
26977
  */
26750
26978
  unregisterResourceInstance(token) {
26979
+ this.tokens.delete(token);
26980
+ this.defs.delete(token);
26981
+ this.graph.delete(token);
26751
26982
  const existed = this.instances.delete(token);
26752
26983
  const before = this.localRows.length;
26753
26984
  this.localRows = this.localRows.filter((row) => row.token !== token);
@@ -26967,6 +27198,7 @@ var init_tools_list_flow = __esm({
26967
27198
  init_availability();
26968
27199
  init_pagination();
26969
27200
  init_errors();
27201
+ init_skill_mode_utils();
26970
27202
  init_ui();
26971
27203
  inputSchema14 = z62.object({
26972
27204
  request: ListToolsRequestSchema2,
@@ -27119,17 +27351,17 @@ var init_tools_list_flow = __esm({
27119
27351
  this.logger.verbose("ensureRemoteCapabilities:done");
27120
27352
  }
27121
27353
  async findTools() {
27122
- this.logger.info("findTools:start");
27354
+ this.logger.verbose("findTools:start");
27123
27355
  try {
27124
27356
  const { authInfo } = this.state.required;
27125
- if (authInfo.sessionIdPayload?.skillsOnlyMode) {
27126
- this.logger.info("findTools: skills-only mode - returning empty tools array");
27357
+ if (isSkillsOnlyRequest(authInfo, this.tryGetContext())) {
27358
+ this.logger.verbose("findTools: skills-only mode - returning empty tools array");
27127
27359
  this.state.set("tools", []);
27128
27360
  this.logger.verbose("findTools:done (skills-only mode)");
27129
27361
  return;
27130
27362
  }
27131
27363
  const apps = this.scope.apps.getApps();
27132
- this.logger.info(`findTools: discovered ${apps.length} app(s)`);
27364
+ this.logger.verbose(`findTools: discovered ${apps.length} app(s)`);
27133
27365
  const tools = [];
27134
27366
  const seenToolIds = /* @__PURE__ */ new Set();
27135
27367
  const usesInputRequests = this.tryGetContext()?.getMrtrExchange() !== void 0;
@@ -27144,7 +27376,7 @@ var init_tools_list_flow = __esm({
27144
27376
  tools.push({ appName: tool.owner.id, tool });
27145
27377
  }
27146
27378
  }
27147
- this.logger.info(`findTools: total tools collected=${tools.length}`);
27379
+ this.logger.verbose(`findTools: total tools collected=${tools.length}`);
27148
27380
  if (tools.length === 0) {
27149
27381
  this.logger.warn("findTools: no tools found across apps");
27150
27382
  }
@@ -27206,7 +27438,7 @@ var init_tools_list_flow = __esm({
27206
27438
  const extra = conflicts.size > 5 ? `, +${conflicts.size - 5} more` : "";
27207
27439
  this.logger.warn(`resolveConflicts: ${conflicts.size} name conflict(s) detected: ${preview}${extra}`);
27208
27440
  } else {
27209
- this.logger.info("resolveConflicts: no name conflicts detected");
27441
+ this.logger.verbose("resolveConflicts: no name conflicts detected");
27210
27442
  }
27211
27443
  const resolved = found.map(({ appName, tool }) => {
27212
27444
  const baseName = tool.metadata.id ?? tool.metadata.name;
@@ -27384,13 +27616,13 @@ var init_tools_list_flow = __esm({
27384
27616
  });
27385
27617
  const preview = this.sample(tools.map((t) => t.name)).join(", ");
27386
27618
  const extra = tools.length > 5 ? `, +${tools.length - 5} more` : "";
27387
- this.logger.info(`parseTools: prepared ${tools.length} tool descriptor(s): ${preview}${extra}`);
27619
+ this.logger.verbose(`parseTools: prepared ${tools.length} tool descriptor(s): ${preview}${extra}`);
27388
27620
  if (nextCursor) {
27389
27621
  this.respond({ tools, nextCursor });
27390
27622
  } else {
27391
27623
  this.respond({ tools });
27392
27624
  }
27393
- this.logger.info("parseTools: response sent");
27625
+ this.logger.verbose("parseTools: response sent");
27394
27626
  this.logger.verbose("parseTools:done");
27395
27627
  } catch (error) {
27396
27628
  if (error instanceof FlowControl) throw error;
@@ -27479,7 +27711,7 @@ var init_tool_types = __esm({
27479
27711
 
27480
27712
  // libs/sdk/src/tool/tool.registry.ts
27481
27713
  import { getMetadata as getMetadata11, tokenName as tokenName5 } from "@frontmcp/di";
27482
- import { ensureMaxLen as ensureMaxLen3, getRuntimeContext as getRuntimeContext8, isEntryAvailable as isEntryAvailable4, sepFor as sepFor4 } from "@frontmcp/utils";
27714
+ import { ensureMaxLen as ensureMaxLen3, getRuntimeContext as getRuntimeContext9, isEntryAvailable as isEntryAvailable4, sepFor as sepFor4 } from "@frontmcp/utils";
27483
27715
  function dedupLineage3(l) {
27484
27716
  const out = [];
27485
27717
  for (const o of l) {
@@ -27721,7 +27953,7 @@ var init_tool_registry = __esm({
27721
27953
  // This is a hard constraint — unlike hideFromDiscovery (soft listing hide) or
27722
27954
  // authorization (per-request in HTTP flows). Filtered entries cannot be listed or called.
27723
27955
  getTools(includeHidden = false) {
27724
- const ctx = getRuntimeContext8();
27956
+ const ctx = getRuntimeContext9();
27725
27957
  const local = [...this.localRows].flat().map((t) => t.instance);
27726
27958
  const adopted = [...this.adopted.values()].flat().map((t) => t.instance);
27727
27959
  return [...local, ...adopted].filter((t) => {
@@ -28731,7 +28963,7 @@ var init_config_symbols = __esm({
28731
28963
  });
28732
28964
 
28733
28965
  // libs/sdk/src/builtin/config/providers/env-loader.ts
28734
- import { fileExists as fileExists2, getCwd, getEnv as getEnv6, getRuntimeContext as getRuntimeContext9, pathResolve as pathResolve2, readFile, setEnv } from "@frontmcp/utils";
28966
+ import { fileExists as fileExists2, getCwd, getEnv as getEnv6, getRuntimeContext as getRuntimeContext10, pathResolve as pathResolve2, readFile, setEnv } from "@frontmcp/utils";
28735
28967
  function parseEnvContent(content) {
28736
28968
  const result = {};
28737
28969
  const lines = content.split("\n");
@@ -28758,7 +28990,7 @@ function parseEnvContent(content) {
28758
28990
  return result;
28759
28991
  }
28760
28992
  function canReadConfigFiles() {
28761
- return getRuntimeContext9().runtime !== "browser";
28993
+ return getRuntimeContext10().runtime !== "browser";
28762
28994
  }
28763
28995
  function processEnvEntries() {
28764
28996
  const env = {};
@@ -30985,6 +31217,18 @@ function matchMountedPath(pattern, path) {
30985
31217
  const expected = mount.split("/");
30986
31218
  const actual = path.split("/");
30987
31219
  if (actual.length < expected.length) return void 0;
31220
+ return captureSegments(expected, actual);
31221
+ }
31222
+ function matchRoutePath(pattern, path) {
31223
+ const expected = withoutTrailingSlash(pattern).split("/");
31224
+ const actual = withoutTrailingSlash(path).split("/");
31225
+ if (actual.length !== expected.length) return void 0;
31226
+ return captureSegments(expected, actual);
31227
+ }
31228
+ function withoutTrailingSlash(path) {
31229
+ return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
31230
+ }
31231
+ function captureSegments(expected, actual) {
30988
31232
  const params = {};
30989
31233
  for (let i = 0; i < expected.length; i++) {
30990
31234
  const segment = expected[i];
@@ -32225,7 +32469,7 @@ import {
32225
32469
  isFrontMcpCredentials as isFrontMcpCredentials2,
32226
32470
  providerHeadersCredentials
32227
32471
  } from "@frontmcp/auth";
32228
- import { getRuntimeContext as getRuntimeContext10, randomUUID as randomUUID13 } from "@frontmcp/utils";
32472
+ import { getRuntimeContext as getRuntimeContext11, randomUUID as randomUUID13 } from "@frontmcp/utils";
32229
32473
  var ExecutionContextBase;
32230
32474
  var init_execution_context_interface = __esm({
32231
32475
  "libs/sdk/src/common/interfaces/execution-context.interface.ts"() {
@@ -32234,6 +32478,7 @@ var init_execution_context_interface = __esm({
32234
32478
  init_context();
32235
32479
  init_frontmcp_context_storage();
32236
32480
  init_mcp_error();
32481
+ init_provider_errors();
32237
32482
  init_flow_interface();
32238
32483
  ExecutionContextBase = class {
32239
32484
  providers;
@@ -32393,13 +32638,12 @@ var init_execution_context_interface = __esm({
32393
32638
  get scope() {
32394
32639
  return this.providers.getScope();
32395
32640
  }
32396
- /**
32397
- * Try to get a dependency, returning undefined if not found.
32398
- */
32641
+ /** Try to get a dependency, returning undefined if not found; only a registered provider that fails to resolve warns. */
32399
32642
  tryGet(token) {
32400
32643
  try {
32401
32644
  return this.providers.get(token);
32402
32645
  } catch (e) {
32646
+ if (e instanceof ProviderNotAvailableError || e instanceof DependencyNotFoundError) return void 0;
32403
32647
  const msg = e instanceof Error ? e.message : String(e);
32404
32648
  this.logger.warn(`Failed to get provider ${String(token)}: ${msg}`);
32405
32649
  return void 0;
@@ -32576,7 +32820,7 @@ var init_execution_context_interface = __esm({
32576
32820
  * Get the current runtime context (platform, runtime, deployment, env).
32577
32821
  */
32578
32822
  get runtimeContext() {
32579
- return getRuntimeContext10();
32823
+ return getRuntimeContext11();
32580
32824
  }
32581
32825
  /**
32582
32826
  * Check if running on a specific OS platform.
@@ -34531,7 +34775,7 @@ var init_skill_instance = __esm({
34531
34775
 
34532
34776
  // libs/sdk/src/skill/skill.registry.ts
34533
34777
  import { tokenName as tokenName10 } from "@frontmcp/di";
34534
- import { getRuntimeContext as getRuntimeContext11, isEntryAvailable as isEntryAvailable5 } from "@frontmcp/utils";
34778
+ import { getRuntimeContext as getRuntimeContext12, isEntryAvailable as isEntryAvailable5 } from "@frontmcp/utils";
34535
34779
  function findIdPathCollision(skills) {
34536
34780
  const byPath = /* @__PURE__ */ new Map();
34537
34781
  for (const skill of skills) {
@@ -34821,7 +35065,7 @@ var init_skill_registry = __esm({
34821
35065
  return skillVis === visibility;
34822
35066
  });
34823
35067
  }
34824
- const ctx = getRuntimeContext11();
35068
+ const ctx = getRuntimeContext12();
34825
35069
  skills = skills.filter((s) => isEntryAvailable5(s.metadata.availableWhen, ctx));
34826
35070
  return skills;
34827
35071
  }
@@ -34843,7 +35087,7 @@ var init_skill_registry = __esm({
34843
35087
  getAlwaysLoadedSkills() {
34844
35088
  let skills = this.listAllIndexed().map((r) => r.instance);
34845
35089
  skills = skills.filter((s) => s.isAlwaysLoaded());
34846
- const ctx = getRuntimeContext11();
35090
+ const ctx = getRuntimeContext12();
34847
35091
  skills = skills.filter((s) => isEntryAvailable5(s.metadata.availableWhen, ctx));
34848
35092
  return skills;
34849
35093
  }
@@ -34974,7 +35218,7 @@ var init_skill_registry = __esm({
34974
35218
  }
34975
35219
  }
34976
35220
  if (localSkill) {
34977
- const ctx = getRuntimeContext11();
35221
+ const ctx = getRuntimeContext12();
34978
35222
  if (!isEntryAvailable5(localSkill.metadata.availableWhen, ctx)) {
34979
35223
  return void 0;
34980
35224
  }
@@ -35101,9 +35345,12 @@ var init_skill_registry = __esm({
35101
35345
  expectDynamicSkills() {
35102
35346
  this.dynamicSkillsExpected = true;
35103
35347
  }
35104
- /** Whether the scope serves skills: it has some, or a plugin registers them at runtime. */
35348
+ /**
35349
+ * Whether the scope serves skills: it has some, a plugin registers them at runtime, or a read-only
35350
+ * external provider serves them.
35351
+ */
35105
35352
  servesSkills() {
35106
- return this.dynamicSkillsExpected || this.hasAny();
35353
+ return this.dynamicSkillsExpected || this.hasAny() || this.externalProvider?.isReadOnly() === true;
35107
35354
  }
35108
35355
  /**
35109
35356
  * Get total skill count.
@@ -36047,7 +36294,11 @@ var init_plugin_registry = __esm({
36047
36294
  }));
36048
36295
  await targetHookScope.hooks.registerHooks(false, ...hooksWithOwner);
36049
36296
  }
36050
- pluginInstance.get = providers.get.bind(providers);
36297
+ const getFromPluginProviders = providers.get.bind(providers);
36298
+ pluginInstance.get = getFromPluginProviders;
36299
+ this.scope.onDispose(() => {
36300
+ if (pluginInstance.get === getFromPluginProviders) Reflect.deleteProperty(pluginInstance, "get");
36301
+ });
36051
36302
  const contextExtensions = rec.metadata.contextExtensions;
36052
36303
  if (contextExtensions && contextExtensions.length > 0) {
36053
36304
  installContextExtensions(rec.metadata.name, contextExtensions);
@@ -36340,7 +36591,7 @@ var init_call_agent_flow = __esm({
36340
36591
  throw new AgentNotFoundError(this.state.required.input.name);
36341
36592
  }
36342
36593
  const activeAgents = agents.getAgents(true);
36343
- this.logger.info(`findAgent: discovered ${activeAgents.length} active agent(s) (including hidden)`);
36594
+ this.logger.verbose(`findAgent: discovered ${activeAgents.length} active agent(s) (including hidden)`);
36344
36595
  const { name: toolName } = this.state.required.input;
36345
36596
  const agentId = toolName;
36346
36597
  const agent = findAgentForCall(agents, toolName);
@@ -36350,7 +36601,7 @@ var init_call_agent_flow = __esm({
36350
36601
  }
36351
36602
  this.logger = this.logger.child(`CallAgentFlow(${agent.name})`);
36352
36603
  this.state.set("agent", agent);
36353
- this.logger.info(`findAgent: agent "${agent.name}" found`);
36604
+ this.logger.verbose(`findAgent: agent "${agent.name}" found`);
36354
36605
  this.logger.verbose("findAgent:done");
36355
36606
  }
36356
36607
  async checkCallDepth() {
@@ -36651,7 +36902,7 @@ var init_call_agent_flow = __esm({
36651
36902
  }
36652
36903
  };
36653
36904
  }
36654
- this.logger.info("finalize: sending response", {
36905
+ this.logger.verbose("finalize: sending response", {
36655
36906
  agent: agent.metadata.name,
36656
36907
  hasContent: Array.isArray(result.content) && result.content.length > 0,
36657
36908
  contentParts: Array.isArray(result.content) ? result.content.length : 0,
@@ -38074,7 +38325,7 @@ var init_agent_instance = __esm({
38074
38325
 
38075
38326
  // libs/sdk/src/agent/agent.registry.ts
38076
38327
  import { tokenName as tokenName13 } from "@frontmcp/di";
38077
- import { getRuntimeContext as getRuntimeContext12, isEntryAvailable as isEntryAvailable6 } from "@frontmcp/utils";
38328
+ import { getRuntimeContext as getRuntimeContext13, isEntryAvailable as isEntryAvailable6 } from "@frontmcp/utils";
38078
38329
  function ownerKeyOf2(lineage) {
38079
38330
  return lineage.map((o) => `${o.kind}:${o.id}`).join("/");
38080
38331
  }
@@ -38296,7 +38547,7 @@ var init_agent_registry = __esm({
38296
38547
  */
38297
38548
  // NOTE: `any` is intentional - heterogeneous agent collections
38298
38549
  getAgents(includeHidden = false) {
38299
- const ctx = getRuntimeContext12();
38550
+ const ctx = getRuntimeContext13();
38300
38551
  const local = [...this.localRows].map((a) => a.instance);
38301
38552
  const adopted = [...this.adopted.values()].flat().map((a) => a.instance);
38302
38553
  return [...local, ...adopted].filter((a) => {
@@ -38329,7 +38580,7 @@ var init_agent_registry = __esm({
38329
38580
  * Used by discovery/listing APIs to enforce registry-level constraints.
38330
38581
  */
38331
38582
  getAvailableInstances() {
38332
- const ctx = getRuntimeContext12();
38583
+ const ctx = getRuntimeContext13();
38333
38584
  return [...this.listAllInstances()].filter((a) => isEntryAvailable6(a.metadata.availableWhen, ctx));
38334
38585
  }
38335
38586
  /**
@@ -38975,6 +39226,9 @@ var init_app_remote_instance = __esm({
38975
39226
  async syncToExternal() {
38976
39227
  return null;
38977
39228
  }
39229
+ setExternalProvider() {
39230
+ return void 0;
39231
+ }
38978
39232
  getExternalProvider() {
38979
39233
  return void 0;
38980
39234
  }
@@ -39524,6 +39778,9 @@ var init_app_esm_instance = __esm({
39524
39778
  async syncToExternal() {
39525
39779
  return null;
39526
39780
  }
39781
+ setExternalProvider() {
39782
+ return void 0;
39783
+ }
39527
39784
  getExternalProvider() {
39528
39785
  return void 0;
39529
39786
  }
@@ -39889,8 +40146,8 @@ var init_auth_ui_registry = __esm({
39889
40146
  */
39890
40147
  registerAuthUiMap(map, sourceDir) {
39891
40148
  if (!map) return;
39892
- for (const [slotKey, rawPath] of Object.entries(map)) {
39893
- const slot = slotKey;
40149
+ for (const [slotKey2, rawPath] of Object.entries(map)) {
40150
+ const slot = slotKey2;
39894
40151
  if (!ALL_SLOTS.includes(slot)) {
39895
40152
  throw new Error(`auth.ui slot "${slot}" is not one of: ${ALL_SLOTS.join(", ")}.`);
39896
40153
  }
@@ -43104,16 +43361,10 @@ var init_oauth_connect_flow = __esm({
43104
43361
  }
43105
43362
  return fetch(input, init);
43106
43363
  }
43107
- /** Fire a `notifications/resources/updated` to connected sessions (best-effort). */
43364
+ /** Fire a `notifications/resources/updated` to callers subscribed to the credential (best-effort). */
43108
43365
  notifyResourcesUpdated(key) {
43109
43366
  try {
43110
- const scope = this.scope;
43111
- const uri = `credential://${encodeURIComponent(key)}`;
43112
- if (typeof scope.notifyResourcesUpdated === "function") {
43113
- scope.notifyResourcesUpdated(uri);
43114
- } else if (typeof scope.resources?.notifyUpdated === "function") {
43115
- scope.resources.notifyUpdated(uri);
43116
- }
43367
+ this.scope.resources.notifyContentChanged(`credential://${encodeURIComponent(key)}`);
43117
43368
  } catch {
43118
43369
  }
43119
43370
  }
@@ -44809,8 +45060,8 @@ import {
44809
45060
  import { z as z74 } from "@frontmcp/lazy-zod";
44810
45061
  import { getMachineId as getMachineId2, randomUUID as randomUUID19, sha256 as sha2562, sha256Hex as sha256Hex13, timingSafeEqual as timingSafeEqual3 } from "@frontmcp/utils";
44811
45062
  function constantTimeEquals(a, b) {
44812
- const encoder5 = new TextEncoder();
44813
- return timingSafeEqual3(sha2562(encoder5.encode(a)), sha2562(encoder5.encode(b)));
45063
+ const encoder6 = new TextEncoder();
45064
+ return timingSafeEqual3(sha2562(encoder6.encode(a)), sha2562(encoder6.encode(b)));
44814
45065
  }
44815
45066
  function quoteHeaderParam(value) {
44816
45067
  return value.replace(/[^\x20-\x21\x23-\x7e]/g, "");
@@ -44830,6 +45081,7 @@ var init_session_verify_flow = __esm({
44830
45081
  "use strict";
44831
45082
  init_common();
44832
45083
  init_notification_service();
45084
+ init_skill_mode_utils();
44833
45085
  init_session_id_utils();
44834
45086
  inputSchema23 = httpRequestInputSchema.extend({
44835
45087
  /**
@@ -44939,7 +45191,8 @@ var init_session_verify_flow = __esm({
44939
45191
  iat: Math.floor(now / 1e3),
44940
45192
  isPublic: authMode === "public",
44941
45193
  authMode,
44942
- ...platformType !== "unknown" && { platformType }
45194
+ ...platformType !== "unknown" && { platformType },
45195
+ ...detectSkillsOnlyMode(this.rawInput.request.query) && { skillsOnlyMode: true }
44943
45196
  };
44944
45197
  const sessionId = encryptJson2(payload);
44945
45198
  this.respond({
@@ -45047,7 +45300,7 @@ var init_session_verify_flow = __esm({
45047
45300
  "handlePublicMode: ignoring non-JWT bearer token (public mode has nothing to verify it against)"
45048
45301
  );
45049
45302
  }
45050
- this.logger.info("handlePublicMode: allowing anonymous access (public mode)");
45303
+ this.logger.verbose("handlePublicMode: allowing anonymous access (public mode)");
45051
45304
  this.createAnonymousSession({
45052
45305
  authMode: "public",
45053
45306
  issuer: "public",
@@ -45217,7 +45470,7 @@ var init_session_verify_flow = __esm({
45217
45470
  required: { token, user },
45218
45471
  session
45219
45472
  } = this.state;
45220
- this.logger.info("Session verified successfully", {
45473
+ this.logger.verbose("Session verified successfully", {
45221
45474
  sub: this.maskSub(user.sub),
45222
45475
  hasSession: !!session
45223
45476
  });
@@ -45949,6 +46202,7 @@ var init_instance_local_primary_auth = __esm({
45949
46202
  refreshSkewMs: this.providerRefreshSkewMs()
45950
46203
  });
45951
46204
  this.consentStoreImpl = new InMemoryConsentStore();
46205
+ this.scope.onDispose(() => this.releaseResources());
45952
46206
  this.dcrClientRegistryImpl = new DcrClientRegistry(this.getDcrConfig() ?? {});
45953
46207
  if (isOrchestratedMode(options)) {
45954
46208
  const cimdConfig = options.cimd;
@@ -45998,6 +46252,8 @@ var init_instance_local_primary_auth = __esm({
45998
46252
  dcrClientRegistryImpl;
45999
46253
  /** Storage adapter backing the persistent stores (kept for disposal). */
46000
46254
  storageAdapter;
46255
+ /** Closes each storage this instance opened (persistent, vault, replay guard, secure store), on scope dispose. */
46256
+ storageClosers = [];
46001
46257
  /**
46002
46258
  * Replay guard for incremental-authorization tickets (GHSA-2c4g-9c8x-6m8g).
46003
46259
  * Shares the persistent adapter when one is configured so the guard holds
@@ -46199,6 +46455,8 @@ var init_instance_local_primary_auth = __esm({
46199
46455
  try {
46200
46456
  const adapter = await createTokenStorageAdapter(this.tokenStorage);
46201
46457
  this.storageAdapter = adapter;
46458
+ this.storageClosers.push(() => adapter.disconnect());
46459
+ this.disposeInMemoryStores();
46202
46460
  this.authorizationStoreImpl = new StorageAuthorizationStore(adapter);
46203
46461
  this.federatedSessionStoreImpl = new StorageFederatedAuthSessionStore(adapter);
46204
46462
  this.orchestratedTokenStoreImpl = new StorageOrchestratedTokenStore(adapter, {
@@ -46294,6 +46552,7 @@ var init_instance_local_primary_auth = __esm({
46294
46552
  const pending = (async () => {
46295
46553
  const memory = new MemoryStorageAdapter();
46296
46554
  await memory.connect();
46555
+ this.storageClosers.push(() => memory.disconnect());
46297
46556
  return memory;
46298
46557
  })();
46299
46558
  this.ticketReplayStorage = pending;
@@ -46309,6 +46568,7 @@ var init_instance_local_primary_auth = __esm({
46309
46568
  } else {
46310
46569
  const memory = new MemoryStorageAdapter();
46311
46570
  await memory.connect();
46571
+ this.storageClosers.push(() => memory.disconnect());
46312
46572
  storage = memory;
46313
46573
  }
46314
46574
  const pepper = getEnv8("VAULT_SECRET") ?? getEnv8("JWT_SECRET") ?? void 0;
@@ -46370,6 +46630,7 @@ var init_instance_local_primary_auth = __esm({
46370
46630
  logger: this.logger.child("SecureStore")
46371
46631
  });
46372
46632
  this.secureStoreBackendImpl = resolved.backend;
46633
+ if (resolved.close) this.storageClosers.push(resolved.close);
46373
46634
  await this.providers.addDynamicProviders(
46374
46635
  createSecureStoreProviders({
46375
46636
  backend: resolved.backend,
@@ -46382,6 +46643,20 @@ var init_instance_local_primary_auth = __esm({
46382
46643
  `SecureStore initialized (backing: ${resolved.kind}, scope: ${resolved.scope}); this.secureStore enabled`
46383
46644
  );
46384
46645
  }
46646
+ /** Stop the in-memory stores' cleanup timers (they are replaced by persistent stores, or the scope is disposed). */
46647
+ disposeInMemoryStores() {
46648
+ if (this.federatedSessionStoreImpl instanceof InMemoryFederatedAuthSessionStore) {
46649
+ this.federatedSessionStoreImpl.dispose();
46650
+ }
46651
+ if (this.orchestratedTokenStoreImpl instanceof InMemoryOrchestratedTokenStore) {
46652
+ this.orchestratedTokenStoreImpl.dispose();
46653
+ }
46654
+ }
46655
+ /** Release what this instance started: the in-memory stores' timers and the storage it opened. */
46656
+ async releaseResources() {
46657
+ this.disposeInMemoryStores();
46658
+ await Promise.allSettled(this.storageClosers.splice(0).map((close) => close()));
46659
+ }
46385
46660
  /**
46386
46661
  * Whether the `secureStore` config selects the SAME persistent backing as the
46387
46662
  * configured `tokenStorage`, so they can share one StorageAdapter. Returns
@@ -47509,7 +47784,7 @@ var init_auth_registry = __esm({
47509
47784
  });
47510
47785
 
47511
47786
  // libs/sdk/src/server/custom-routes.helper.ts
47512
- function computeReservedPaths(entryPath, routeBase) {
47787
+ function computeReservedPaths(entryPath, routeBase, healthPaths = []) {
47513
47788
  const prefix = normalizeEntryPrefix(entryPath);
47514
47789
  const base = normalizeScopeBase(routeBase);
47515
47790
  const mcpBase = `${prefix}${base}`;
@@ -47518,7 +47793,8 @@ function computeReservedPaths(entryPath, routeBase) {
47518
47793
  `${mcpBase}/sse`,
47519
47794
  `${mcpBase}/message`,
47520
47795
  "/health",
47521
- "/metrics"
47796
+ "/metrics",
47797
+ ...healthPaths.map(normalizeForCompare)
47522
47798
  ]);
47523
47799
  return { exact, prefixes: ["/oauth", "/.well-known"] };
47524
47800
  }
@@ -47580,9 +47856,9 @@ function wrapWithIpFilter(handler, checkClientIp) {
47580
47856
  };
47581
47857
  }
47582
47858
  function registerCustomHttpRoutes(args) {
47583
- const { routes, server, verifySession, checkClientIp, entryPath, routeBase, logger } = args;
47859
+ const { routes, server, verifySession, checkClientIp, entryPath, routeBase, healthPaths, logger } = args;
47584
47860
  if (!routes || routes.length === 0) return;
47585
- const reserved = computeReservedPaths(entryPath, routeBase);
47861
+ const reserved = computeReservedPaths(entryPath, routeBase, healthPaths);
47586
47862
  for (const route of routes) {
47587
47863
  assertNotReserved(route.method, route.path, reserved);
47588
47864
  const handler = route.auth === true ? wrapWithAuth(route.handler, verifySession, logger) : route.handler;
@@ -47599,7 +47875,7 @@ var init_custom_routes_helper = __esm({
47599
47875
  ReservedRouteCollisionError = class extends Error {
47600
47876
  constructor(method, path, reserved) {
47601
47877
  super(
47602
- `Custom http.route "${method} ${path}" collides with the reserved FrontMCP path "${reserved}". Reserved prefixes are the MCP entry path (and its /sse + /message siblings), /oauth/*, /.well-known/*, /health, and /metrics. Choose a different path.`
47878
+ `Custom http.route "${method} ${path}" collides with the reserved FrontMCP path "${reserved}". Reserved prefixes are the MCP entry path (and its /sse + /message siblings), /oauth/*, /.well-known/*, /health, /metrics, and the health probe paths (/healthz, /readyz unless health.healthzPath / health.readyzPath move them). Choose a different path.`
47603
47879
  );
47604
47880
  this.method = method;
47605
47881
  this.path = path;
@@ -47973,7 +48249,7 @@ var init_channel_utils = __esm({
47973
48249
  });
47974
48250
 
47975
48251
  // libs/sdk/src/channel/channel.registry.ts
47976
- import { getRuntimeContext as getRuntimeContext13, isEntryAvailable as isEntryAvailable7 } from "@frontmcp/utils";
48252
+ import { getRuntimeContext as getRuntimeContext14, isEntryAvailable as isEntryAvailable7 } from "@frontmcp/utils";
47977
48253
  var ChannelRegistry;
47978
48254
  var init_channel_registry = __esm({
47979
48255
  "libs/sdk/src/channel/channel.registry.ts"() {
@@ -48022,7 +48298,7 @@ var init_channel_registry = __esm({
48022
48298
  }
48023
48299
  /* -------------------- Initialize -------------------- */
48024
48300
  async initialize() {
48025
- const runtimeContext = getRuntimeContext13();
48301
+ const runtimeContext = getRuntimeContext14();
48026
48302
  for (const token of this.tokens) {
48027
48303
  const rec = this.defs.get(token);
48028
48304
  if (!rec) continue;
@@ -48583,7 +48859,7 @@ async function registerChannelCapabilities(args) {
48583
48859
  const agentEmitterSubscribe = args.agentEmitterSubscribe ?? ((cb) => completions.agents.subscribe(cb));
48584
48860
  const jobEmitterSubscribe = args.jobEmitterSubscribe ?? ((cb) => completions.jobs.subscribe(cb));
48585
48861
  const unsubscribers = [];
48586
- const reservedPaths = http ? computeReservedPaths(http.entryPath, http.routeBase) : void 0;
48862
+ const reservedPaths = http ? computeReservedPaths(http.entryPath, http.routeBase, http.healthPaths) : void 0;
48587
48863
  const webhookPaths = /* @__PURE__ */ new Map();
48588
48864
  const channelRegistry = new ChannelRegistry(providers, channelsList, owner, channelProviders);
48589
48865
  await channelRegistry.ready;
@@ -52022,9 +52298,9 @@ var init_workflow_step_executor = __esm({
52022
52298
  throw lastError ?? new Error(`Step "${step.id}" failed after ${maxAttempts} attempts`);
52023
52299
  }
52024
52300
  /**
52025
- * Run one attempt, racing a timer. The timer does NOT cancel a job that already started; it rejects
52026
- * the attempt early and aborts its flow, so an attempt still building its providers or loading its
52027
- * auth when it times out never starts the job.
52301
+ * Run one attempt, racing a timer. On a timeout the attempt is rejected and its flow aborted: a job
52302
+ * not started yet never starts, and a started one sees `this.signal` aborted while its flow ends as
52303
+ * failed (its `Did('execute')` hooks don't run). The timer does not stop `execute()` itself.
52028
52304
  */
52029
52305
  executeWithTimeout(job, step, input, timeout, attempt) {
52030
52306
  const { context, contextProviders, authInfo, authoritiesContextBuilder, workflowName, workflowRunId } = this.extra;
@@ -52650,8 +52926,14 @@ var init_job_interface = __esm({
52650
52926
  _output;
52651
52927
  _attempt;
52652
52928
  _logs = [];
52929
+ /**
52930
+ * Aborted when the workflow step running this attempt gives up on it (its `timeout` passed), with
52931
+ * the `WorkflowJobTimeoutError` as its reason; undefined outside a workflow step. The attempt is not
52932
+ * stopped for the job: pass the signal to `fetch` and other cancellable work, or check it.
52933
+ */
52934
+ signal;
52653
52935
  constructor(args) {
52654
- const { metadata, input, providers, logger, attempt } = args;
52936
+ const { metadata, input, providers, logger, attempt, signal } = args;
52655
52937
  super({
52656
52938
  providers,
52657
52939
  logger: logger.child(`job:${metadata.id ?? metadata.name}`),
@@ -52662,6 +52944,13 @@ var init_job_interface = __esm({
52662
52944
  this.metadata = metadata;
52663
52945
  this._input = input;
52664
52946
  this._attempt = attempt;
52947
+ this.signal = signal;
52948
+ }
52949
+ /** Like {@link ExecutionContextBase.fetch}, and also aborted with {@link signal}. */
52950
+ fetch(input, init) {
52951
+ const context = this.fetchContext(init);
52952
+ if (context && this.signal) return context.fetch(input, init, this.signal);
52953
+ return super.fetch(input, init);
52665
52954
  }
52666
52955
  get input() {
52667
52956
  return this._input;
@@ -52825,7 +53114,12 @@ var init_execute_job_flow = __esm({
52825
53114
  const { ctx, attempt } = this.input;
52826
53115
  const contextProviders = ctx.contextProviders ?? await jobContextProviders(job, this.context);
52827
53116
  this.throwIfAborted();
52828
- const jobContext = job.create(parsedInput, { authInfo: this.state.authInfo ?? {}, contextProviders, attempt });
53117
+ const jobContext = job.create(parsedInput, {
53118
+ authInfo: this.state.authInfo ?? {},
53119
+ contextProviders,
53120
+ attempt,
53121
+ signal: ctx.signal
53122
+ });
52829
53123
  await jobContext.loadAuthContext();
52830
53124
  this.throwIfAborted();
52831
53125
  this.appendContextHooks(hooksBoundTo(this.scope.hooks.getClsHooks(job.record.provide), jobContext));
@@ -52838,12 +53132,15 @@ var init_execute_job_flow = __esm({
52838
53132
  try {
52839
53133
  output = await runOnSurface("job", async () => jobContext.execute(parsedInput));
52840
53134
  } catch (error) {
53135
+ this.throwIfAborted();
52841
53136
  if (!(error instanceof FlowControl && error.type === "respond")) throw toJobError(error);
52842
53137
  output = error.output;
52843
53138
  }
53139
+ this.throwIfAborted();
52844
53140
  this.state.set("output", output);
52845
53141
  }
52846
53142
  async validateOutput() {
53143
+ this.throwIfAborted();
52847
53144
  const { job, jobContext } = this.state.required;
52848
53145
  const result = job.parseOutput(this.state.output);
52849
53146
  this.state.set("answer", { result, logs: [...jobContext.getLogs()] });
@@ -52873,12 +53170,19 @@ var init_execute_job_flow = __esm({
52873
53170
  if (flowError || !answer) return;
52874
53171
  this.respond(answer);
52875
53172
  }
52876
- /** Answer for the job; a hook that answers before `validateOutput` gets its answer recorded as the result. */
53173
+ /**
53174
+ * Answer for the job. A hook's answer is checked against the job's `outputSchema`, as `execute()`'s result
53175
+ * is: undeclared fields are dropped, and a mismatch fails the attempt with `InvalidOutputError`.
53176
+ */
52877
53177
  respond(output) {
52878
- const answer = outputSchema30.parse(output);
53178
+ const answer = output === this.state.answer ? output : this.checkedAnswer(output);
52879
53179
  this.state.set("answer", answer);
52880
53180
  throw FlowControl.respond(answer);
52881
53181
  }
53182
+ checkedAnswer(output) {
53183
+ const { result, logs } = outputSchema30.parse(output);
53184
+ return { result: this.input.job.parseOutput(result), logs };
53185
+ }
52882
53186
  throwIfAborted() {
52883
53187
  const signal = this.input.ctx.signal;
52884
53188
  if (!signal?.aborted) return;
@@ -53006,7 +53310,8 @@ var init_job_instance = __esm({
53006
53310
  providers,
53007
53311
  logger,
53008
53312
  authInfo,
53009
- attempt: extra.attempt ?? 1
53313
+ attempt: extra.attempt ?? 1,
53314
+ signal: extra.signal
53010
53315
  };
53011
53316
  switch (this.record.kind) {
53012
53317
  case "CLASS_TOKEN" /* CLASS_TOKEN */:
@@ -55897,11 +56202,11 @@ var init_skill_http_auth = __esm({
55897
56202
  * This prevents timing attacks that could reveal information about valid API keys.
55898
56203
  */
55899
56204
  timingSafeIncludes(keys, candidate) {
55900
- const encoder5 = new TextEncoder();
55901
- const candidateBytes = encoder5.encode(candidate);
56205
+ const encoder6 = new TextEncoder();
56206
+ const candidateBytes = encoder6.encode(candidate);
55902
56207
  let found = false;
55903
56208
  for (const key of keys) {
55904
- const keyBytes = encoder5.encode(key);
56209
+ const keyBytes = encoder6.encode(key);
55905
56210
  if (keyBytes.length === candidateBytes.length) {
55906
56211
  try {
55907
56212
  if (timingSafeEqual4(keyBytes, candidateBytes)) {
@@ -57309,8 +57614,9 @@ var init_tool_interface = __esm({
57309
57614
  * Notify subscribed clients that a resource's contents changed.
57310
57615
  *
57311
57616
  * Sends `notifications/resources/updated` to every session subscribed to `uri`
57312
- * (via `resources/subscribe`); a no-op for sessions that aren't subscribed. Call
57313
- * this when a tool mutates state that backs a `@Resource` so subscribers re-fetch.
57617
+ * (via `resources/subscribe`) and to every MCP 2026-07-28 `subscriptions/listen`
57618
+ * stream subscribed to it; a no-op for callers that aren't subscribed. Call this
57619
+ * when a tool mutates state that backs a `@Resource` so subscribers re-fetch.
57314
57620
  *
57315
57621
  * @param uri - The URI of the resource whose contents changed.
57316
57622
  *
@@ -57324,7 +57630,7 @@ var init_tool_interface = __esm({
57324
57630
  * ```
57325
57631
  */
57326
57632
  notifyResourceUpdated(uri) {
57327
- this.scope.notifications.notifyResourceUpdated(uri);
57633
+ this.scope.resources.notifyContentChanged(uri);
57328
57634
  }
57329
57635
  /**
57330
57636
  * Notify all connected clients that the set of available resources changed.
@@ -59430,6 +59736,18 @@ function getSepVisibleSkills(scope) {
59430
59736
  if (!registry || !registry.hasAny()) return [];
59431
59737
  return registry.getSkills({ visibility: "mcp" });
59432
59738
  }
59739
+ async function getExternalProviderSkills(scope) {
59740
+ const registry = scope.skills;
59741
+ if (registry?.getExternalProvider()?.isReadOnly() !== true) return [];
59742
+ const { skills } = await registry.listSkills({ limit: Number.MAX_SAFE_INTEGER });
59743
+ return skills.filter((metadata) => !registry.findByName(metadata.name));
59744
+ }
59745
+ async function loadExternalProviderSkill(scope, skillPath) {
59746
+ const registry = scope.skills;
59747
+ if (registry?.getExternalProvider()?.isReadOnly() !== true) return void 0;
59748
+ if (skillPath.includes("/") || registry.findByName(skillPath)) return void 0;
59749
+ return (await registry.loadSkill(skillPath))?.skill;
59750
+ }
59433
59751
  function findSkillByPath(scope, skillPath) {
59434
59752
  const registry = scope.skills;
59435
59753
  if (!registry || !registry.hasAny()) return void 0;
@@ -59748,7 +60066,10 @@ var init_skill_index_resource = __esm({
59748
60066
  skillPathSegments: skill.getSkillPathSegments()
59749
60067
  })
59750
60068
  );
59751
- if (skills.length > 0) {
60069
+ for (const metadata of await getExternalProviderSkills(this.scope)) {
60070
+ entries.push(buildSkillMdIndexEntry({ name: metadata.name, description: metadata.description }));
60071
+ }
60072
+ if (entries.length > 0) {
59752
60073
  entries.push(
59753
60074
  buildResourceTemplateIndexEntry(
59754
60075
  "Read the raw SKILL.md (frontmatter + body) for any skill served by this MCP server.",
@@ -59814,9 +60135,7 @@ var init_skill_md_resource = __esm({
59814
60135
  return { values: filtered, total: filtered.length };
59815
60136
  }
59816
60137
  async execute(uri, params) {
59817
- const { loadResult, instance } = await findAndLoadSkillByPath(this.scope, params.skillPath);
59818
- await assertSkillAuthorized(this.scope, instance, this.getAuthInfo());
59819
- const raw = serializeSkillMd(loadResult.skill);
60138
+ const raw = serializeSkillMd(await this.readSkill(params.skillPath));
59820
60139
  return {
59821
60140
  contents: [
59822
60141
  {
@@ -59827,6 +60146,16 @@ var init_skill_md_resource = __esm({
59827
60146
  ]
59828
60147
  };
59829
60148
  }
60149
+ /** A registered skill at `skillPath`, or else one a read-only external provider serves there. */
60150
+ async readSkill(skillPath) {
60151
+ if (!findSkillByPath(this.scope, skillPath)) {
60152
+ const providerSkill = await loadExternalProviderSkill(this.scope, skillPath);
60153
+ if (providerSkill) return providerSkill;
60154
+ }
60155
+ const { loadResult, instance } = await findAndLoadSkillByPath(this.scope, skillPath);
60156
+ await assertSkillAuthorized(this.scope, instance, this.getAuthInfo());
60157
+ return loadResult.skill;
60158
+ }
59830
60159
  };
59831
60160
  Sep2640SkillMdResource = __decorateClass([
59832
60161
  _ResourceTemplate({
@@ -59926,47 +60255,60 @@ function buildPerSkillResourceRecord(scope, skill, opts = {}) {
59926
60255
  };
59927
60256
  }
59928
60257
  async function registerPerSkillResources(options) {
59929
- const { scope, resourceRegistry, skills, logger, resolveLastModified } = options;
59930
- const registered = [];
59931
- for (const skill of skills) {
59932
- let lastModified;
59933
- if (resolveLastModified) {
59934
- try {
59935
- lastModified = await resolveLastModified(skill);
59936
- } catch (err) {
59937
- logger.warn(
59938
- `Failed to resolve SEP-2640 lastModified for "${skill.name}": ${err instanceof Error ? err.message : String(err)}`
59939
- );
59940
- }
59941
- }
60258
+ const { scope, skillRegistry, resourceRegistry, logger, resolveLastModified } = options;
60259
+ const registered = /* @__PURE__ */ new Map();
60260
+ const register = (skill) => {
59942
60261
  try {
59943
- const record = buildPerSkillResourceRecord(scope, skill, { lastModified });
60262
+ const record = buildPerSkillResourceRecord(scope, skill);
59944
60263
  resourceRegistry.registerDynamicResource(record);
59945
- registered.push({
59946
- skillPath: skill.getSkillPath(),
60264
+ registered.set(skill.getSkillPath(), {
60265
+ token: record.provide,
59947
60266
  metadata: record.metadata,
59948
60267
  extensionKeys: Object.keys(skillExtensionMetadata(skill))
59949
60268
  });
59950
60269
  logger.verbose(`Registered SEP-2640 per-skill resource: ${record.metadata.uri}`);
60270
+ return resolveLastModified ? addLastModified(record.metadata, skill, resolveLastModified, logger) : Promise.resolve();
59951
60271
  } catch (err) {
59952
60272
  logger.warn(
59953
60273
  `Failed to register SEP-2640 per-skill resource for "${skill.name}": ${err instanceof Error ? err.message : String(err)}`
59954
60274
  );
60275
+ return Promise.resolve();
59955
60276
  }
59956
- }
59957
- if (registered.length > 0) {
59958
- scope.skills?.subscribe({ immediate: false }, () => {
59959
- const served = servedSkillsByPath(scope);
59960
- for (const resource of registered) {
59961
- const skill = served.get(resource.skillPath);
59962
- if (skill) refreshFromSkill(resource, skill);
59963
- }
59964
- });
60277
+ };
60278
+ const reconcile = () => {
60279
+ const served = servedSkillsByPath(skillRegistry);
60280
+ for (const [skillPath, resource] of registered) {
60281
+ if (served.has(skillPath)) continue;
60282
+ resourceRegistry.unregisterResourceInstance(resource.token);
60283
+ registered.delete(skillPath);
60284
+ }
60285
+ const lastModifiedUpdates = [];
60286
+ for (const [skillPath, skill] of served) {
60287
+ const resource = registered.get(skillPath);
60288
+ if (resource) refreshFromSkill(resource, skill);
60289
+ else lastModifiedUpdates.push(register(skill));
60290
+ }
60291
+ return lastModifiedUpdates;
60292
+ };
60293
+ await Promise.all(reconcile());
60294
+ const unsubscribe = skillRegistry.subscribe({ immediate: false }, () => {
60295
+ reconcile();
60296
+ });
60297
+ scope.onDispose(unsubscribe);
60298
+ }
60299
+ async function addLastModified(metadata, skill, resolveLastModified, logger) {
60300
+ try {
60301
+ const lastModified = await resolveLastModified(skill);
60302
+ if (lastModified && metadata.annotations) metadata.annotations.lastModified = lastModified;
60303
+ } catch (err) {
60304
+ logger.warn(
60305
+ `Failed to resolve SEP-2640 lastModified for "${skill.name}": ${err instanceof Error ? err.message : String(err)}`
60306
+ );
59965
60307
  }
59966
60308
  }
59967
- function servedSkillsByPath(scope) {
60309
+ function servedSkillsByPath(skillRegistry) {
59968
60310
  const served = /* @__PURE__ */ new Map();
59969
- for (const skill of getSepVisibleSkills(scope)) {
60311
+ for (const skill of skillRegistry.getSkills({ visibility: "mcp" })) {
59970
60312
  const skillPath = skill.getSkillPath();
59971
60313
  if (!served.has(skillPath)) served.set(skillPath, skill);
59972
60314
  }
@@ -60031,7 +60373,7 @@ function registerSkillAuditWriter(options) {
60031
60373
  if (!audit?.enabled) return;
60032
60374
  const mod = resolveAuditModule(logger);
60033
60375
  if (!mod) {
60034
- const msg = '[skill-audit] audit.enabled is true but no audit module factory is registered. Call setSkillAuditFactory(() => require("@frontmcp/adapters/skills")) at boot, or supply a signer + store explicitly in skillsConfig.audit.';
60376
+ const msg = "[skill-audit] audit.enabled is true but no audit module is registered. @frontmcp/plugin-skilled-openapi registers it when the plugin is installed; otherwise call setSkillAuditFactory(() => auditModule) at boot, with `import * as auditModule from '@frontmcp/adapters/skills'`.";
60035
60377
  if (isProductionRuntime()) {
60036
60378
  throw new Error(msg);
60037
60379
  }
@@ -60045,9 +60387,8 @@ function registerSkillAuditWriter(options) {
60045
60387
  }
60046
60388
  const signer = audit.signer ?? createDefaultSigner(mod, logger);
60047
60389
  const store = audit.store ?? createDefaultStore(mod, logger);
60048
- const writerOptions = audit.subjectMode !== void 0 ? { subjectMode: audit.subjectMode } : void 0;
60049
60390
  const AuditWriter = mod.SkillAuditWriter;
60050
- const writer = new AuditWriter(store, signer, logger, audit.metrics, writerOptions);
60391
+ const writer = new AuditWriter(store, signer, logger, audit.metrics, auditWriterOptions(audit));
60051
60392
  providers.injectProvider({
60052
60393
  provide: mod.SkillAuditWriterToken,
60053
60394
  value: writer,
@@ -60075,7 +60416,20 @@ function createDefaultSigner(mod, logger) {
60075
60416
  );
60076
60417
  return new mod.Hs256AuditSigner(bytes, "frontmcp-default-hs256");
60077
60418
  }
60419
+ function auditWriterOptions(audit) {
60420
+ const options = {};
60421
+ if (audit.subjectMode !== void 0) options.subjectMode = audit.subjectMode;
60422
+ if (audit.subjectHashSecret !== void 0) {
60423
+ options.subjectHashSecret = typeof audit.subjectHashSecret === "string" ? new TextEncoder().encode(audit.subjectHashSecret) : audit.subjectHashSecret;
60424
+ }
60425
+ return Object.keys(options).length > 0 ? options : void 0;
60426
+ }
60078
60427
  function createDefaultStore(mod, logger) {
60428
+ if (isProductionRuntime()) {
60429
+ throw new Error(
60430
+ '[skill-audit] refusing to use the in-memory audit store in production. Configure skillsConfig.audit.store with a persistent store, e.g. new StorageAdapterAuditStore(await createStorage({ type: "redis", redis: { config: { host, port } } })) from @frontmcp/adapters/skills and @frontmcp/utils.'
60431
+ );
60432
+ }
60079
60433
  logger.warn(
60080
60434
  "[skill-audit] no audit store configured \u2014 using in-memory store. Records are lost on restart and not shared across pods. Configure skillsConfig.audit.store for production."
60081
60435
  );
@@ -60106,6 +60460,10 @@ async function registerSkillCapabilities(options) {
60106
60460
  if (dynamicSkills) {
60107
60461
  skillRegistry.expectDynamicSkills();
60108
60462
  }
60463
+ if (skillsConfig?.externalProvider) {
60464
+ await skillsConfig.externalProvider.initialize();
60465
+ skillRegistry.setExternalProvider(skillsConfig.externalProvider);
60466
+ }
60109
60467
  if (!skillRegistry.servesSkills()) {
60110
60468
  return;
60111
60469
  }
@@ -60113,17 +60471,13 @@ async function registerSkillCapabilities(options) {
60113
60471
  const shouldRegisterResources = skillsConfig?.mcpResources !== false;
60114
60472
  if (shouldRegisterResources) {
60115
60473
  await registerSep2640Resources({ resourceRegistry, logger });
60116
- const scope = providers.getActiveScope();
60117
- const visibleSkills = skillRegistry.getSkills({ visibility: "mcp" });
60118
- if (visibleSkills.length > 0) {
60119
- await registerPerSkillResources({
60120
- scope,
60121
- resourceRegistry,
60122
- skills: visibleSkills,
60123
- logger,
60124
- resolveLastModified: resolveLastModifiedForSkill
60125
- });
60126
- }
60474
+ await registerPerSkillResources({
60475
+ scope: providers.getActiveScope(),
60476
+ skillRegistry,
60477
+ resourceRegistry,
60478
+ logger,
60479
+ resolveLastModified: resolveLastModifiedForSkill
60480
+ });
60127
60481
  } else {
60128
60482
  logger.verbose("SEP-2640 skill:// resources disabled via skillsConfig.mcpResources=false");
60129
60483
  }
@@ -62031,9 +62385,9 @@ var init_handle_mcp_20260728_flow = __esm({
62031
62385
  });
62032
62386
 
62033
62387
  // libs/sdk/src/ha/ha-headers.ts
62034
- import { buildSetCookie, getEnv as getEnv12, getMachineId as getMachineId3, getRuntimeContext as getRuntimeContext14 } from "@frontmcp/utils";
62388
+ import { buildSetCookie, getEnv as getEnv12, getMachineId as getMachineId3, getRuntimeContext as getRuntimeContext15 } from "@frontmcp/utils";
62035
62389
  function machineIdHeader() {
62036
- if (getRuntimeContext14().deployment !== "distributed") return void 0;
62390
+ if (getRuntimeContext15().deployment !== "distributed") return void 0;
62037
62391
  return [DEFAULT_FRONTMCP_MACHINE_ID_HEADER, getMachineId3()];
62038
62392
  }
62039
62393
  function applyMachineIdHeader(response) {
@@ -62064,24 +62418,6 @@ var init_ha_headers = __esm({
62064
62418
  }
62065
62419
  });
62066
62420
 
62067
- // libs/sdk/src/skill/skill-mode.utils.ts
62068
- function detectSkillsOnlyMode(query) {
62069
- if (!query) return false;
62070
- const mode = query["mode"];
62071
- if (mode === "skills_only") {
62072
- return true;
62073
- }
62074
- if (Array.isArray(mode) && mode.includes("skills_only")) {
62075
- return true;
62076
- }
62077
- return false;
62078
- }
62079
- var init_skill_mode_utils = __esm({
62080
- "libs/sdk/src/skill/skill-mode.utils.ts"() {
62081
- "use strict";
62082
- }
62083
- });
62084
-
62085
62421
  // libs/sdk/src/transport/flows/handle.sse.flow.ts
62086
62422
  import { z as z106 } from "@frontmcp/lazy-zod";
62087
62423
  function getQuerySessionId2(urlPath) {
@@ -62326,10 +62662,10 @@ var init_handle_stateless_http_flow = __esm({
62326
62662
  const method = body?.method;
62327
62663
  if (method === "initialize") {
62328
62664
  this.state.set("requestType", "initialize");
62329
- logger.info("router: requestType=initialize, method=POST");
62665
+ logger.verbose("router: requestType=initialize, method=POST");
62330
62666
  } else if (method && RequestSchema.safeParse(request.body).success) {
62331
62667
  this.state.set("requestType", "message");
62332
- logger.info(`router: requestType=message, method=${method}`);
62668
+ logger.verbose(`router: requestType=message, method=${method}`);
62333
62669
  } else {
62334
62670
  logger.warn("router: invalid request, no valid method");
62335
62671
  this.respond(httpRespond.rpcError("Invalid Request"));
@@ -62343,7 +62679,7 @@ var init_handle_stateless_http_flow = __esm({
62343
62679
  const logger = this.scope.logger.child("HandleStatelessHttpFlow");
62344
62680
  const { request, response } = this.rawInput;
62345
62681
  const { token, isAuthenticated, requestType } = this.state;
62346
- logger.info(`handleRequest: using ${isAuthenticated ? "authenticated" : "anonymous"} stateless transport`);
62682
+ logger.verbose(`handleRequest: using ${isAuthenticated ? "authenticated" : "anonymous"} stateless transport`);
62347
62683
  const transport = isAuthenticated && token ? await transportService.getOrCreateAuthenticatedStatelessTransport("stateless-http", token, response) : await transportService.getOrCreateAnonymousStatelessTransport("stateless-http", response);
62348
62684
  if (!request.headers["mcp-session-id"]) {
62349
62685
  request.headers["mcp-session-id"] = STATELESS_SESSION_ID;
@@ -62994,7 +63330,7 @@ var init_handle_streamable_http_flow = __esm({
62994
63330
  }
62995
63331
  const session = sessionResolution.session;
62996
63332
  this.state.set(stateSchema41.parse({ token, session }));
62997
- logger.info("parseInput: session resolved", { sessionId: session.id?.slice(0, 20) });
63333
+ logger.verbose("parseInput: session resolved", { sessionId: session.id?.slice(0, 20) });
62998
63334
  }
62999
63335
  async router() {
63000
63336
  const { request } = this.rawInput;
@@ -63010,17 +63346,17 @@ var init_handle_streamable_http_flow = __esm({
63010
63346
  }
63011
63347
  this.state.set("requestType", classification.requestType);
63012
63348
  if (classification.requestType === "sseListener") {
63013
- logger.info("router: requestType=sseListener, method=GET");
63349
+ logger.verbose("router: requestType=sseListener, method=GET");
63014
63350
  } else if (classification.requestType === "initialize") {
63015
- logger.info("router: requestType=initialize, method=POST");
63351
+ logger.verbose("router: requestType=initialize, method=POST");
63016
63352
  } else if (classification.requestType === "extApps") {
63017
63353
  const method = request.body?.method;
63018
- logger.info(`router: requestType=extApps, method=${method}`);
63354
+ logger.verbose(`router: requestType=extApps, method=${method}`);
63019
63355
  } else if (classification.requestType === "elicitResult") {
63020
- logger.info("router: requestType=elicitResult, method=POST");
63356
+ logger.verbose("router: requestType=elicitResult, method=POST");
63021
63357
  } else {
63022
63358
  const method = request.body?.method;
63023
- logger.info(`router: requestType=message, method=${method}`);
63359
+ logger.verbose(`router: requestType=message, method=${method}`);
63024
63360
  }
63025
63361
  }
63026
63362
  async onInitialize() {
@@ -63079,7 +63415,7 @@ var init_handle_streamable_http_flow = __esm({
63079
63415
  const logger = this.scopeLogger.child("handle:streamable-http:onElicitResult");
63080
63416
  const { request, response } = this.rawInput;
63081
63417
  const { token, session } = this.state.required;
63082
- logger.info("onElicitResult: starting", {
63418
+ logger.verbose("onElicitResult: starting", {
63083
63419
  sessionId: session.id?.slice(0, 20),
63084
63420
  hasToken: !!token
63085
63421
  });
@@ -63132,7 +63468,7 @@ var init_handle_streamable_http_flow = __esm({
63132
63468
  const logger = this.scopeLogger.child("handle:streamable-http:onMessage");
63133
63469
  const { request, response } = this.rawInput;
63134
63470
  const { token, session } = this.state.required;
63135
- logger.info("onMessage: starting", {
63471
+ logger.verbose("onMessage: starting", {
63136
63472
  sessionId: session.id?.slice(0, 20),
63137
63473
  hasToken: !!token
63138
63474
  });
@@ -63256,7 +63592,7 @@ var init_handle_streamable_http_flow = __esm({
63256
63592
  this.handled();
63257
63593
  return;
63258
63594
  }
63259
- logger.info("onExtApps: starting", {
63595
+ logger.verbose("onExtApps: starting", {
63260
63596
  sessionId: session.id?.slice(0, 20),
63261
63597
  method: request.body?.method
63262
63598
  });
@@ -63641,7 +63977,7 @@ var init_transport_local_adapter = __esm({
63641
63977
  capabilities: mergedCapabilities,
63642
63978
  serverInfo: info
63643
63979
  };
63644
- this.logger.info("connectServer: advertising capabilities", {
63980
+ this.logger.verbose("connectServer: advertising capabilities", {
63645
63981
  hasTools: hasTools || hasAgents,
63646
63982
  // Agents expose themselves as tools
63647
63983
  hasResources,
@@ -63674,7 +64010,7 @@ var init_transport_local_adapter = __esm({
63674
64010
  return this.key.type;
63675
64011
  }
63676
64012
  async destroy(reason) {
63677
- console.log("destroying transporter, reason:", reason);
64013
+ this.logger.verbose("destroying transporter", { reason });
63678
64014
  this.scope.notifications.unregisterServer(this.key.sessionId);
63679
64015
  try {
63680
64016
  } catch {
@@ -63802,7 +64138,7 @@ var init_transport_local_adapter = __esm({
63802
64138
  * which routes it to the correct node that's waiting for it.
63803
64139
  */
63804
64140
  handleIfElicitResult(req) {
63805
- this.logger.info("[handleIfElicitResult] checking request", {
64141
+ this.logger.verbose("[handleIfElicitResult] checking request", {
63806
64142
  hasPendingElicit: !!this.pendingElicit,
63807
64143
  bodyKeys: req.body ? Object.keys(req.body) : [],
63808
64144
  hasResult: !!req.body?.result
@@ -64220,9 +64556,9 @@ var init_transport_streamable_http_adapter = __esm({
64220
64556
  },
64221
64557
  onsessioninitialized: (sessionId2) => {
64222
64558
  if (sessionId2) {
64223
- console.log(`session initialized: ${sessionId2.slice(0, 40)}`);
64559
+ this.logger.verbose("[StreamableHttpAdapter] session initialized", { sessionId: sessionId2.slice(0, 40) });
64224
64560
  } else {
64225
- console.log(`stateless session initialized`);
64561
+ this.logger.verbose("[StreamableHttpAdapter] stateless session initialized");
64226
64562
  }
64227
64563
  },
64228
64564
  // Pass EventStore from scope config (or undefined to disable resumability)
@@ -64234,7 +64570,7 @@ var init_transport_streamable_http_adapter = __esm({
64234
64570
  }
64235
64571
  async initialize(req, res) {
64236
64572
  this.ensureAuthInfo(req, this);
64237
- this.logger.info("[StreamableHttpAdapter] initialize() called", {
64573
+ this.logger.verbose("[StreamableHttpAdapter] initialize() called", {
64238
64574
  method: req.method,
64239
64575
  sessionId: this.key.sessionId.slice(0, 30),
64240
64576
  bodyMethod: req.body?.method,
@@ -64244,7 +64580,7 @@ var init_transport_streamable_http_adapter = __esm({
64244
64580
  bodyKeys: req.body && typeof req.body === "object" ? Object.keys(req.body) : []
64245
64581
  });
64246
64582
  await this.ready;
64247
- this.logger.info("[StreamableHttpAdapter] transport state before handleRequest", {
64583
+ this.logger.verbose("[StreamableHttpAdapter] transport state before handleRequest", {
64248
64584
  isRecreatable: this.transport instanceof RecreateableStreamableHTTPServerTransport,
64249
64585
  hasWebTransport: !!this.transport._webStandardTransport,
64250
64586
  webTransportInitialized: this.transport._webStandardTransport?._initialized,
@@ -64316,7 +64652,7 @@ var init_transport_streamable_http_adapter = __esm({
64316
64652
  });
64317
64653
  const { elicitId, expiresAt, requestParams, pendingRecord } = flowOutput;
64318
64654
  const ttl = expiresAt - Date.now();
64319
- this.logger.info("[StreamableHttpAdapter] sendElicitRequest: sending elicitation/create", {
64655
+ this.logger.verbose("[StreamableHttpAdapter] sendElicitRequest: sending elicitation/create", {
64320
64656
  relatedRequestId,
64321
64657
  elicitId,
64322
64658
  mode: pendingRecord.mode,
@@ -64326,7 +64662,7 @@ var init_transport_streamable_http_adapter = __esm({
64326
64662
  await this.transport.send(rpcRequest(this.newRequestId, "elicitation/create", requestParams), {
64327
64663
  relatedRequestId
64328
64664
  });
64329
- this.logger.info("[StreamableHttpAdapter] sendElicitRequest: transport.send() completed");
64665
+ this.logger.verbose("[StreamableHttpAdapter] sendElicitRequest: transport.send() completed");
64330
64666
  } catch (error) {
64331
64667
  this.logger.error("[StreamableHttpAdapter] sendElicitRequest: transport.send() failed", error);
64332
64668
  try {
@@ -65799,6 +66135,7 @@ var init_http_request_flow = __esm({
65799
66135
  init_schema7();
65800
66136
  init_errors();
65801
66137
  init_ha_headers();
66138
+ init_skill_mode_utils();
65802
66139
  init_mcp_20260728();
65803
66140
  init_request_log_redaction();
65804
66141
  plan43 = {
@@ -65816,6 +66153,8 @@ var init_http_request_flow = __esm({
65816
66153
  "checkAuthorization",
65817
66154
  // rate limits keyed on the caller's verified identity
65818
66155
  "acquireIdentityQuota",
66156
+ // `?mode=skills_only`: the tool flows hide and refuse tools for this request
66157
+ "resolveSkillsOnlyMode",
65819
66158
  "router"
65820
66159
  ],
65821
66160
  execute: [
@@ -66079,6 +66418,9 @@ var init_http_request_flow = __esm({
66079
66418
  defaultVersion: defaultProtocolVersion
66080
66419
  });
66081
66420
  }
66421
+ async resolveSkillsOnlyMode() {
66422
+ if (detectSkillsOnlyMode(this.rawInput.request.query)) this.tryGetContext()?.set(SKILLS_ONLY_REQUEST, true);
66423
+ }
66082
66424
  async router() {
66083
66425
  try {
66084
66426
  const { request } = this.rawInput;
@@ -66211,7 +66553,7 @@ var init_http_request_flow = __esm({
66211
66553
  }
66212
66554
  const protocol = authorization.session?.payload?.protocol;
66213
66555
  if (protocol) {
66214
- this.logger.info(`[${this.requestId}] decision from session: ${protocol}`);
66556
+ this.logger.verbose(`[${this.requestId}] decision from session: ${protocol}`);
66215
66557
  this.state.set("intent", protocol);
66216
66558
  return;
66217
66559
  }
@@ -66514,6 +66856,9 @@ var init_http_request_flow = __esm({
66514
66856
  __decorateClass([
66515
66857
  Stage44("checkAuthorization")
66516
66858
  ], HttpRequestFlow.prototype, "checkAuthorization", 1);
66859
+ __decorateClass([
66860
+ Stage44("resolveSkillsOnlyMode")
66861
+ ], HttpRequestFlow.prototype, "resolveSkillsOnlyMode", 1);
66517
66862
  __decorateClass([
66518
66863
  Stage44("router")
66519
66864
  ], HttpRequestFlow.prototype, "router", 1);
@@ -66675,7 +67020,7 @@ var init_tracer_provider_utils = __esm({
66675
67020
  import "reflect-metadata";
66676
67021
  import { AuthoritiesContextBuilder } from "@frontmcp/auth";
66677
67022
  import { createGuardManager } from "@frontmcp/guard";
66678
- import { createRedisClient as createRedisClient3, getEnvFlag, getMachineId as getMachineId5, getRuntimeContext as getRuntimeContext15, isEdgeRuntime } from "@frontmcp/utils";
67023
+ import { createRedisClient as createRedisClient3, getEnvFlag, getMachineId as getMachineId5, getRuntimeContext as getRuntimeContext16, isEdgeRuntime } from "@frontmcp/utils";
66679
67024
  var SCOPE_NON_DISPATCHABLE_FLOWS, Scope;
66680
67025
  var init_scope_instance = __esm({
66681
67026
  "libs/sdk/src/scope/scope.instance.ts"() {
@@ -66773,6 +67118,15 @@ var init_scope_instance = __esm({
66773
67118
  routeBase;
66774
67119
  orchestrated = false;
66775
67120
  server;
67121
+ /** The HTTP routes this scope registered (`http.routes`, channel webhooks), in order. */
67122
+ registeredHttpRoutes = [];
67123
+ /** Records each route for adapters without a route server (the web-fetch handler), and mounts it on the host. */
67124
+ httpRouteRegistrar = {
67125
+ registerRoute: (method, path, handler) => {
67126
+ this.registeredHttpRoutes.push({ method, path, handler });
67127
+ return this.server.registerRoute(method, path, handler);
67128
+ }
67129
+ };
66776
67130
  /** Lazy-initialized elicitation store for distributed elicitation support */
66777
67131
  _elicitationStore;
66778
67132
  /** Backend type for the elicitation store (used by the orphan-sqlite WARN guard). */
@@ -66848,7 +67202,7 @@ var init_scope_instance = __esm({
66848
67202
  this.scopeApps = new AppRegistry(this.scopeProviders, this.metadata.apps, scopeRef);
66849
67203
  this.logger.info(`Initializing ${this.metadata.apps.length} app(s)...`);
66850
67204
  const transportConfig = this.metadata.transport;
66851
- const isDistributed = getRuntimeContext15().deployment === "distributed";
67205
+ const isDistributed = getRuntimeContext16().deployment === "distributed";
66852
67206
  if (isDistributed && this.metadata.redis && !this.cliMode) {
66853
67207
  try {
66854
67208
  const haRedis = this.createHaRedisClient();
@@ -66895,7 +67249,7 @@ var init_scope_instance = __esm({
66895
67249
  onOrphan: (sessionId, previousNodeId, session) => transportService.adoptClaimedSession(sessionId, previousNodeId, session)
66896
67250
  });
66897
67251
  }
66898
- if (getRuntimeContext15().deployment === "serverless") {
67252
+ if (getRuntimeContext16().deployment === "serverless") {
66899
67253
  const protocolCfg = transportConfig?.protocol;
66900
67254
  const hasSSE = typeof protocolCfg === "string" ? protocolCfg !== "stateless-api" : protocolCfg?.sse === true;
66901
67255
  if (hasSSE) {
@@ -66963,7 +67317,11 @@ var init_scope_instance = __esm({
66963
67317
  }
66964
67318
  this.logger.warn(msg);
66965
67319
  }
66966
- const { store: taskStore, type: taskType } = await createTaskStore({
67320
+ const {
67321
+ store: taskStore,
67322
+ type: taskType,
67323
+ storage: taskStorage
67324
+ } = await createTaskStore({
66967
67325
  redis: tasksRedis,
66968
67326
  sqlite: tasksSqlite,
66969
67327
  keyPrefix: tasksConfig?.keyPrefix ?? "mcp:task:",
@@ -66971,6 +67329,10 @@ var init_scope_instance = __esm({
66971
67329
  isEdgeRuntime: onEdge
66972
67330
  });
66973
67331
  this._taskStore = taskStore;
67332
+ this.onDispose(async () => {
67333
+ await taskStore.destroy?.();
67334
+ await taskStorage?.disconnect();
67335
+ });
66974
67336
  this.taskBackendType = taskType;
66975
67337
  this._taskRegistry = new TaskRegistry(
66976
67338
  {
@@ -67387,7 +67749,7 @@ var init_scope_instance = __esm({
67387
67749
  }
67388
67750
  registerCustomHttpRoutes({
67389
67751
  routes: this.metadata.http?.routes,
67390
- server: this.server,
67752
+ server: this.httpRouteRegistrar,
67391
67753
  // `session:verify` input uses a loose passthrough request shape; the
67392
67754
  // ServerRequest class instance satisfies it at runtime.
67393
67755
  verifySession: (request) => this.runFlow("session:verify", { request }),
@@ -67397,6 +67759,7 @@ var init_scope_instance = __esm({
67397
67759
  }),
67398
67760
  entryPath: this.entryPath,
67399
67761
  routeBase: this.routeBase,
67762
+ healthPaths: servedHealthPaths(this.metadata.health),
67400
67763
  logger: this.logger
67401
67764
  });
67402
67765
  const channelsConfig = this.metadata.channels;
@@ -67415,13 +67778,14 @@ var init_scope_instance = __esm({
67415
67778
  flowRegistry: this.scopeFlows,
67416
67779
  toolRegistry: this.scopeTools,
67417
67780
  http: {
67418
- server: this.server,
67781
+ server: this.httpRouteRegistrar,
67419
67782
  checkClientIp: (request, response) => this.runFlow("http:ip-filter", {
67420
67783
  request,
67421
67784
  response
67422
67785
  }),
67423
67786
  entryPath: this.entryPath,
67424
- routeBase: this.routeBase
67787
+ routeBase: this.routeBase,
67788
+ healthPaths: servedHealthPaths(this.metadata.health)
67425
67789
  },
67426
67790
  logger: this.logger
67427
67791
  });
@@ -67838,6 +68202,10 @@ var init_scope_instance = __esm({
67838
68202
  get publicAccessGuard() {
67839
68203
  return this._rateLimitManager ?? this._publicAccessGuard;
67840
68204
  }
68205
+ /** The HTTP routes this scope registered (`http.routes`, channel webhooks), guards included. */
68206
+ get httpRoutes() {
68207
+ return this.registeredHttpRoutes;
68208
+ }
67841
68209
  /**
67842
68210
  * Health service for liveness and readiness probes.
67843
68211
  * Returns undefined if health endpoints are disabled.
@@ -68233,6 +68601,7 @@ var init_provider_registry = __esm({
68233
68601
  constructor(list, parentProviders, options) {
68234
68602
  super("ProviderRegistry", parentProviders, list, false);
68235
68603
  this.parentProviders = parentProviders;
68604
+ parentProviders?.childRegistries.add(this);
68236
68605
  this.providedBy = /* @__PURE__ */ new Map();
68237
68606
  const configured = options?.distributedMode !== void 0 || options?.providerCaching !== void 0;
68238
68607
  this.sessionCacheEnabled = !configured && parentProviders ? parentProviders.sessionCacheEnabled : shouldCacheProviders(options?.distributedMode, options?.providerCaching);
@@ -68268,6 +68637,8 @@ var init_provider_registry = __esm({
68268
68637
  sessionCleanupInterval = null;
68269
68638
  /** Whether session caching is enabled (disabled in distributed/serverless mode) */
68270
68639
  sessionCacheEnabled;
68640
+ /** The registries built below this one (an app's, a plugin's, an agent's), disposed with it. */
68641
+ childRegistries = /* @__PURE__ */ new Set();
68271
68642
  getProviders() {
68272
68643
  return [...this.instances.values()];
68273
68644
  }
@@ -68900,7 +69271,7 @@ var init_provider_registry = __esm({
68900
69271
  }
68901
69272
  }
68902
69273
  /**
68903
- * Dispose of the registry, cleaning up all resources.
69274
+ * Dispose of the registry and every registry built below it, cleaning up all resources.
68904
69275
  * Call this when the registry/scope is being destroyed to prevent:
68905
69276
  * - Memory leaks from retained interval handles
68906
69277
  * - Orphaned session cleanup timers
@@ -68912,6 +69283,8 @@ var init_provider_registry = __esm({
68912
69283
  * ```
68913
69284
  */
68914
69285
  dispose() {
69286
+ for (const child of [...this.childRegistries]) child.dispose();
69287
+ this.parentProviders?.childRegistries.delete(this);
68915
69288
  this.stopSessionCleanup();
68916
69289
  this.sessionStores.clear();
68917
69290
  for (const lock of this.sessionBuildLocks.values()) {
@@ -69702,8 +70075,82 @@ var init_web_response_renderer = __esm({
69702
70075
  }
69703
70076
  });
69704
70077
 
69705
- // libs/sdk/src/transport/web-fetch-handler.ts
70078
+ // libs/sdk/src/transport/web-http-route.ts
69706
70079
  import { runRequestExclusive as runRequestExclusive6 } from "@frontmcp/utils";
70080
+ function findRoute(routes, request) {
70081
+ for (const route of routes) {
70082
+ if (route.method !== request.method) continue;
70083
+ const params = matchRoutePath(route.path, request.path);
70084
+ if (params) return { route, params };
70085
+ }
70086
+ return void 0;
70087
+ }
70088
+ function createWebRouteResponse() {
70089
+ let controller;
70090
+ const body = new ReadableStream({ start: (streamController) => controller = streamController });
70091
+ let resolveRendered = () => void 0;
70092
+ const rendered = new Promise((resolve) => resolveRendered = resolve);
70093
+ const response = new RelayServerResponse({
70094
+ head(status, headers) {
70095
+ const webHeaders = new Headers();
70096
+ for (const [name45, value] of Object.entries(headers)) {
70097
+ for (const item of Array.isArray(value) ? value : [value]) webHeaders.append(name45, item);
70098
+ }
70099
+ resolveRendered(new Response(BODYLESS_STATUSES.has(status) ? null : body, { status, headers: webHeaders }));
70100
+ },
70101
+ data(chunk) {
70102
+ const data = decodeRelayChunk(chunk);
70103
+ controller?.enqueue(typeof data === "string" ? encoder5.encode(data) : data);
70104
+ },
70105
+ end() {
70106
+ controller?.close();
70107
+ }
70108
+ });
70109
+ const failBody = (error) => {
70110
+ response.destroy();
70111
+ controller?.error(error);
70112
+ };
70113
+ return { response, rendered, failBody };
70114
+ }
70115
+ function failureResponse(error) {
70116
+ const output = flowErrorToHttpOutput(error);
70117
+ return output ? renderHttpOutputToWebResponse(output) : Response.json({ error: "Internal Server Error" }, { status: 500 });
70118
+ }
70119
+ function serveHttpRouteWeb(routes, request, logger) {
70120
+ const match = findRoute(routes, request);
70121
+ if (!match) return Promise.resolve(void 0);
70122
+ request.params = { ...match.params, ...request.params };
70123
+ const { response, rendered, failBody } = createWebRouteResponse();
70124
+ return new Promise((resolve) => {
70125
+ void rendered.then(resolve);
70126
+ const passOn = () => resolve(void 0);
70127
+ runRequestExclusive6(async () => match.route.handler(request, response.asServerResponse(), passOn)).catch(
70128
+ (error) => {
70129
+ if (!response.headersSent) {
70130
+ resolve(failureResponse(error));
70131
+ return;
70132
+ }
70133
+ logger.error(`HTTP route ${match.route.method} ${match.route.path} failed after its response started`, error);
70134
+ failBody(error);
70135
+ }
70136
+ );
70137
+ });
70138
+ }
70139
+ var encoder5, BODYLESS_STATUSES;
70140
+ var init_web_http_route = __esm({
70141
+ "libs/sdk/src/transport/web-http-route.ts"() {
70142
+ "use strict";
70143
+ init_flow_http_path();
70144
+ init_flow_error_output();
70145
+ init_relay_http();
70146
+ init_web_response_renderer();
70147
+ encoder5 = new TextEncoder();
70148
+ BODYLESS_STATUSES = /* @__PURE__ */ new Set([101, 204, 205, 304]);
70149
+ }
70150
+ });
70151
+
70152
+ // libs/sdk/src/transport/web-fetch-handler.ts
70153
+ import { runRequestExclusive as runRequestExclusive7 } from "@frontmcp/utils";
69707
70154
  function isCloudflareWorkersRuntime(request) {
69708
70155
  if (typeof navigator !== "undefined" && navigator.userAgent === CLOUDFLARE_WORKERS_USER_AGENT) return true;
69709
70156
  const cloudflareProperties = request.cf;
@@ -69947,7 +70394,7 @@ async function runHttpRequestFlowWeb(scope, request, opts = {}) {
69947
70394
  const serverRequest = await toServerRequest(request, url, opts.ctx, opts.persistent, opts.env);
69948
70395
  let output;
69949
70396
  try {
69950
- output = await runRequestExclusive6(
70397
+ output = await runRequestExclusive7(
69951
70398
  () => scope.runFlow("http:request", {
69952
70399
  request: serverRequest,
69953
70400
  response: {}
@@ -69962,10 +70409,10 @@ async function runMatchingHttpFlowWeb(scope, request, opts = {}) {
69962
70409
  const url = new URL(request.url);
69963
70410
  const serverRequest = await toServerRequest(request, url, opts.ctx, void 0, opts.env);
69964
70411
  const flowName = await scope.findHttpFlowName(serverRequest);
69965
- if (!flowName) return void 0;
70412
+ if (!flowName) return serveHttpRouteWeb(scope.httpRoutes, serverRequest, scope.logger);
69966
70413
  let output;
69967
70414
  try {
69968
- output = await runRequestExclusive6(
70415
+ output = await runRequestExclusive7(
69969
70416
  () => scope.runFlow(flowName, {
69970
70417
  request: serverRequest,
69971
70418
  response: {}
@@ -70095,6 +70542,7 @@ var init_web_fetch_handler = __esm({
70095
70542
  init_csp_middleware();
70096
70543
  init_host_validation();
70097
70544
  init_flow_error_output();
70545
+ init_web_http_route();
70098
70546
  init_web_response_renderer();
70099
70547
  CLOUDFLARE_WORKERS_USER_AGENT = "Cloudflare-Workers";
70100
70548
  carriedPeerAddresses = /* @__PURE__ */ new WeakMap();
@@ -70117,9 +70565,6 @@ var init_noop_server = __esm({
70117
70565
  }
70118
70566
  registerRoute(_method, _path2, _handler) {
70119
70567
  }
70120
- enhancedHandler(handler) {
70121
- return handler;
70122
- }
70123
70568
  prepare() {
70124
70569
  }
70125
70570
  getHandler() {
@@ -70327,7 +70772,7 @@ var init_browser_express_host = __esm({
70327
70772
  });
70328
70773
 
70329
70774
  // libs/sdk/src/server/server.instance.ts
70330
- import { getRuntimeContext as getRuntimeContext16, isProduction as isProduction7 } from "@frontmcp/utils";
70775
+ import { getRuntimeContext as getRuntimeContext17, isProduction as isProduction7 } from "@frontmcp/utils";
70331
70776
  var DEFAULT_CORS, FrontMcpServerInstance;
70332
70777
  var init_server_instance = __esm({
70333
70778
  "libs/sdk/src/server/server.instance.ts"() {
@@ -70377,9 +70822,6 @@ var init_server_instance = __esm({
70377
70822
  registerRoute(method, path, handler) {
70378
70823
  return this.host.registerRoute(method, path, handler);
70379
70824
  }
70380
- enhancedHandler(handler) {
70381
- return this.host.enhancedHandler(handler);
70382
- }
70383
70825
  /**
70384
70826
  * Set the health service and config for route registration.
70385
70827
  * Must be called before prepare() to enable enriched health endpoints.
@@ -70436,7 +70878,7 @@ var init_server_instance = __esm({
70436
70878
  }
70437
70879
  async start() {
70438
70880
  this.prepare();
70439
- const deploymentMode = getRuntimeContext16().deployment;
70881
+ const deploymentMode = getRuntimeContext17().deployment;
70440
70882
  const bindAddress = resolveBindAddress(this.config.security, deploymentMode);
70441
70883
  const findings = auditSecurityDefaults(
70442
70884
  {
@@ -71437,6 +71879,7 @@ var execute_task_exports = {};
71437
71879
  __export(execute_task_exports, {
71438
71880
  executeTaskWorker: () => executeTaskWorker
71439
71881
  });
71882
+ import { getHostname as getHostname3 } from "@frontmcp/utils";
71440
71883
  async function executeTaskWorker(options, taskId) {
71441
71884
  const parsedConfig = frontMcpMetadataSchema.parse({
71442
71885
  ...options,
@@ -71517,7 +71960,8 @@ async function executeTaskWorker(options, taskId) {
71517
71960
  executor: {
71518
71961
  host: "cli",
71519
71962
  pid: process.pid,
71520
- spawnedAt: (/* @__PURE__ */ new Date()).toISOString()
71963
+ spawnedAt: (/* @__PURE__ */ new Date()).toISOString(),
71964
+ hostname: getHostname3()
71521
71965
  }
71522
71966
  });
71523
71967
  const onSignal = () => registry.abort(taskId, "SIGTERM");
@@ -73922,21 +74366,22 @@ init_skill_utils();
73922
74366
 
73923
74367
  // libs/sdk/src/skill/skill-directory-loader.ts
73924
74368
  init_skill_metadata();
73925
- import { basename as basename2, fileExists as fileExists6, joinPath as joinPath4, readdir as readdir2, readFile as readFile5, stat as stat3 } from "@frontmcp/utils";
74369
+ import { basename as basename2, fileExists as fileExists6, isAbsolute as isAbsolute4, pathJoin as pathJoin3, pathResolve as pathResolve7, readdir as readdir2, readFile as readFile5, stat as stat3 } from "@frontmcp/utils";
74370
+ init_caller_dir_utils();
73926
74371
  init_sdk_errors();
73927
74372
  init_skill_md_parser();
73928
74373
  async function scanSkillResources(dirPath) {
73929
74374
  const resources = {};
73930
- const scriptsPath = joinPath4(dirPath, "scripts");
73931
- const referencesPath = joinPath4(dirPath, "references");
73932
- const assetsPath = joinPath4(dirPath, "assets");
73933
- const examplesPath = joinPath4(dirPath, "examples");
74375
+ const scriptsPath = pathJoin3(dirPath, "scripts");
74376
+ const referencesPath = pathJoin3(dirPath, "references");
74377
+ const assetsPath = pathJoin3(dirPath, "assets");
74378
+ const examplesPath = pathJoin3(dirPath, "examples");
73934
74379
  const checks = await Promise.all([
73935
74380
  checkDirectory(scriptsPath),
73936
74381
  checkDirectory(referencesPath),
73937
74382
  checkDirectory(assetsPath),
73938
74383
  checkDirectory(examplesPath),
73939
- fileExists6(joinPath4(dirPath, "SKILL.md"))
74384
+ fileExists6(pathJoin3(dirPath, "SKILL.md"))
73940
74385
  ]);
73941
74386
  if (checks[0]) resources.scripts = scriptsPath;
73942
74387
  if (checks[1]) resources.references = referencesPath;
@@ -73968,7 +74413,7 @@ async function findNestedSkillMd(dirPath, maxDepth = Number.POSITIVE_INFINITY) {
73968
74413
  throw err;
73969
74414
  }
73970
74415
  for (const entry of entries) {
73971
- const full = joinPath4(current, entry);
74416
+ const full = pathJoin3(current, entry);
73972
74417
  let entryStat;
73973
74418
  try {
73974
74419
  entryStat = await stat3(full);
@@ -73986,8 +74431,23 @@ async function findNestedSkillMd(dirPath, maxDepth = Number.POSITIVE_INFINITY) {
73986
74431
  await walk(dirPath, 0, "");
73987
74432
  return found.sort();
73988
74433
  }
74434
+ var SKILL_DIRECTORY_LOADER_BASENAMES = ["skill-directory-loader.ts", "skill-directory-loader.js"];
74435
+ async function resolveSkillDirectory(dirPath, callerDir) {
74436
+ if (isAbsolute4(dirPath)) return dirPath;
74437
+ const fromCaller = callerDir ? pathResolve7(callerDir, dirPath) : void 0;
74438
+ if (fromCaller && await fileExists6(pathJoin3(fromCaller, "SKILL.md"))) return fromCaller;
74439
+ const fromCwd = pathResolve7(dirPath);
74440
+ if (await fileExists6(pathJoin3(fromCwd, "SKILL.md"))) return fromCwd;
74441
+ return fromCaller ?? fromCwd;
74442
+ }
73989
74443
  async function loadSkillDirectory(dirPath, logger) {
73990
- const skillMdPath = joinPath4(dirPath, "SKILL.md");
74444
+ return loadResolvedSkillDirectory(
74445
+ await resolveSkillDirectory(dirPath, captureCallerDir(SKILL_DIRECTORY_LOADER_BASENAMES)),
74446
+ logger
74447
+ );
74448
+ }
74449
+ async function loadResolvedSkillDirectory(dirPath, logger) {
74450
+ const skillMdPath = pathJoin3(dirPath, "SKILL.md");
73991
74451
  const exists = await fileExists6(skillMdPath);
73992
74452
  if (!exists) {
73993
74453
  throw new InvalidSkillError(basename2(dirPath), "SKILL.md not found in directory");
@@ -74109,6 +74569,11 @@ init_direct();
74109
74569
  init_direct();
74110
74570
  init_direct();
74111
74571
 
74572
+ // libs/sdk/src/server/adapters/base.host.adapter.ts
74573
+ init_common();
74574
+ var HostServerAdapter = class extends FrontMcpServer {
74575
+ };
74576
+
74112
74577
  // libs/sdk/src/transport/index.ts
74113
74578
  init_transport_types();
74114
74579
  init_in_memory_server();
@@ -74346,6 +74811,7 @@ export {
74346
74811
  HookEntry,
74347
74812
  HookKind,
74348
74813
  HookTargetNotDefinedError,
74814
+ HostServerAdapter,
74349
74815
  HttpBinarySchema,
74350
74816
  HttpConsumedSchema,
74351
74817
  HttpCookieSchema,
@@ -74422,6 +74888,7 @@ export {
74422
74888
  LoggerKind,
74423
74889
  LoggerRegistry,
74424
74890
  MANIFEST_PRIMITIVE_KEYS,
74891
+ MAX_CONCURRENT_TASKS_PER_SESSION,
74425
74892
  MCP_ERROR_CODES,
74426
74893
  McpClientService,
74427
74894
  McpError,
@@ -74564,6 +75031,7 @@ export {
74564
75031
  TaskAlreadyTerminalError,
74565
75032
  TaskAugmentationNotSupportedError,
74566
75033
  TaskAugmentationRequiredError,
75034
+ TaskConcurrencyLimitError,
74567
75035
  TaskNotFoundError,
74568
75036
  TaskNotifier,
74569
75037
  TaskRegistry,