AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
fix(chat): chat-built steps run their dynamic fields with real values (#16120)
Hazem Adelfe3c86081b9a
diff --git a/brain/knowledge/flows-execution/chat.md b/brain/knowledge/flows-execution/chat.mdindex 0e5a124d2bd..819cff57e11 100644--- a/brain/knowledge/flows-execution/chat.md+++ b/brain/knowledge/flows-execution/chat.md@@ -53,6 +53,7 @@ A turn is kept alive / reclaimed by three separate mechanisms in `execute-agent-- **The context budget subtracts what the request reserves.** Anthropic/OpenRouter count tool schemas and the reserved `max_tokens` against the 200k window, so `getAgentConfig` passes `reservedTokens` (the clamped output window from `agentAiUtils.affordableOutputTokens`, the same helper the worker uses for `maxOutputTokens`, plus `TOOL_SCHEMA_TOKEN_ESTIMATE = 12_000`) into `agentCompaction`. The threshold, the fit check and the recent window are all measured against `maxContext - reservedTokens`, and the recent window is sized by estimated tokens, not message count. The tool-schema figure is a constant because the tools are built in the worker and the API never sees their definitions. The worker sets `maxOutputTokens` per step in `prepareStep`, so a thinking-disabled step (round one, discovery phase) does not reserve `thinkingBudget`. The system prompt's size is added to the reserve for the window and fit check, and each message is capped at 20k chars in the summary request so the summarizer itself cannot overflow.- **A write tool in `BUILD_ONLY_TOOL_NAMES` is only reachable if something flips the phase for it.** The denylist is the consistent home for anything that writes (`ap_create_flow`, `ap_create_table`, `ap_lock_and_publish` are all in it), but the only route out of `discovery` is `ap_set_phase`, whose description tells the model to switch when it starts *building an automation*. A tool for a subject with no build guide and no sibling build-only call, the agent-building tools being the case that found this, becomes invisible in any conversation that never builds a flow: `activeToolsForPhase` filters it out and the prompt names no tool, so the model cannot discover that it exists. Classifying by "does it write" is not enough; check what would actually flip the phase in a conversation about *that* subject. The four agent *write* tools (`ap_create_agent`, `ap_update_agent`, `ap_add_agent_tool`, `ap_remove_agent_tool`) were added to the set and then reverted for exactly this, with a test pinning the choice; `ap_list_agents` is a read and was never in it, so the group is five tools and only four were ever candidates.- **Read-only checks don't belong in `BUILD_ONLY_TOOL_NAMES`.** `ap_validate_flow` was in it, so "check that this solution fits together" never saw the tool. The agent inspected flows by hand instead and misread a Call Flow `flowId` (an externalId) as a mismatch with the flow's id. It now stays visible in discovery, like `ap_flow_structure`.+- **A dynamic property only runs with a saved schema.** The engine processes a `DYNAMIC` prop's sub-fields (JSON parse, numbers, arrays) only from `propertySettings[prop].schema`, which the builder saves when it resolves the prop. Chat tools used to save `propertySettings: {}`, so an advanced-mode Call Flow payload reached the subflow as one string and a live run saved empty fields. `mcpUtils.resolveDynamicPropertySettings` now resolves and saves it on build, add and update.- **Capability notes are built where `discoveryOnly` is not known, so a prompt can promise tools the worker has stripped.** `getAgentConfig` composes the system prompt in the api, while `discoveryOnly` rides on the job data; before Aug 2026 it never crossed that boundary. Meanwhile the worker strips image tools, email tools and the agent tools on such a run, so the notes claimed all three. Two of the three had been wrong since long before anyone noticed, because each note computed its own availability term. The flag now travels with the config request and the three notes read one shared `actingRun = !dryRun && !discoveryOnly`. Whenever a tool group is gated on a run mode in the worker, the note that advertises it has to be gated on the same term, in one place.- **Tool output can't be trusted to waive a charge.** A user's own MCP server or `ap_run_code` controls its output's top-level keys, and they reach the persisted part unchanged. Chat billing only honours `billedAtCost` from `ap_web_search` and `ap_generate_image`; a new built-in tool that bills at cost must be added to `TOOLS_THAT_BILL_AT_COST` in `chatBilling`.- **Credits are checked after every step, not just before the turn.** `runAgentTurn` asks the API (`agentHasCredits`) after each tool step, sending what the turn has used so far (`chatBilling.creditsForTurn`, the same rule end-of-turn billing uses), and stops once the remaining balance no longer covers it. Flat credits are only charged when the turn ends, so without that pending count the balance never moves mid-turn. The check fails open if the RPC errors.diff --git a/packages/server/api/src/app/mcp/tools/ap-add-step.ts b/packages/server/api/src/app/mcp/tools/ap-add-step.tsindex b4e9f3e29b2..bb5cd6d314e 100644--- a/packages/server/api/src/app/mcp/tools/ap-add-step.ts+++ b/packages/server/api/src/app/mcp/tools/ap-add-step.ts@@ -119,6 +119,7 @@ export const apAddStepTool = ({ mcp, userId }: McpToolContext, log: FastifyBaseLif (unknownPropsError) {return unknownPropsError}+ pieceSettings.propertySettings = await mcpUtils.resolveDynamicPropertySettings({ pieceName: versionResult.normalizedPieceName, pieceVersion: versionResult.pieceVersion, componentName: actionName, componentType: 'action', input: resolvedInput, projectId: mcp.projectId, platformId: project.platformId, log })}}skeletonAction = {diff --git a/packages/server/api/src/app/mcp/tools/ap-build-flow.ts b/packages/server/api/src/app/mcp/tools/ap-build-flow.tsindex 8767bcfb1fe..e960735e45a 100644--- a/packages/server/api/src/app/mcp/tools/ap-build-flow.ts+++ b/packages/server/api/src/app/mcp/tools/ap-build-flow.ts@@ -113,7 +113,7 @@ export const apBuildFlowTool = ({ mcp, userId }: McpToolContext, log: FastifyBaspieceVersion: triggerVersionResult.pieceVersion,triggerName: trigger.triggerName,input: triggerInput,- propertySettings: {},+ propertySettings: await mcpUtils.resolveDynamicPropertySettings({ pieceName: triggerVersionResult.normalizedPieceName, pieceVersion: triggerVersionResult.pieceVersion, componentName: trigger.triggerName, componentType: 'trigger', input: triggerInput, projectId, platformId, log }),},})let currentFlow = await flowService(log).update({@@ -152,7 +152,8 @@ export const apBuildFlowTool = ({ mcp, userId }: McpToolContext, log: FastifyBasconst stepUnknown = await knownStepInput({ step, pieceName: resolvedPieceName, pieceVersion: resolvedPieceVersion, platformId, log })const rewritten = mcpUtils.rewriteAllReferences({ input: stepUnknown.input, loopItems: step.loopItems, trigger: latestTrigger })const rewrittenStep = { ...step, input: rewritten.input, loopItems: rewritten.loopItems }- const skeleton = buildSkeleton({ step: rewrittenStep, name: stepName, resolvedPieceVersion, resolvedPieceName })+ const propertySettings = await stepPropertySettings({ actionName: step.actionName, pieceName: resolvedPieceName, pieceVersion: resolvedPieceVersion, input: { ...(rewritten.input ?? {}), ...(step.auth ? { auth: `{{connections['${step.auth}']}}` } : {}) }, projectId, platformId, log })+ const skeleton = buildSkeleton({ step: rewrittenStep, name: stepName, resolvedPieceVersion, resolvedPieceName, propertySettings })const parseResult = UpdateActionRequest.safeParse(skeleton)if (!parseResult.success) {skippedSteps.push(step.displayName)@@ -227,6 +228,22 @@ export const apBuildFlowTool = ({ mcp, userId }: McpToolContext, log: FastifyBas}}+async function stepPropertySettings({ actionName, pieceName, pieceVersion, input, projectId, platformId, log }: {+ actionName: string | undefined+ pieceName: string | undefined+ pieceVersion: string | undefined+ input: Record<string, unknown>+ projectId: string+ platformId: string+ log: FastifyBaseLogger+}): Promise<Record<string, unknown>> {+ const isPieceAction = !isNil(pieceName) && !isNil(pieceVersion) && !isNil(actionName)+ if (!isPieceAction) {+ return {}+ }+ return mcpUtils.resolveDynamicPropertySettings({ pieceName, pieceVersion, componentName: actionName, componentType: 'action', input, projectId, platformId, log })+}+async function knownStepInput({ step, pieceName, pieceVersion, platformId, log }: {step: z.infer<typeof stepSpec>pieceName: string | undefined@@ -242,11 +259,12 @@ async function knownStepInput({ step, pieceName, pieceVersion, platformId, log }return mcpUtils.dropUnknownInputProps({ pieceName, pieceVersion, componentName: actionName, componentType: 'action', input: step.input, platformId, log })}-function buildSkeleton({ step, name, resolvedPieceVersion, resolvedPieceName }: {+function buildSkeleton({ step, name, resolvedPieceVersion, resolvedPieceName, propertySettings }: {step: z.infer<typeof stepSpec>name: stringresolvedPieceVersion?: stringresolvedPieceName?: string+ propertySettings: Record<string, unknown>}): Record<string, unknown> {const resolvedInput = {...(step.input ?? {}),@@ -281,7 +299,7 @@ function buildSkeleton({ step, name, resolvedPieceVersion, resolvedPieceName }:pieceVersion: resolvedPieceVersion ?? '',actionName: step.actionName ?? '',input: resolvedInput,- propertySettings: {},+ propertySettings,errorHandlingOptions: mcpUtils.buildErrorHandlingOptions({ continueOnFailure: step.continueOnFailure, retryOnFailure: step.retryOnFailure }),},}diff --git a/packages/server/api/src/app/mcp/tools/ap-update-step.ts b/packages/server/api/src/app/mcp/tools/ap-update-step.tsindex 3a5fbbb473d..dfe58ad7761 100644--- a/packages/server/api/src/app/mcp/tools/ap-update-step.ts+++ b/packages/server/api/src/app/mcp/tools/ap-update-step.ts@@ -144,6 +144,7 @@ export const apUpdateStepTool = ({ mcp, userId }: McpToolContext, log: FastifyBareturn unknownPropsError}updatedSettings.input = knownInput+ updatedSettings.propertySettings = await mcpUtils.resolveDynamicPropertySettings({ pieceName, pieceVersion, componentName: resolvedActionName, componentType: 'action', input: knownInput, propertySettings: currentSettings.propertySettings, changedKeys: Object.keys(callerInput), projectId: mcp.projectId, platformId: project.platformId, log })}}diff --git a/packages/server/api/src/app/mcp/tools/ap-update-trigger.ts b/packages/server/api/src/app/mcp/tools/ap-update-trigger.tsindex a05c75b06f0..9083368c4b1 100644--- a/packages/server/api/src/app/mcp/tools/ap-update-trigger.ts+++ b/packages/server/api/src/app/mcp/tools/ap-update-trigger.ts@@ -84,7 +84,7 @@ export const apUpdateTriggerTool = ({ mcp, userId }: McpToolContext, log: FastifpieceVersion,triggerName,input,- propertySettings: existingPieceSettings?.propertySettings ?? {},+ propertySettings: await mcpUtils.resolveDynamicPropertySettings({ pieceName: resolvedPieceName, pieceVersion, componentName: triggerName, componentType: 'trigger', input, propertySettings: existingPieceSettings?.propertySettings, changedKeys: existingPieceSettings?.pieceVersion === pieceVersion ? Object.keys(callerInput) : Object.keys(input), projectId: mcp.projectId, platformId: project.platformId, log }),},}diff --git a/packages/server/api/src/app/mcp/tools/mcp-utils.ts b/packages/server/api/src/app/mcp/tools/mcp-utils.tsindex a982f874ff1..21358dff172 100644--- a/packages/server/api/src/app/mcp/tools/mcp-utils.ts+++ b/packages/server/api/src/app/mcp/tools/mcp-utils.ts@@ -1,6 +1,6 @@import { isNil, isObject, tryCatch } from '@activepieces/core-utils'import { AiMetadata, OutputSchema, OutputSchemaField, PieceMetadataModel, PiecePropertyMap, PropertyType } from '@activepieces/pieces-framework'-import { BranchOperator, EngineResponse, EngineResponseStatus, flowStructureUtil, McpServerType, McpToolResult, ProjectScopedMcpServer, singleValueConditions, WorkerJobType } from '@activepieces/shared'+import { BranchOperator, EngineResponse, EngineResponseStatus, flowStructureUtil, McpServerType, McpToolResult, ProjectScopedMcpServer, PropertyExecutionType, PropertySettings, singleValueConditions, WorkerJobType } from '@activepieces/shared'import type { BranchedAction, Step } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'import { z } from 'zod'@@ -714,6 +714,38 @@ async function executePropertyResolution({ pieceName, pieceVersion, actionOrTrigreturn { status: 'failed', message: 'Unrecognized options format' }}+async function resolveDynamicPropertySettings({ pieceName, pieceVersion, componentName, componentType, input, propertySettings, changedKeys = [], projectId, platformId, log }: {+ pieceName: string+ pieceVersion: string+ componentName: string+ componentType: 'action' | 'trigger'+ input: Record<string, unknown>+ propertySettings?: unknown+ changedKeys?: string[]+ projectId: string+ platformId: string+ log: FastifyBaseLogger+}): Promise<Record<string, PropertySettings>> {+ const current = z.record(z.string(), PropertySettings).safeParse(propertySettings).data ?? {}+ const { data: piece } = await tryCatch(() => pieceMetadataService(log).getOrThrow({ platformId, name: pieceName, version: pieceVersion }))+ const component = isNil(piece) ? undefined : (componentType === 'action' ? piece.actions[componentName] : piece.triggers[componentName])+ if (isNil(component)) {+ return current+ }+ const needingSchema = Object.entries(component.props).filter(([name, prop]) => {+ const watchedKeys = [name, ...('refreshers' in prop ? prop.refreshers : [])]+ const needsSchema = isNil(current[name]?.schema) || watchedKeys.some((key) => changedKeys.includes(key))+ return prop.type === PropertyType.DYNAMIC && !isNil(input[name]) && needsSchema+ })+ const refreshed = await Promise.all(needingSchema.map(async ([name]) => {+ const type = current[name]?.type ?? PropertyExecutionType.MANUAL+ const { data: result } = await tryCatch(() => executePropertyResolution({ pieceName, pieceVersion, actionOrTriggerName: componentName, propertyName: name, input, projectId, platformId, log }))+ const settings: PropertySettings = result?.status === 'dynamic' ? { type, schema: result.props } : { type }+ return [name, settings] as const+ }))+ return { ...current, ...Object.fromEntries(refreshed) }+}+// Classify an action by how many records it returns, from its name. This is the signal the agent// lacks today: it reaches for find_record (one match) when it meant to enumerate, then thrashes on// the empty result. 'enumerate' = list/search/plural-find; 'single' = find/get one; 'other' = a write@@ -847,6 +879,7 @@ export const mcpUtils = {rewriteAllReferences,extractOptionsArray,executePropertyResolution,+ resolveDynamicPropertySettings,RESOLVE_TIMEOUT_MS,STEP_REFERENCE_HINT,BRANCH_CONDITIONS_INPUT_SCHEMA,diff --git a/packages/server/api/src/assets/prompts/guides/build_flow.md b/packages/server/api/src/assets/prompts/guides/build_flow.mdindex ba609f17046..b9e0a25207f 100644--- a/packages/server/api/src/assets/prompts/guides/build_flow.md+++ b/packages/server/api/src/assets/prompts/guides/build_flow.md@@ -50,7 +50,7 @@ How to build one:2. **Names:** name each flow for its one job, in plain words ("Save order", not "Flow 2" or "Order flow helper").3. **Order:** tables first, then subflows, then the flows that call them. Each step needs an id the previous one returned.4. **Subflow:** trigger `@activepieces/piece-subflows` `callableFlow`, with `exampleData.sampleData` listing every input it takes, e.g. `{"orderId": "123", "email": "[email protected]"}`. Its steps read each input as `{{trigger['output'].data.<key>}}`, never `{{trigger['output'].<key>}}` (that is empty at run time). Add a `returnResponse` step only if a caller needs data back.-5. **Caller:** a `callFlow` step with `flowId` set to the subflow's **externalId** (the one `ap_build_flow` returned, not its flow id). Use `mode: "simple"` and send every key of the subflow's sample data in `flowProps.payload` as an object; a JSON-text payload arrives in the subflow as one string. Set `waitForResponse` only when the subflow has a Return Response step.+5. **Caller:** a `callFlow` step with `flowId` set to the subflow's **externalId** (the one `ap_build_flow` returned, not its flow id). Use `mode: "simple"` and send every key of the subflow's sample data in `flowProps.payload` as an object. Set `waitForResponse` only when the subflow has a Return Response step.6. **Tables steps:** `table_id` is the table's **externalId**. Form `values` are keyed by field externalId.7. **Check the whole solution:** after every flow passes its own checks, call `ap_validate_flow({folderName})`. Fix each issue it lists and run it again until it returns ✅. Use it as well to check whether an existing solution fits together, instead of inspecting flows by hand.8. **Build card:** one card for the whole solution. `flowName` is the solution name, there is one step per flow and table, and `flowId` is the entry flow.diff --git a/packages/server/api/test/integration/ce/mcp/mcp-tools.test.ts b/packages/server/api/test/integration/ce/mcp/mcp-tools.test.tsindex 115ee43a2b8..c0e7146d177 100644--- a/packages/server/api/test/integration/ce/mcp/mcp-tools.test.ts+++ b/packages/server/api/test/integration/ce/mcp/mcp-tools.test.ts@@ -1,8 +1,8 @@-import { apId } from '@activepieces/core-utils'-import { FlowActionType, FlowCreatorType, FlowOperationType, FlowRunStatus, flowStructureUtil, FlowTriggerType, McpServerType, PackageType, PieceType, ProjectScopedMcpServer, RunEnvironment, StepLocationRelativeToParent } from '@activepieces/shared'+import { apId, isObject } from '@activepieces/core-utils'+import { EngineResponseStatus, FlowActionType, FlowCreatorType, FlowOperationType, FlowRunStatus, flowStructureUtil, FlowTriggerType, McpServerType, PackageType, PieceType, ProjectScopedMcpServer, RunEnvironment, StepLocationRelativeToParent } from '@activepieces/shared'import { FastifyBaseLogger, FastifyInstance } from 'fastify'import { StatusCodes } from 'http-status-codes'-import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'import { z } from 'zod'import { flowService } from '../../../../src/app/flows/flow/flow.service'import { flowFolderService } from '../../../../src/app/flows/folder/folder.service'@@ -34,6 +34,7 @@ import { apReadStepSettingsTool } from '../../../../src/app/mcp/tools/ap-read-stimport { apRunActionTool } from '../../../../src/app/mcp/tools/ap-run-action'import { mcpUtils } from '../../../../src/app/mcp/tools/mcp-utils'import { tableService } from '../../../../src/app/tables/table/table.service'+import { userInteractionWatcher } from '../../../../src/app/workers/user-interaction-watcher'import { db } from '../../../helpers/db'import { createMockPieceMetadata } from '../../../helpers/mocks'import { createTestContext } from '../../../helpers/test-context'@@ -56,6 +57,17 @@ beforeAll(async () => {packageType: PackageType.REGISTRY,platformId: undefined,actions: {+ send_template: {+ name: 'send_template',+ displayName: 'Send Template',+ description: 'Send an email from a template',+ requireAuth: false,+ props: {+ template: { type: 'SHORT_TEXT', displayName: 'Template', required: true },+ note: { type: 'SHORT_TEXT', displayName: 'Note', required: false },+ fields: { type: 'DYNAMIC', displayName: 'Fields', required: true, refreshers: ['template'] },+ },+ },send_email: {name: 'send_email',displayName: 'Send Email',@@ -79,6 +91,16 @@ beforeAll(async () => {label: { type: 'SHORT_TEXT', displayName: 'Label', required: false },},},+ new_templated_email: {+ name: 'new_templated_email',+ displayName: 'New Templated Email',+ description: 'Triggers on new email matching a template',+ requireAuth: false,+ props: {+ template: { type: 'SHORT_TEXT', displayName: 'Template', required: true },+ fields: { type: 'DYNAMIC', displayName: 'Fields', required: true, refreshers: ['template'] },+ },+ },new_labeled_email: {name: 'new_labeled_email',displayName: 'New Labeled Email',@@ -99,6 +121,7 @@ beforeAll(async () => {},})await db.save('piece_metadata', gmailPiece)+ await db.save('piece_metadata', { ...gmailPiece, id: apId(), version: '0.0.9' })const arrayPiece = createMockPieceMetadata({name: '@activepieces/piece-test-array',@@ -2813,4 +2836,106 @@ describe('MCP Tools integration', () => {expect(text(triggerUpdate)).not.toContain('Unknown properties')expect(updatedFlow.version.trigger.settings.input).toEqual({ folder: 'INBOX', label: 'urgent' })})++ it('ap_add_step and ap_update_step save the schema of a dynamic property, so the engine can process its fields', async () => {+ const ctx = await createTestContext(app)+ const mcp = makeMcp(ctx.project.id)+ const schema = { count: { type: 'NUMBER', displayName: 'Count', required: false } }+ const resolve = vi.spyOn(userInteractionWatcher, 'submitAndWaitForResponse').mockResolvedValue({ status: EngineResponseStatus.OK, response: { options: schema } })+ const flowId = await createFlowAndGetId(mcp, 'Dynamic schema')+ await apUpdateTriggerTool({ mcp }, mockLog).execute({ flowId, pieceName: '@activepieces/piece-test-email', triggerName: 'new_email' })++ await apAddStepTool({ mcp }, mockLog).execute({+ flowId, parentStepName: 'trigger', stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER, stepType: FlowActionType.PIECE, displayName: 'Send',+ pieceName: '@activepieces/piece-test-email', actionName: 'send_template', input: { template: 'welcome', fields: { count: '3' } },+ })+ const afterAdd = resolve.mock.calls.length+ await apUpdateStepTool({ mcp }, mockLog).execute({ flowId, stepName: 'step_1', input: { note: 'unrelated' } })+ const afterUnrelatedEdit = resolve.mock.calls.length+ await apUpdateStepTool({ mcp }, mockLog).execute({ flowId, stepName: 'step_1', input: { template: 'reminder' } })+ const afterRefresherEdit = resolve.mock.calls.length+ resolve.mockRestore()+ const flow = await flowService(mockLog).getOnePopulatedOrThrow({ id: flowId, projectId: ctx.project.id })++ expect(afterAdd).toBe(1)+ expect(afterUnrelatedEdit).toBe(1)+ expect(afterRefresherEdit).toBe(2)+ expect(flowStructureUtil.getStepOrThrow('step_1', flow.version.trigger).settings.propertySettings).toMatchObject({ fields: { type: 'MANUAL', schema } })+ })++ it('ap_add_step still saves the step when the dynamic property schema cannot be resolved', async () => {+ const ctx = await createTestContext(app)+ const mcp = makeMcp(ctx.project.id)+ const resolve = vi.spyOn(userInteractionWatcher, 'submitAndWaitForResponse').mockRejectedValue(new Error('no worker'))+ const flowId = await createFlowAndGetId(mcp, 'Dynamic schema failure')+ await apUpdateTriggerTool({ mcp }, mockLog).execute({ flowId, pieceName: '@activepieces/piece-test-email', triggerName: 'new_email' })++ const added = await apAddStepTool({ mcp }, mockLog).execute({+ flowId, parentStepName: 'trigger', stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER, stepType: FlowActionType.PIECE, displayName: 'Send',+ pieceName: '@activepieces/piece-test-email', actionName: 'send_template', input: { template: 'welcome', fields: { count: '3' } },+ })+ resolve.mockRestore()+ const flow = await flowService(mockLog).getOnePopulatedOrThrow({ id: flowId, projectId: ctx.project.id })++ expect(text(added)).toContain('✅')+ expect(flowStructureUtil.getStepOrThrow('step_1', flow.version.trigger).settings.propertySettings?.fields?.schema).toBeUndefined()+ })++ it('ap_build_flow and ap_update_trigger save a dynamic trigger schema, and a failed refresh drops the stale one', async () => {+ const ctx = await createTestContext(app)+ const mcp = makeMcp(ctx.project.id)+ const schema = { count: { type: 'NUMBER', displayName: 'Count', required: false } }+ const resolve = vi.spyOn(userInteractionWatcher, 'submitAndWaitForResponse').mockResolvedValue({ status: EngineResponseStatus.OK, response: { options: schema } })++ const built = await apBuildFlowTool({ mcp }, mockLog).execute({+ flowName: 'Dynamic trigger',+ trigger: { pieceName: '@activepieces/piece-test-email', triggerName: 'new_templated_email', input: { template: 'welcome', fields: { count: '3' } } },+ steps: [{ type: FlowActionType.PIECE, displayName: 'Send', pieceName: '@activepieces/piece-test-email', actionName: 'send_template', auth: 'my-connection', input: { template: 'welcome', fields: { count: '1' } } }],+ })+ const { flowId } = structured({ result: built, schema: z.object({ flowId: z.string() }) })+ const builtFlow = await flowService(mockLog).getOnePopulatedOrThrow({ id: flowId, projectId: ctx.project.id })+ const stepResolveInput = resolve.mock.calls.map(([request]) => request).find((request) => isObject(request) && request.actionOrTriggerName === 'send_template')++ await apUpdateTriggerTool({ mcp }, mockLog).execute({ flowId, pieceName: '@activepieces/piece-test-email', triggerName: 'new_templated_email', input: { template: 'reminder' } })+ const afterRefresh = await flowService(mockLog).getOnePopulatedOrThrow({ id: flowId, projectId: ctx.project.id })+ resolve.mockRejectedValue(new Error('no worker'))+ await apUpdateTriggerTool({ mcp }, mockLog).execute({ flowId, pieceName: '@activepieces/piece-test-email', triggerName: 'new_templated_email', input: { template: 'digest' } })+ resolve.mockRestore()+ const afterFailedRefresh = await flowService(mockLog).getOnePopulatedOrThrow({ id: flowId, projectId: ctx.project.id })++ expect(builtFlow.version.trigger.settings.propertySettings).toMatchObject({ fields: { schema } })+ expect(stepResolveInput).toMatchObject({ input: { auth: "{{connections['my-connection']}}" } })+ expect(afterRefresh.version.trigger.settings.propertySettings).toMatchObject({ fields: { schema } })+ expect(afterFailedRefresh.version.trigger.settings.propertySettings?.fields).toEqual({ type: 'MANUAL' })+ })++ it('ap_update_trigger re-resolves a dynamic trigger schema when it moves the trigger to a newer piece version', async () => {+ const ctx = await createTestContext(app)+ const mcp = makeMcp(ctx.project.id)+ const oldSchema = { count: { type: 'SHORT_TEXT', displayName: 'Count', required: false } }+ const newSchema = { count: { type: 'NUMBER', displayName: 'Count', required: false } }+ const flowId = await createFlowAndGetId(mcp, 'Version upgrade')+ const flow = await flowService(mockLog).getOnePopulatedOrThrow({ id: flowId, projectId: ctx.project.id })+ await flowService(mockLog).update({+ id: flowId, projectId: ctx.project.id, userId: null, platformId: ctx.platform.id,+ operation: {+ type: FlowOperationType.UPDATE_TRIGGER,+ request: {+ name: flow.version.trigger.name,+ displayName: 'New Templated Email',+ valid: false,+ type: FlowTriggerType.PIECE,+ settings: { pieceName: '@activepieces/piece-test-email', pieceVersion: '0.0.9', triggerName: 'new_templated_email', input: { template: 'welcome', fields: { count: '3' } }, propertySettings: { fields: { type: 'MANUAL', schema: oldSchema } } },+ },+ },+ })+ const resolve = vi.spyOn(userInteractionWatcher, 'submitAndWaitForResponse').mockResolvedValue({ status: EngineResponseStatus.OK, response: { options: newSchema } })++ await apUpdateTriggerTool({ mcp }, mockLog).execute({ flowId, pieceName: '@activepieces/piece-test-email', triggerName: 'new_templated_email', displayName: 'Renamed' })+ resolve.mockRestore()+ const updated = await flowService(mockLog).getOnePopulatedOrThrow({ id: flowId, projectId: ctx.project.id })++ expect(updated.version.trigger.settings.pieceVersion).toBe('0.1.0')+ expect(updated.version.trigger.settings.propertySettings).toMatchObject({ fields: { type: 'MANUAL', schema: newSchema } })+ })})