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): formulas in chat-built flows no longer show up as missing steps (#16387)
Hazem Adel3edf6dc44770
diff --git a/packages/server/api/src/app/mcp/tools/flow-validation.ts b/packages/server/api/src/app/mcp/tools/flow-validation.tsindex 445d74b903c..c850df30cf5 100644--- a/packages/server/api/src/app/mcp/tools/flow-validation.ts+++ b/packages/server/api/src/app/mcp/tools/flow-validation.ts@@ -1,3 +1,4 @@+import { AP_FUNCTIONS } from '@activepieces/core-formula'import { isNil } from '@activepieces/core-utils'import { BranchExecutionType, flowStructureUtil, FlowTrigger, FlowTriggerType, Step } from '@activepieces/shared'@@ -33,6 +34,10 @@ function validateFlow({ trigger }: { trigger: FlowTrigger }): ValidationResult {}const strings = collectStringValues({ step })+ const bareFunctions = [...new Set(strings.flatMap((value) => findBareFormulaFunctions({ value })))]+ for (const fn of bareFunctions) {+ issues.push({ category: 'template_reference', severity: 'error', stepName: step.name, message: `"${step.displayName}" uses the formula function ${fn}() inside {{ }}, which only holds step references. Write it as ap-formula-v1::{${fn}({{step_1['output'].field}})}::ap-formula-v1, with single braces around the formula.` })+ }const seenRefs = new Set<string>()for (const str of strings) {const refs = extractReferencedStepNames({ value: str })@@ -121,18 +126,32 @@ function walkValues(obj: unknown, fn: (val: unknown) => void): void {}function extractReferencedStepNames({ value }: { value: string }): string[] {- const regex = /\{\{(\w+)/g+ const regex = /\{\{\s*(\w+)\s*(\()?/gconst names = new Set<string>()let matchwhile ((match = regex.exec(value)) !== null) {const name = match[1]- if (name !== 'connections') {+ const isFunctionCall = match[2] !== undefined+ if (name !== 'connections' && !isFunctionCall) {names.add(name)}}return [...names]}+function findBareFormulaFunctions({ value }: { value: string }): string[] {+ const outsideFormulas = value.replace(WRAPPED_FORMULA, '')+ const called = [...outsideFormulas.matchAll(BARE_FUNCTION_CALL)].map((match) => match[1])+ return [...new Set(called.filter((name) => FORMULA_FUNCTION_NAMES.has(comparableFunctionName(name))))]+}++function comparableFunctionName(name: string): string {+ return name.toLowerCase().replace(/_/g, '')+}++const WRAPPED_FORMULA = /ap-formula-v(\d+)::\{[\s\S]*?\}::ap-formula-v\1/g+const BARE_FUNCTION_CALL = /\{\{\s*([A-Za-z_]\w*)\s*\(/g+const FORMULA_FUNCTION_NAMES = new Set(AP_FUNCTIONS.map((fn) => comparableFunctionName(fn.name)))const CATEGORY_ORDER: ValidationIssue['category'][] = ['step_validity', 'template_reference', 'empty_branch']const CATEGORY_LABELS: Record<ValidationIssue['category'], string> = {step_validity: 'Step Validity',diff --git a/packages/server/api/src/app/mcp/tools/mcp-utils.ts b/packages/server/api/src/app/mcp/tools/mcp-utils.tsindex 1082f09fb07..38aadc29b93 100644--- a/packages/server/api/src/app/mcp/tools/mcp-utils.ts+++ b/packages/server/api/src/app/mcp/tools/mcp-utils.ts@@ -1,4 +1,4 @@-import { isNil, isObject, tryCatch } from '@activepieces/core-utils'+import { applyFunctionToValuesSync, 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, PropertyExecutionType, PropertySettings, singleValueConditions, WorkerJobType } from '@activepieces/shared'import type { BranchedAction, Step } from '@activepieces/shared'@@ -636,12 +636,16 @@ function rewriteAllReferences<C = unknown>({ input, loopItems, conditions, trigg}): { input?: Record<string, unknown>, loopItems?: string, conditions?: C } {const stepNames = flowStructureUtil.getAllSteps(trigger).map(s => s.name)return {- input: input ? expressionRewriter.rewriteDeep(input, stepNames, true) : undefined,- loopItems: loopItems != null ? expressionRewriter.rewriteStepReferences({ input: loopItems, stepNames, idempotent: true }) : loopItems,- conditions: conditions ? expressionRewriter.rewriteDeep(conditions, stepNames, true) : conditions,+ input: input ? expressionRewriter.rewriteDeep(applyFunctionToValuesSync<Record<string, unknown>>(input, normalizeFormulaText), stepNames, true) : undefined,+ loopItems: loopItems != null ? expressionRewriter.rewriteStepReferences({ input: normalizeFormulaText(loopItems), stepNames, idempotent: true }) : loopItems,+ conditions: conditions ? expressionRewriter.rewriteDeep(applyFunctionToValuesSync<C>(conditions, normalizeFormulaText), stepNames, true) : conditions,}}+function normalizeFormulaText(text: string): string {+ return text.replace(DOUBLE_BRACED_FORMULA, (_match, version: string, expression: string) => `ap-formula-v${version}::{${expression}}::ap-formula-v${version}`)+}+function extractOptionsArray(options: unknown): Array<{ label: string, value: unknown }> | null {if (Array.isArray(options)) return options@@ -656,6 +660,7 @@ function extractOptionsArray(options: unknown): Array<{ label: string, value: un}const RESOLVE_TIMEOUT_MS = 30_000+const DOUBLE_BRACED_FORMULA = /ap-formula-v(\d+)::\{\{\s*([A-Za-z_]\w*\s*\([\s\S]*?\))\s*\}\}::ap-formula-v\1/gconst FOLDER_NAME_SCHEMA = z.string().trim().min(1).max(255).optional().describe('Name of an existing folder to place it in. For a solution of several flows and tables, create the folder with ap_create_folder in an earlier step than the calls that use it (never in the same step, they run at once), then pass the same folderName to each of them.')@@ -853,6 +858,7 @@ export const mcpUtils = {publishedFlowWarning,diagnosePieceProps,coerceEmptyContainerInputs,+ normalizeFormulaText,detectUnknownInputProps,rejectUnknownInputProps,dropUnknownInputProps,diff --git a/packages/server/api/test/unit/app/mcp/flow-validation.test.ts b/packages/server/api/test/unit/app/mcp/flow-validation.test.tsnew file mode 100644index 00000000000..40d6e526157--- /dev/null+++ b/packages/server/api/test/unit/app/mcp/flow-validation.test.ts@@ -0,0 +1,56 @@+import { FlowActionType, FlowTrigger, FlowTriggerType } from '@activepieces/shared'+import { describe, expect, it } from 'vitest'+import { flowValidation } from '../../../../src/app/mcp/tools/flow-validation'++describe('flowValidation.validateFlow — formulas', () => {+ it('does not read a formula function as a missing step', () => {+ const result = flowValidation.validateFlow({ trigger: flowWithInput({ text: 'ap-formula-v1::{count({{trigger[\'output\'].rows}})}::ap-formula-v1' }) })++ expect(result.issues).toEqual([])+ })++ it('names a formula function written inside {{ }} and shows the right syntax', () => {+ const result = flowValidation.validateFlow({ trigger: flowWithInput({ text: 'Total: {{length(trigger[\'output\'].rows)}}' }) })++ expect(result.issues).toHaveLength(1)+ expect(result.issues[0].message).toContain('length()')+ expect(result.issues[0].message).toContain('ap-formula-v1::{length(')+ })++ it('accepts a JavaScript helper the engine runs inside {{ }}', () => {+ const result = flowValidation.validateFlow({ trigger: flowWithInput({ text: "{{ flattenNestedKeys(trigger['output'], ['users', 'name']) }}" }) })++ expect(result.issues).toEqual([])+ })++ it('names a camelCase formula function written inside {{ }}', () => {+ const result = flowValidation.validateFlow({ trigger: flowWithInput({ text: '{{formatDate(now(); "YYYY")}}' }) })++ expect(result.issues.map((issue) => issue.message)).toEqual([expect.stringContaining('formatDate()')])+ })++ it('still flags a reference to a step that does not exist', () => {+ const result = flowValidation.validateFlow({ trigger: flowWithInput({ text: '{{step_9[\'output\'].id}}' }) })++ expect(result.issues.map((issue) => issue.message)).toEqual([expect.stringContaining('does not exist')])+ })+})++function flowWithInput(input: Record<string, unknown>): FlowTrigger {+ return {+ name: 'trigger',+ valid: true,+ displayName: 'Catch Webhook',+ lastUpdatedDate: '2024-01-01T00:00:00Z',+ type: FlowTriggerType.PIECE,+ settings: { pieceName: '@activepieces/piece-webhook', pieceVersion: '~0.1.0', triggerName: 'catch_webhook', input: {}, propertySettings: {} },+ nextAction: {+ name: 'step_1',+ valid: true,+ displayName: 'Send Email',+ lastUpdatedDate: '2024-01-01T00:00:00Z',+ type: FlowActionType.PIECE,+ settings: { pieceName: '@activepieces/piece-gmail', pieceVersion: '~0.1.0', actionName: 'send_email', input, propertySettings: {} },+ },+ }+}diff --git a/packages/server/api/test/unit/app/mcp/mcp-utils.test.ts b/packages/server/api/test/unit/app/mcp/mcp-utils.test.tsindex a8b3e025cd5..8466373a3f4 100644--- a/packages/server/api/test/unit/app/mcp/mcp-utils.test.ts+++ b/packages/server/api/test/unit/app/mcp/mcp-utils.test.ts@@ -508,3 +508,26 @@ describe('mcpUtils.resolveRouterStep', () => {expect(text && 'text' in text ? text.text : '').toContain('ai_router')})})++describe('mcpUtils.normalizeFormulaText — double braces around a formula', () => {+ it('turns ap-formula-v1::{{fn(...)}}::ap-formula-v1 into single braces and keeps the references inside', () => {+ const fixed = mcpUtils.normalizeFormulaText('ap-formula-v1::{{formatDate(addDays(now(); -7); "YYYY-MM-DD")}}::ap-formula-v1')++ expect(fixed).toBe('ap-formula-v1::{formatDate(addDays(now(); -7); "YYYY-MM-DD")}::ap-formula-v1')+ })++ it('fixes double braces in router conditions too', () => {+ const trigger: EmptyTrigger = { name: 'trigger', displayName: 'Trigger', type: FlowTriggerType.EMPTY, valid: false, lastUpdatedDate: '2026-10-11T00:00:00.000Z', settings: {} }+ const conditions = [[{ firstValue: 'ap-formula-v1::{{count(1; 2)}}::ap-formula-v1' }]]++ const rewritten = mcpUtils.rewriteAllReferences({ conditions, trigger })++ expect(rewritten.conditions).toEqual([[{ firstValue: 'ap-formula-v1::{count(1; 2)}::ap-formula-v1' }]])+ })++ it('leaves a correct formula and a plain reference untouched', () => {+ const correct = 'ap-formula-v1::{count({{step_1[\'output\'].rows}})}::ap-formula-v1 and {{step_1[\'output\'].id}}'++ expect(mcpUtils.normalizeFormulaText(correct)).toBe(correct)+ })+})