@frontmcp/sdk 1.12.3 → 1.13.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/agent/agent.instance.d.ts +2 -0
  2. package/agent/agent.instance.d.ts.map +1 -1
  3. package/app/instances/app.lazy.instance.d.ts.map +1 -1
  4. package/auth/flows/auth.verify.flow.d.ts.map +1 -1
  5. package/auth/flows/session.verify.flow.d.ts.map +1 -1
  6. package/auth/instances/instance.remote-primary-auth.d.ts +2 -1
  7. package/auth/instances/instance.remote-primary-auth.d.ts.map +1 -1
  8. package/auth/transparent-audience.d.ts +21 -0
  9. package/auth/transparent-audience.d.ts.map +1 -0
  10. package/browser/agent/agent.instance.mjs +9 -1
  11. package/browser/app/instances/app.lazy.instance.mjs +1 -0
  12. package/browser/auth/flows/session.verify.flow.mjs +10 -4
  13. package/browser/auth/instances/instance.remote-primary-auth.mjs +13 -5
  14. package/browser/auth/transparent-audience.mjs +52 -0
  15. package/browser/common/interfaces/tool.interface.mjs +4 -0
  16. package/browser/common/metadata/app.metadata.mjs +2 -0
  17. package/browser/common/metadata/front-mcp.metadata.mjs +4 -0
  18. package/browser/common/metadata/input-policy.mjs +12 -0
  19. package/browser/common/metadata/output-policy.mjs +1 -0
  20. package/browser/common/metadata/tool.metadata.mjs +3 -1
  21. package/browser/common/tokens/app.tokens.mjs +1 -0
  22. package/browser/common/tokens/front-mcp.tokens.mjs +1 -0
  23. package/browser/common/tokens/tool.tokens.mjs +2 -1
  24. package/browser/context/frontmcp-context.mjs +2 -2
  25. package/browser/elicitation/questions/ask-question.mjs +1 -2
  26. package/browser/elicitation/questions/question.store.mjs +22 -8
  27. package/browser/elicitation/send-elicitation-result.tool.mjs +11 -6
  28. package/browser/index.cjs +5017 -4157
  29. package/browser/notification/notification.service.mjs +1 -0
  30. package/browser/remote-mcp/factories/record-builders.mjs +2 -0
  31. package/browser/resource/flows/read-resource.flow.mjs +33 -10
  32. package/browser/scope/scope.instance.mjs +3 -1
  33. package/browser/server/security/resolve-allowed-hosts.mjs +3 -2
  34. package/browser/task/store/storage-task.store.mjs +69 -20
  35. package/browser/task/store/task-session-index.mjs +300 -0
  36. package/browser/task/store/task-store.factory.mjs +4 -1
  37. package/browser/tool/flows/call-tool.flow.mjs +103 -21
  38. package/browser/tool/flows/tools-list.flow.mjs +49 -8
  39. package/browser/tool/tool-output-policy.mjs +14 -3
  40. package/browser/tool/tool.instance.mjs +9 -2
  41. package/browser/tool/tool.utils.mjs +90 -3
  42. package/browser/tool/ui/app-only-tools.mjs +17 -0
  43. package/browser/tool/undeclared-arguments-message.mjs +61 -0
  44. package/browser/tool/undeclared-arguments.mjs +35 -0
  45. package/browser/transport/flows/handle.mcp-20260728.flow.mjs +12 -16
  46. package/common/entries/tool.entry.d.ts +12 -1
  47. package/common/entries/tool.entry.d.ts.map +1 -1
  48. package/common/interfaces/tool.interface.d.ts +17 -0
  49. package/common/interfaces/tool.interface.d.ts.map +1 -1
  50. package/common/metadata/app.metadata.d.ts +19 -0
  51. package/common/metadata/app.metadata.d.ts.map +1 -1
  52. package/common/metadata/front-mcp.metadata.d.ts +161 -9
  53. package/common/metadata/front-mcp.metadata.d.ts.map +1 -1
  54. package/common/metadata/index.d.ts +1 -0
  55. package/common/metadata/index.d.ts.map +1 -1
  56. package/common/metadata/input-policy.d.ts +22 -0
  57. package/common/metadata/input-policy.d.ts.map +1 -0
  58. package/common/metadata/output-policy.d.ts +21 -3
  59. package/common/metadata/output-policy.d.ts.map +1 -1
  60. package/common/metadata/tool.metadata.d.ts +20 -1
  61. package/common/metadata/tool.metadata.d.ts.map +1 -1
  62. package/common/records/app.record.d.ts +2 -1
  63. package/common/records/app.record.d.ts.map +1 -1
  64. package/common/tokens/app.tokens.d.ts.map +1 -1
  65. package/common/tokens/front-mcp.tokens.d.ts.map +1 -1
  66. package/common/tokens/tool.tokens.d.ts +1 -0
  67. package/common/tokens/tool.tokens.d.ts.map +1 -1
  68. package/elicitation/elicitation.types.d.ts +2 -0
  69. package/elicitation/elicitation.types.d.ts.map +1 -1
  70. package/elicitation/questions/ask-question.d.ts.map +1 -1
  71. package/elicitation/questions/question.store.d.ts +5 -0
  72. package/elicitation/questions/question.store.d.ts.map +1 -1
  73. package/esm/index.mjs +31 -31
  74. package/index.d.ts +15 -15
  75. package/index.js +40 -40
  76. package/notification/notification.service.d.ts.map +1 -1
  77. package/package.json +10 -10
  78. package/remote-mcp/factories/record-builders.d.ts.map +1 -1
  79. package/resource/flows/read-resource.flow.d.ts +13 -1
  80. package/resource/flows/read-resource.flow.d.ts.map +1 -1
  81. package/scope/scope.instance.d.ts.map +1 -1
  82. package/server/security/resolve-allowed-hosts.d.ts +4 -2
  83. package/server/security/resolve-allowed-hosts.d.ts.map +1 -1
  84. package/task/store/storage-task.store.d.ts +19 -2
  85. package/task/store/storage-task.store.d.ts.map +1 -1
  86. package/task/store/task-session-index.d.ts +100 -0
  87. package/task/store/task-session-index.d.ts.map +1 -0
  88. package/task/store/task-store.factory.d.ts +5 -0
  89. package/task/store/task-store.factory.d.ts.map +1 -1
  90. package/task/task.types.d.ts +6 -0
  91. package/task/task.types.d.ts.map +1 -1
  92. package/tool/flows/call-tool.flow.d.ts +13 -1
  93. package/tool/flows/call-tool.flow.d.ts.map +1 -1
  94. package/tool/flows/tools-list.flow.d.ts +8 -1
  95. package/tool/flows/tools-list.flow.d.ts.map +1 -1
  96. package/tool/tool-output-policy.d.ts +6 -1
  97. package/tool/tool-output-policy.d.ts.map +1 -1
  98. package/tool/tool.instance.d.ts +2 -0
  99. package/tool/tool.instance.d.ts.map +1 -1
  100. package/tool/tool.utils.d.ts +12 -0
  101. package/tool/tool.utils.d.ts.map +1 -1
  102. package/tool/ui/app-only-tools.d.ts +9 -0
  103. package/tool/ui/app-only-tools.d.ts.map +1 -0
  104. package/tool/undeclared-arguments-message.d.ts +13 -0
  105. package/tool/undeclared-arguments-message.d.ts.map +1 -0
  106. package/tool/undeclared-arguments.d.ts +7 -0
  107. package/tool/undeclared-arguments.d.ts.map +1 -0
  108. package/transport/flows/handle.mcp-20260728.flow.d.ts.map +1 -1
@@ -60,6 +60,7 @@ import {
60
60
  ToolEntry
61
61
  } from "../../common/index.mjs";
62
62
  import { callSurfaceOf, entryUnavailableError, isOfferedOnSurface } from "../../common/availability/index.mjs";
63
+ import { resolveInputUndeclaredKeysPolicy } from "../../common/metadata/input-policy.mjs";
63
64
  import { normalizeToolAuthProviders, resolveToolVisibility } from "../../common/metadata/tool.metadata.mjs";
64
65
  import {
65
66
  lookupTool,
@@ -103,9 +104,12 @@ import { TaskNotifier } from "../../task/helpers/task-notifier.mjs";
103
104
  import { TASK_DEFAULTS, toWireShape } from "../../task/task.types.mjs";
104
105
  import { linkedAbortController } from "../../utils/abort.utils.mjs";
105
106
  import { appOwnerIdOf, hookOwnerIdOf, isServerEntryOwner } from "../../utils/lineage.utils.mjs";
106
- import { toolOutputPolicies } from "../tool-output-policy.mjs";
107
+ import { resolveStructuredContentValidation, toolInputPolicies, toolOutputPolicies } from "../tool-output-policy.mjs";
108
+ import { asElicitationFallback, isReturnedCallToolResult } from "../tool.utils.mjs";
109
+ import { isAppOnlyTool, knownPlatformOf, rendersAppPages } from "../ui/app-only-tools.mjs";
107
110
  import { toolServingMode } from "../ui/serving-mode-default.mjs";
108
111
  import { hasUIConfig, WIDGET_CALL_META_KEY } from "../ui/ui-shared.mjs";
112
+ import { findUndeclaredArguments, formatKeyPath } from "../undeclared-arguments.mjs";
109
113
  import { askToOpenConnectPages, credentialsRequiredErrorOf, evaluateToolCredentialGate } from "./tool-credentials.gate.mjs";
110
114
  function htmlResponsePrefixFor(ui, platformType) {
111
115
  const prefix = ui?.htmlResponsePrefix;
@@ -137,6 +141,8 @@ var stateSchema = z.object({
137
141
  uiResult: z.any().optional(),
138
142
  // UI metadata from rendering (merged into _meta)
139
143
  uiMeta: z.record(z.string(), z.unknown()).optional(),
144
+ // Under input.undeclaredKeys 'warn': the line the answer ends with, naming the arguments that were ignored
145
+ undeclaredArgumentsNote: z.string().optional(),
140
146
  // Metadata hooks add to the result (e.g. the cache plugin's `cache: 'hit'`), merged into the
141
147
  // result's _meta; never merged into rawOutput, which is the tool's data
142
148
  resultMeta: z.record(z.string(), z.unknown()).optional(),
@@ -168,6 +174,8 @@ var plan = {
168
174
  // A session that listed an older tool list is told so before a tool it may no longer have is looked up
169
175
  "checkSurface",
170
176
  "findTool",
177
+ // A hook that switched the tool hands the run over to the hooks of the tool that runs
178
+ "useToolHooks",
171
179
  "checkEnabled",
172
180
  // A lazy app's entry that is on and still a placeholder: its app failed to load before this run
173
181
  "checkAppLoaded",
@@ -197,6 +205,8 @@ var toolClassHooksJoin = entryClassHooksJoin({ flow: name, plan, contextStage: "
197
205
  var { Stage } = FlowHooksOf(name);
198
206
  var resolvedTools = new ResolvedEntries();
199
207
  var reportedUndeclaredKeyPaths = /* @__PURE__ */ new WeakMap();
208
+ var reportedInvalidStructuredContent = /* @__PURE__ */ new WeakSet();
209
+ var reportedUndeclaredArguments = /* @__PURE__ */ new WeakMap();
200
210
  var reportedUnfittedTools = /* @__PURE__ */ new WeakSet();
201
211
  var loggedAliasCalls = /* @__PURE__ */ new WeakMap();
202
212
  var MAX_REPORTED_UNDECLARED_KEY_PATHS = 100;
@@ -221,6 +231,8 @@ var CallToolFlow = class extends FlowBase {
221
231
  return (resolvedTools.peek(rawInput, toolName) ?? lookupTool(scope, toolName))?.record.provide;
222
232
  }
223
233
  logger = this.scopeLogger.child("CallToolFlow");
234
+ /** The output the UI renders, parsed once per call (see {@link uiOutput}). */
235
+ declaredUiOutput;
224
236
  /** The tool's name (its `id`, else its `name`) once `findTool` resolved it, else the name the call asks for. */
225
237
  get toolName() {
226
238
  return this.state.tool?.name ?? (this.state.input ?? this.input.request.params).name;
@@ -328,11 +340,24 @@ var CallToolFlow = class extends FlowBase {
328
340
  this.logger.warn(`findTool: rejecting external tools/call for internal tool "${name2}"`);
329
341
  throw new ToolNotFoundError(name2);
330
342
  }
343
+ const isTaskRun = Boolean(ctxObj?.taskId);
344
+ if (isAppOnlyTool(tool.metadata) && this.isClientCall() && !isTaskRun && !rendersAppPages(this.appPagePlatform())) {
345
+ this.logger.warn(`findTool: rejecting tools/call of "${name2}", a tool for the MCP Apps page only`);
346
+ throw new ToolNotFoundError(name2);
347
+ }
331
348
  this.logger = this.logger.child(`CallToolFlow(${name2})`);
332
349
  this.state.set("tool", tool);
333
350
  this.logger.verbose(`findTool: tool "${name2}" found`);
334
351
  this.logger.verbose("findTool:done");
335
352
  }
353
+ async useToolHooks() {
354
+ const { tool } = this.state;
355
+ if (!tool) return;
356
+ await this.useEntryHooks(
357
+ hookOwnerIdOf(this.scope.tools.lineageOf(tool) ?? [], tool.owner),
358
+ tool.record.provide
359
+ );
360
+ }
336
361
  async checkEnabled() {
337
362
  const { tool } = this.state.required;
338
363
  await assertEntryEnabled("Tool", tool.name, tool.metadata.enabled, this.tryGetContext(), this.logger);
@@ -664,13 +689,15 @@ var CallToolFlow = class extends FlowBase {
664
689
  context.mark("createToolCallContext");
665
690
  context._toolNameInternal = tool.metadata.id ?? tool.metadata.name;
666
691
  context._toolInputInternal = input.arguments;
692
+ context.idempotencyKey = ctx.idempotencyKey;
667
693
  context._jsonRpcRequestIdInternal = this.state.jsonRpcRequestId;
668
694
  context._onRespondInternal = (value) => this.state.set("rawOutput", value);
695
+ context._onRecordsChangedInternal = ctx.onRecordsChanged;
669
696
  const frontmcpContext = context.tryGetContext();
670
697
  const authInfoWithTransport = authInfo;
671
- if (frontmcpContext && authInfoWithTransport?.transport?.sendElicitRequest) {
698
+ const jsonRpcRequestId = this.state.jsonRpcRequestId;
699
+ if (frontmcpContext && authInfoWithTransport?.transport?.sendElicitRequest && jsonRpcRequestId !== void 0) {
672
700
  const transport = authInfoWithTransport.transport;
673
- const jsonRpcRequestId = this.state.jsonRpcRequestId;
674
701
  frontmcpContext.setTransport({
675
702
  sendElicitRequest: transport.sendElicitRequest.bind(transport),
676
703
  type: transport.type,
@@ -797,7 +824,6 @@ var CallToolFlow = class extends FlowBase {
797
824
  toolContext.mark("validateInput");
798
825
  try {
799
826
  toolContext.input = tool.parseInput(input);
800
- this.logger.verbose("validateInput:done");
801
827
  } catch (err) {
802
828
  if (err instanceof z.ZodError) {
803
829
  throw new InvalidInputError("Invalid tool input", err.issues);
@@ -805,6 +831,21 @@ var CallToolFlow = class extends FlowBase {
805
831
  this.logger.error("validateInput: failed to parse input", err);
806
832
  throw new InvalidInputError("Unknown error occurred when trying to parse input");
807
833
  }
834
+ await this.applyInputPolicy(tool, input.arguments, toolContext.input);
835
+ this.logger.verbose("validateInput:done");
836
+ }
837
+ /** `input.undeclaredKeys` for the arguments the `inputSchema` does not declare, which parsing dropped. */
838
+ async applyInputPolicy(tool, sent, parsed) {
839
+ const policy = resolveInputUndeclaredKeysPolicy(...toolInputPolicies(tool, this.scope));
840
+ if (policy === "strip") return;
841
+ const keyPaths = findUndeclaredArguments(tool.inputSchema ?? {}, sent, parsed);
842
+ if (keyPaths.length === 0) return;
843
+ const messages = await import("../undeclared-arguments-message.mjs");
844
+ const declaredKeys = Object.keys(tool.inputSchema ?? {});
845
+ if (policy === "fail") throw new InvalidInputError(messages.undeclaredArgumentsRefusal(keyPaths, declaredKeys));
846
+ this.state.set("undeclaredArgumentsNote", messages.undeclaredArgumentsNote(keyPaths, declaredKeys));
847
+ const newKeyPaths = unreportedKeyPaths(reportedUndeclaredArguments, tool, keyPaths.map(formatKeyPath));
848
+ if (newKeyPaths.length > 0) this.logger.warn(messages.undeclaredArgumentsWarning(tool.metadata.name, newKeyPaths));
808
849
  }
809
850
  async execute() {
810
851
  this.logger.verbose("execute:start");
@@ -818,6 +859,8 @@ var CallToolFlow = class extends FlowBase {
818
859
  const running = runOnSurface(
819
860
  callSurfaceOf(this.input.ctx),
820
861
  () => runAsTool({ name: tool.name, fullName: tool.fullName }, async () => {
862
+ await this.input.ctx.beforeExecute?.();
863
+ if (toolContext.signal?.aborted) return;
821
864
  toolContext.output = await toolContext.execute(toolContext.input);
822
865
  })
823
866
  );
@@ -871,6 +914,7 @@ var CallToolFlow = class extends FlowBase {
871
914
  // no `tools/call` resolves.
872
915
  toolName: tool.fullName,
873
916
  toolInput: this.state.required.input.arguments,
917
+ idempotencyKey: toolContext.idempotencyKey,
874
918
  elicitMessage: error.elicitMessage,
875
919
  elicitSchema: error.schema,
876
920
  createdAt: Date.now(),
@@ -915,7 +959,7 @@ ${JSON.stringify(error.schema, null, 2)}
915
959
  }
916
960
  }
917
961
  };
918
- toolContext.output = fallbackResponse;
962
+ toolContext.output = asElicitationFallback(fallbackResponse);
919
963
  this.logger.verbose("execute:done (elicitation fire-and-forget fallback)");
920
964
  return;
921
965
  }
@@ -962,8 +1006,7 @@ ${JSON.stringify(error.schema, null, 2)}
962
1006
  }
963
1007
  async applyUI() {
964
1008
  this.logger.verbose("applyUI:start");
965
- const { tool, rawOutput: executeOutput, input } = this.state;
966
- const rawOutput = declaredOutput(tool, executeOutput);
1009
+ const { tool, input } = this.state;
967
1010
  const ctx = this.input.ctx;
968
1011
  if (ctx?._skipUI || isWidgetCall(input?.["_meta"])) {
969
1012
  this.logger.verbose("applyUI:skip (agent or widget call - structured data only)");
@@ -973,6 +1016,7 @@ ${JSON.stringify(error.schema, null, 2)}
973
1016
  this.logger.verbose("applyUI:skip (no UI config)");
974
1017
  return;
975
1018
  }
1019
+ const rawOutput = this.uiOutput();
976
1020
  try {
977
1021
  const scope = this.scope;
978
1022
  const { buildToolResponseContent, isUIRenderFailure, MCP_APPS_MIME_TYPE, resolveServingMode } = await import("../ui/ui-render.mjs");
@@ -1099,9 +1143,9 @@ ${JSON.stringify(error.schema, null, 2)}
1099
1143
  * is rendered for this call when the serving mode didn't, and goes to this caller only.
1100
1144
  */
1101
1145
  async applyHtmlResponse(prefix, renderedHtml, platformType) {
1102
- const { tool, rawOutput: executeOutput, input } = this.state;
1146
+ const { tool, input } = this.state;
1103
1147
  if (!tool || !this.scope.toolUI) return;
1104
- const rawOutput = declaredOutput(tool, executeOutput);
1148
+ const rawOutput = this.uiOutput();
1105
1149
  const { buildHtmlResponseText, buildToolResponseContent, isUIRenderFailure } = await import("../ui/ui-render.mjs");
1106
1150
  let html = renderedHtml;
1107
1151
  if (html === void 0) {
@@ -1135,9 +1179,10 @@ ${JSON.stringify(error.schema, null, 2)}
1135
1179
  const outputPolicies = toolOutputPolicies(tool, this.scope);
1136
1180
  const undeclaredKeys = resolveUndeclaredKeysPolicy(...outputPolicies);
1137
1181
  const parseResult = tool.safeParseOutput(rawOutput, {
1138
- // A call that renders the tool's UI sends declared keys only, whatever the policy
1139
- undeclaredKeys: uiResult && undeclaredKeys === "keep" ? "strip" : undeclaredKeys,
1140
- onUndeclaredKeys: (keyPaths) => this.warnUndeclaredKeysOnce(tool, keyPaths)
1182
+ undeclaredKeys,
1183
+ onUndeclaredKeys: (keyPaths) => this.warnUndeclaredKeysOnce(tool, keyPaths),
1184
+ validateStructuredContent: resolveStructuredContentValidation(...outputPolicies),
1185
+ onInvalidStructuredContent: () => this.warnInvalidStructuredContentOnce(tool)
1141
1186
  });
1142
1187
  if (!parseResult.success) {
1143
1188
  this.logger.error("finalize: output validation failed", {
@@ -1161,7 +1206,7 @@ ${JSON.stringify(error.schema, null, 2)}
1161
1206
  });
1162
1207
  }
1163
1208
  }
1164
- const result = parseResult.data;
1209
+ const result = { ...parseResult.data };
1165
1210
  const rawMeta = (() => {
1166
1211
  if (typeof rawOutput !== "object" || rawOutput === null) return void 0;
1167
1212
  const meta = rawOutput["_meta"];
@@ -1184,6 +1229,10 @@ ${JSON.stringify(error.schema, null, 2)}
1184
1229
  result._meta = { ...result._meta, ...uiMeta };
1185
1230
  }
1186
1231
  }
1232
+ const { undeclaredArgumentsNote } = this.state;
1233
+ if (undeclaredArgumentsNote) {
1234
+ result.content = [...result.content, { type: "text", text: undeclaredArgumentsNote }];
1235
+ }
1187
1236
  this.logger.verbose("finalize: sending response", {
1188
1237
  tool: tool.metadata.name,
1189
1238
  hasContent: Array.isArray(result.content) && result.content.length > 0,
@@ -1257,6 +1306,16 @@ ${JSON.stringify(error.schema, null, 2)}
1257
1306
  const sessionId = authInfo?.sessionId;
1258
1307
  return authInfo?.sessionIdPayload?.platformType ?? this.tryGetContext()?.platformType ?? (sessionId ? this.scope.notifications.getPlatformType(sessionId) : void 0) ?? "unknown";
1259
1308
  }
1309
+ /** The caller's platform for a tool meant for the MCP Apps page: what it negotiated before a user-agent guess. */
1310
+ appPagePlatform() {
1311
+ const { authInfo } = this.state;
1312
+ const sessionId = authInfo?.sessionId;
1313
+ return knownPlatformOf(
1314
+ this.tryGetContext()?.platformType,
1315
+ sessionId ? this.scope.notifications.getPlatformType(sessionId) : void 0,
1316
+ authInfo?.sessionIdPayload?.platformType
1317
+ );
1318
+ }
1260
1319
  callerProfile() {
1261
1320
  return callerClientProfile(this.scope.metadata.clients, {
1262
1321
  context: this.tryGetContext(),
@@ -1275,13 +1334,25 @@ ${JSON.stringify(error.schema, null, 2)}
1275
1334
  const isObjectSchema = typeof schema === "object" && schema !== null && Reflect.get(schema, "type") === "object";
1276
1335
  return (schemaMode === "definition" || schemaMode === "both") && isObjectSchema;
1277
1336
  }
1337
+ /** What the UI renders and echoes: what the `outputSchema` declares, and undeclared keys under 'keep'; parsed once. */
1338
+ uiOutput() {
1339
+ const { tool, rawOutput } = this.state;
1340
+ if (!tool) return rawOutput;
1341
+ if (this.declaredUiOutput) return this.declaredUiOutput.value;
1342
+ const keepsUndeclaredKeys = resolveUndeclaredKeysPolicy(...toolOutputPolicies(tool, this.scope)) === "keep";
1343
+ this.declaredUiOutput = { value: declaredOutput(tool, rawOutput, keepsUndeclaredKeys ? "keep" : "strip") };
1344
+ return this.declaredUiOutput.value;
1345
+ }
1346
+ warnInvalidStructuredContentOnce(tool) {
1347
+ if (reportedInvalidStructuredContent.has(tool)) return;
1348
+ reportedInvalidStructuredContent.add(tool);
1349
+ this.logger.warn(
1350
+ `Tool "${tool.metadata.name}" returned a CallToolResult whose structuredContent is missing or does not match its outputSchema, and output.validateStructuredContent: 'warn' sent it as returned. Without 'warn' such an answer is refused with INVALID_OUTPUT.`
1351
+ );
1352
+ }
1278
1353
  warnUndeclaredKeysOnce(tool, keyPaths) {
1279
- const reportedKeyPaths = reportedUndeclaredKeyPaths.get(tool) ?? /* @__PURE__ */ new Set();
1280
- reportedUndeclaredKeyPaths.set(tool, reportedKeyPaths);
1281
- const roomLeft = MAX_REPORTED_UNDECLARED_KEY_PATHS - reportedKeyPaths.size;
1282
- const newKeyPaths = keyPaths.filter((keyPath) => !reportedKeyPaths.has(keyPath)).slice(0, roomLeft);
1354
+ const newKeyPaths = unreportedKeyPaths(reportedUndeclaredKeyPaths, tool, keyPaths);
1283
1355
  if (newKeyPaths.length === 0) return;
1284
- newKeyPaths.forEach((keyPath) => reportedKeyPaths.add(keyPath));
1285
1356
  this.logger.warn(
1286
1357
  `Tool "${tool.metadata.name}" answered with keys its outputSchema does not declare, so they were stripped: ${newKeyPaths.join(", ")}. Declare them, or set output.undeclaredKeys to 'strip', 'keep' or 'fail'.`
1287
1358
  );
@@ -1303,6 +1374,9 @@ __decorateClass([
1303
1374
  __decorateClass([
1304
1375
  Stage("findTool")
1305
1376
  ], CallToolFlow.prototype, "findTool", 1);
1377
+ __decorateClass([
1378
+ Stage("useToolHooks")
1379
+ ], CallToolFlow.prototype, "useToolHooks", 1);
1306
1380
  __decorateClass([
1307
1381
  Stage("checkEnabled")
1308
1382
  ], CallToolFlow.prototype, "checkEnabled", 1);
@@ -1372,11 +1446,19 @@ CallToolFlow = __decorateClass([
1372
1446
  access: "public"
1373
1447
  })
1374
1448
  ], CallToolFlow);
1375
- function declaredOutput(tool, output) {
1449
+ function unreportedKeyPaths(reported, tool, keyPaths) {
1450
+ const reportedKeyPaths = reported.get(tool) ?? /* @__PURE__ */ new Set();
1451
+ reported.set(tool, reportedKeyPaths);
1452
+ const roomLeft = MAX_REPORTED_UNDECLARED_KEY_PATHS - reportedKeyPaths.size;
1453
+ const newKeyPaths = keyPaths.filter((keyPath) => !reportedKeyPaths.has(keyPath)).slice(0, roomLeft);
1454
+ newKeyPaths.forEach((keyPath) => reportedKeyPaths.add(keyPath));
1455
+ return newKeyPaths;
1456
+ }
1457
+ function declaredOutput(tool, output, undeclaredKeys) {
1376
1458
  if (!tool?.outputSchema || typeof output !== "object" || output === null || Array.isArray(output)) return output;
1377
- if (Array.isArray(output["content"])) return output;
1378
- const parsed = tool.safeParseOutput(output);
1459
+ const parsed = tool.safeParseOutput(output, { undeclaredKeys });
1379
1460
  if (!parsed.success) return output;
1461
+ if (isReturnedCallToolResult(tool.outputSchema, output)) return parsed.data;
1380
1462
  const structured = parsed.data.structuredContent;
1381
1463
  return typeof structured === "object" && structured !== null && !Array.isArray(structured) ? structured : output;
1382
1464
  }
@@ -36,6 +36,7 @@ import { isSkillsOnlyRequest } from "../../skill/skill-mode.utils.mjs";
36
36
  import { enabledItems, SURFACE_META_KEY, surfaceHash } from "../../surface/index.mjs";
37
37
  import { isListedByAuthorities } from "../../surface/entry-authorized.mjs";
38
38
  import { toolOutputPolicies } from "../tool-output-policy.mjs";
39
+ import { isAppOnlyTool, knownPlatformOf, rendersAppPages } from "../ui/app-only-tools.mjs";
39
40
  import { buildStaticWidgetUri, hasUIConfig } from "../ui/ui-shared.mjs";
40
41
  var inputSchema = z.object({
41
42
  request: ListToolsRequestSchema,
@@ -71,13 +72,22 @@ var stateSchema = z.object({
71
72
  });
72
73
  var plan = {
73
74
  pre: ["parseInput", "ensureRemoteCapabilities"],
74
- execute: ["findTools", "filterByEnabled", "filterByAuthorities", "filterByPublicAccess", "resolveConflicts"],
75
+ execute: [
76
+ "findTools",
77
+ "filterByEnabled",
78
+ "filterByAuthorities",
79
+ "filterByPublicAccess",
80
+ "filterByAppVisibility",
81
+ "resolveConflicts"
82
+ ],
75
83
  post: ["parseTools"]
76
84
  };
77
85
  var name = "tools:list-tools";
78
86
  var { Stage } = FlowHooksOf("tools:list-tools");
79
87
  var ToolsListFlow = class extends FlowBase {
80
88
  logger = this.scopeLogger.child("ToolsListFlow");
89
+ /** The names hooks asked `removeTool` to leave out, applied to the tools whenever `findTools` finds them. */
90
+ removedToolNames = /* @__PURE__ */ new Set();
81
91
  sample(arr, n = 5) {
82
92
  return arr.slice(0, n);
83
93
  }
@@ -198,7 +208,10 @@ var ToolsListFlow = class extends FlowBase {
198
208
  if (tools.length === 0) {
199
209
  this.logger.warn("findTools: no tools found across apps");
200
210
  }
201
- this.state.set("tools", tools);
211
+ this.state.set(
212
+ "tools",
213
+ tools.filter(({ tool }) => !this.isRemoved(tool))
214
+ );
202
215
  this.state.set("foundTools", tools);
203
216
  this.logger.verbose("findTools:done");
204
217
  } catch (error) {
@@ -251,6 +264,33 @@ var ToolsListFlow = class extends FlowBase {
251
264
  )
252
265
  );
253
266
  }
267
+ /** Leave a tool out of this listing, by its listed or its own name: for a hook on any stage up to `parseTools`. */
268
+ removeTool(name2) {
269
+ this.removedToolNames.add(name2);
270
+ const { tools, resolvedTools } = this.state;
271
+ const keptTools = tools?.filter(({ tool }) => !this.isRemoved(tool));
272
+ const keptResolvedTools = resolvedTools?.filter(({ tool, finalName }) => !this.isRemoved(tool, finalName));
273
+ if (keptTools) this.state.set("tools", keptTools);
274
+ if (keptResolvedTools) this.state.set("resolvedTools", keptResolvedTools);
275
+ }
276
+ isRemoved(tool, finalName) {
277
+ const names = [finalName, tool.fullName, tool.metadata.id ?? tool.metadata.name];
278
+ return names.some((name2) => name2 !== void 0 && this.removedToolNames.has(name2));
279
+ }
280
+ async filterByAppVisibility() {
281
+ const { authInfo } = this.state;
282
+ const sessionId = authInfo?.sessionId;
283
+ const callerPlatform = knownPlatformOf(
284
+ this.tryGetContext()?.platformType,
285
+ sessionId ? this.scope.notifications?.getPlatformType(sessionId) : void 0,
286
+ authInfo?.sessionIdPayload?.platformType
287
+ );
288
+ if (rendersAppPages(callerPlatform)) return;
289
+ this.state.set(
290
+ "tools",
291
+ this.state.required.tools.filter(({ tool }) => !isAppOnlyTool(tool.metadata))
292
+ );
293
+ }
254
294
  async resolveConflicts() {
255
295
  this.logger.verbose("resolveConflicts:start");
256
296
  try {
@@ -381,6 +421,8 @@ var ToolsListFlow = class extends FlowBase {
381
421
  const meta = {};
382
422
  const isExtApps = platformType === "ext-apps";
383
423
  const widgetUri = uiConfig.resourceUri || buildStaticWidgetUri(finalName);
424
+ const declaredUiMeta = tool.metadata._meta?.["ui"];
425
+ const ownUiMeta = typeof declaredUiMeta === "object" && declaredUiMeta !== null ? declaredUiMeta : {};
384
426
  const applySizingMeta = (uiMeta) => {
385
427
  if (uiConfig.preferredHeight !== void 0) uiMeta["preferredHeight"] = uiConfig.preferredHeight;
386
428
  if (uiConfig.minHeight !== void 0) uiMeta["minHeight"] = uiConfig.minHeight;
@@ -389,9 +431,7 @@ var ToolsListFlow = class extends FlowBase {
389
431
  if (uiConfig.autoResize !== void 0) uiMeta["autoResize"] = uiConfig.autoResize;
390
432
  };
391
433
  if (isExtApps) {
392
- const uiMeta = {
393
- resourceUri: widgetUri
394
- };
434
+ const uiMeta = { ...ownUiMeta, resourceUri: widgetUri };
395
435
  if (uiConfig.csp) {
396
436
  uiMeta["csp"] = uiConfig.csp;
397
437
  }
@@ -415,9 +455,7 @@ var ToolsListFlow = class extends FlowBase {
415
455
  meta["frontmcp/displayMode"] = manifest.displayMode;
416
456
  }
417
457
  } else {
418
- const uiMeta = {
419
- resourceUri: widgetUri
420
- };
458
+ const uiMeta = { ...ownUiMeta, resourceUri: widgetUri };
421
459
  if (uiConfig.csp) {
422
460
  uiMeta["csp"] = uiConfig.csp;
423
461
  }
@@ -476,6 +514,9 @@ __decorateClass([
476
514
  __decorateClass([
477
515
  Stage("filterByPublicAccess")
478
516
  ], ToolsListFlow.prototype, "filterByPublicAccess", 1);
517
+ __decorateClass([
518
+ Stage("filterByAppVisibility")
519
+ ], ToolsListFlow.prototype, "filterByAppVisibility", 1);
479
520
  __decorateClass([
480
521
  Stage("resolveConflicts")
481
522
  ], ToolsListFlow.prototype, "resolveConflicts", 1);
@@ -4,11 +4,20 @@ import {
4
4
  } from "../common/index.mjs";
5
5
  import { appOwnerIdOf } from "../utils/lineage.utils.mjs";
6
6
  function toolOutputPolicies(tool, scope) {
7
- const appId = appOwnerIdOf(scope.tools.lineageOf(tool) ?? [], tool.owner);
8
- const app = appId === void 0 ? void 0 : scope.apps.getApps().find((candidate) => candidate.id === appId);
9
- const appOutput = app?.metadata?.output;
7
+ const appOutput = appMetadataOf(tool, scope)?.output;
10
8
  return [tool.metadata.output, appOutput, scope.metadata.output];
11
9
  }
10
+ function resolveStructuredContentValidation(tool, app, server) {
11
+ return tool?.validateStructuredContent ?? app?.validateStructuredContent ?? server?.validateStructuredContent ?? "enforce";
12
+ }
13
+ function toolInputPolicies(tool, scope) {
14
+ const appInput = appMetadataOf(tool, scope)?.input;
15
+ return [tool.metadata.input, appInput, scope.metadata.input];
16
+ }
17
+ function appMetadataOf(tool, scope) {
18
+ const appId = appOwnerIdOf(scope.tools.lineageOf(tool) ?? [], tool.owner);
19
+ return appId === void 0 ? void 0 : scope.apps.getApps().find((candidate) => candidate.id === appId)?.metadata;
20
+ }
12
21
  function describeUnlistedOutputSchemas(scope) {
13
22
  return scope.tools.getTools().flatMap((tool) => {
14
23
  const reason = tool.getUnlistedOutputSchemaReason();
@@ -20,5 +29,7 @@ function describeUnlistedOutputSchemas(scope) {
20
29
  }
21
30
  export {
22
31
  describeUnlistedOutputSchemas,
32
+ resolveStructuredContentValidation,
33
+ toolInputPolicies,
23
34
  toolOutputPolicies
24
35
  };
@@ -11,6 +11,7 @@ import { InvalidHookFlowError } from "../errors/mcp.error.mjs";
11
11
  import { describeUnreachableEntryClassHooks, unreachableHooksMessage } from "../hooks/entry-class-hooks.mjs";
12
12
  import { normalizeHooksFromCls } from "../hooks/hooks.utils.mjs";
13
13
  import { toolClassHooksJoin } from "./flows/call-tool.flow.mjs";
14
+ import { resolveStructuredContentValidation, toolOutputPolicies } from "./tool-output-policy.mjs";
14
15
  import { buildParsedToolResult } from "./tool.utils.mjs";
15
16
  var looseArgumentsSchema = z.looseObject({});
16
17
  var ToolInstance = class extends ToolEntry {
@@ -140,16 +141,22 @@ var ToolInstance = class extends ToolEntry {
140
141
  */
141
142
  parseOutput(raw, options) {
142
143
  const descriptor = this.outputSchema;
143
- return buildParsedToolResult(descriptor, raw, options);
144
+ return buildParsedToolResult(descriptor, raw, this.withOwnOutputPolicy(options));
144
145
  }
145
146
  safeParseOutput(raw, options) {
146
147
  const descriptor = this.outputSchema;
147
148
  try {
148
- return { success: true, data: buildParsedToolResult(descriptor, raw, options) };
149
+ return { success: true, data: buildParsedToolResult(descriptor, raw, this.withOwnOutputPolicy(options)) };
149
150
  } catch (error) {
150
151
  return { success: false, error };
151
152
  }
152
153
  }
154
+ /** The caller's options, with the tool's own `validateStructuredContent` (Tool > App > server) where it passes none. */
155
+ withOwnOutputPolicy(options = {}) {
156
+ if (options.validateStructuredContent !== void 0) return options;
157
+ const policies = toolOutputPolicies(this, this.scope);
158
+ return { ...options, validateStructuredContent: resolveStructuredContentValidation(...policies) };
159
+ }
153
160
  };
154
161
  var FunctionToolContext = class extends ToolContext {
155
162
  constructor(record, args) {
@@ -14,6 +14,7 @@ import {
14
14
  import { InvalidEntityError, InvalidOutputError } from "../errors/index.mjs";
15
15
  import { isPackageSpecifier, parsePackageSpecifier } from "../esm-loader/package-specifier.mjs";
16
16
  import { toStructuredContent } from "../utils/content.utils.mjs";
17
+ import { resolveStructuredContentValidation } from "./tool-output-policy.mjs";
17
18
  function collectToolMetadata(cls) {
18
19
  const extended = getMetadata(extendedToolMetadata, cls);
19
20
  const seed = extended ? { ...extended } : {};
@@ -91,8 +92,8 @@ function isCallToolResult(value) {
91
92
  return true;
92
93
  }
93
94
  function buildParsedToolResult(descriptor, raw, options = {}) {
94
- if (isCallToolResult(raw)) {
95
- return raw;
95
+ if (isReturnedCallToolResult(descriptor, raw)) {
96
+ return withDeclaredStructuredContent(descriptor, raw, options);
96
97
  }
97
98
  const content = [];
98
99
  let structuredData;
@@ -154,6 +155,87 @@ function buildParsedToolResult(descriptor, raw, options = {}) {
154
155
  }
155
156
  return result;
156
157
  }
158
+ function isReturnedCallToolResult(descriptor, raw) {
159
+ if (!isCallToolResult(raw)) return false;
160
+ if (raw.content.length > 0 || raw.structuredContent !== void 0 || raw.isError) return true;
161
+ return !structuredOutputSchemaOf(descriptor)?.safeParse(raw).success;
162
+ }
163
+ var elicitationFallbacks = /* @__PURE__ */ new WeakSet();
164
+ function asElicitationFallback(answer) {
165
+ elicitationFallbacks.add(answer);
166
+ return answer;
167
+ }
168
+ function withDeclaredStructuredContent(descriptor, result, options) {
169
+ const schema = structuredOutputSchemaOf(descriptor);
170
+ if (!schema || result.isError || elicitationFallbacks.has(result)) return result;
171
+ const { structuredContent } = result;
172
+ const parsed = declaredStructuredContent(schema, structuredContent);
173
+ if ("error" in parsed) {
174
+ if (resolveStructuredContentValidation({ validateStructuredContent: options.validateStructuredContent }) === "enforce") {
175
+ throw parsed.error;
176
+ }
177
+ options.onInvalidStructuredContent?.();
178
+ return result;
179
+ }
180
+ const declared = toStructuredContent(applyUndeclaredKeysPolicy(schema, structuredContent, parsed.declared, options));
181
+ const sent = JSON.parse(JSON.stringify(structuredContent));
182
+ if (isSameJson(declared, sent)) return result;
183
+ const content = result.content.map(
184
+ (block) => block.type === "text" && repeatsJson(block.text, sent) ? { ...block, text: JSON.stringify(declared) } : block
185
+ );
186
+ return { ...result, content, structuredContent: declared };
187
+ }
188
+ function repeatsJson(text, value) {
189
+ try {
190
+ return isSameJson(JSON.parse(text), value);
191
+ } catch {
192
+ return false;
193
+ }
194
+ }
195
+ function isSameJson(left, right) {
196
+ if (left === right) return true;
197
+ if (Array.isArray(left) || Array.isArray(right)) {
198
+ return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((item, index) => isSameJson(item, right[index]));
199
+ }
200
+ if (!isRecord(left) || !isRecord(right)) return false;
201
+ const leftKeys = Object.keys(left);
202
+ return leftKeys.length === Object.keys(right).length && leftKeys.every((key) => Object.prototype.hasOwnProperty.call(right, key) && isSameJson(left[key], right[key]));
203
+ }
204
+ function declaredStructuredContent(schema, structuredContent) {
205
+ if (structuredContent === void 0)
206
+ return { error: new InvalidOutputError({ reason: "missing structuredContent" }) };
207
+ try {
208
+ return { declared: parseDeclaredOutput(schema, structuredContent) };
209
+ } catch (error) {
210
+ return { error: error instanceof InvalidOutputError ? error : new InvalidOutputError() };
211
+ }
212
+ }
213
+ var SHAPE_KEEPING_WRAPPERS = /* @__PURE__ */ new Set([
214
+ "readonly",
215
+ "optional",
216
+ "nullable",
217
+ "default",
218
+ "prefault",
219
+ "nonoptional",
220
+ "catch"
221
+ ]);
222
+ function answersObject(schema, lazies = /* @__PURE__ */ new Set()) {
223
+ const def = schema?._zod?.def;
224
+ if (!def) return false;
225
+ const type = String(def["type"]);
226
+ if (type === "object" || type === "record") return true;
227
+ if (type === "lazy") {
228
+ return !lazies.has(def) && answersObject(def["getter"](), /* @__PURE__ */ new Set([...lazies, def]));
229
+ }
230
+ if (type === "pipe") return answersObject(def["in"], lazies);
231
+ if (type === "union") return def["options"].every((option) => answersObject(option, lazies));
232
+ if (type === "intersection") return answersObject(def["left"], lazies) && answersObject(def["right"], lazies);
233
+ return SHAPE_KEEPING_WRAPPERS.has(type) && answersObject(def["innerType"], lazies);
234
+ }
235
+ function structuredOutputSchemaOf(descriptor) {
236
+ if (descriptor instanceof z.ZodType) return answersObject(descriptor) ? descriptor : void 0;
237
+ return !Array.isArray(descriptor) && isZodRawShape(descriptor) ? z.object(descriptor) : void 0;
238
+ }
157
239
  function parseSingleValue(descriptor, value, options, path) {
158
240
  if (typeof descriptor === "string") {
159
241
  switch (descriptor) {
@@ -240,7 +322,9 @@ function parseSingleValue(descriptor, value, options, path) {
240
322
  };
241
323
  }
242
324
  function parseAgainstOutputSchema(schema, value, options = {}) {
243
- const declared = parseDeclaredOutput(schema, value);
325
+ return applyUndeclaredKeysPolicy(schema, value, parseDeclaredOutput(schema, value), options);
326
+ }
327
+ function applyUndeclaredKeysPolicy(schema, value, declared, options) {
244
328
  const policy = options.undeclaredKeys ?? "strip";
245
329
  if (policy === "strip" || hasTransform(schema)) return declared;
246
330
  const undeclaredKeys = findDroppedKeys(value, declared);
@@ -381,11 +465,14 @@ function buildAgentToolDefinition(tool) {
381
465
  };
382
466
  }
383
467
  export {
468
+ asElicitationFallback,
384
469
  buildAgentToolDefinition,
385
470
  buildAgentToolDefinitions,
386
471
  buildParsedToolResult,
387
472
  collectToolMetadata,
473
+ isCallToolResult,
388
474
  isExternalToolRecord,
475
+ isReturnedCallToolResult,
389
476
  normalizeTool,
390
477
  toolDiscoveryDeps
391
478
  };
@@ -0,0 +1,17 @@
1
+ // libs/sdk/src/tool/ui/app-only-tools.ts
2
+ function isAppOnlyTool(metadata) {
3
+ const ui = metadata._meta?.["ui"];
4
+ const visibility = typeof ui === "object" && ui !== null ? Reflect.get(ui, "visibility") : void 0;
5
+ return Array.isArray(visibility) && !visibility.includes("model");
6
+ }
7
+ function knownPlatformOf(...platforms) {
8
+ return platforms.find((platform) => platform !== void 0 && platform !== "unknown");
9
+ }
10
+ function rendersAppPages(platformType) {
11
+ return platformType === "ext-apps" || platformType === "openai";
12
+ }
13
+ export {
14
+ isAppOnlyTool,
15
+ knownPlatformOf,
16
+ rendersAppPages
17
+ };