Skip to content

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

fix(chat): a new flow says why each step is invalid (#16388)

Hazem Adelc660dcb96995
diff --git a/packages/server/api/src/app/flows/flow-version/flow-version-validator-util.ts b/packages/server/api/src/app/flows/flow-version/flow-version-validator-util.ts
index 08c7530708c..d5229d01cea 100644
--- a/packages/server/api/src/app/flows/flow-version/flow-version-validator-util.ts
+++ b/packages/server/api/src/app/flows/flow-version/flow-version-validator-util.ts
@@ -1,10 +1,10 @@
-import { ActivepiecesError, ErrorCode, isNil, PlatformId, STEP_NAME_REGEX, UserId } from '@activepieces/core-utils'
+import { ActivepiecesError, ErrorCode, isNil, PlatformId, STEP_NAME_REGEX, unique, UserId } from '@activepieces/core-utils'
import {
PieceAuthProperty,
piecePropertiesUtils,
PiecePropertyMap,
} from '@activepieces/pieces-framework'
-import { AiRouterActionSettingsWithValidation, CodeActionSettings, FlowActionType, FlowOperationRequest, FlowOperationType, flowPieceUtil, flowStructureUtil, FlowTrigger, FlowTriggerType, LoopOnItemsActionSettings, PieceActionSettings, PieceTriggerSettings, RouterActionSettingsWithValidation, SourceCode } from '@activepieces/shared'
+import { AiRouterActionSettingsWithValidation, CodeActionSettings, FlowActionType, FlowOperationRequest, FlowOperationType, flowPieceUtil, flowStructureUtil, FlowTrigger, FlowTriggerType, LoopOnItemsActionSettings, PieceActionSettings, PieceTriggerSettings, RouterActionSettingsWithValidation, SourceCode, Step } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { z } from 'zod'
import { pieceMetadataService } from '../../pieces/metadata/piece-metadata-service'
@@ -24,6 +24,7 @@ const codeSettingsValidator = CodeActionSettings.and(z.object({
type ValidationResult = {
valid: boolean
cleanInput?: Record<string, unknown>
+ invalidInputs?: string[]
}
export const flowVersionValidationUtil = (log: FastifyBaseLogger) => ({
@@ -135,6 +136,15 @@ export const flowVersionValidationUtil = (log: FastifyBaseLogger) => ({
}
return clonedRequest
},
+ async invalidPieceInputs({ platformId, step }: { platformId: PlatformId, step: Step }): Promise<string[]> {
+ if (step.type === FlowActionType.PIECE) {
+ return (await validateAction({ settings: step.settings, platformId, log })).invalidInputs ?? []
+ }
+ if (step.type === FlowTriggerType.PIECE) {
+ return (await validateTrigger({ settings: step.settings, platformId, log })).invalidInputs ?? []
+ }
+ return []
+ },
})
function assertImportedStepNamesAreSafe(trigger: FlowTrigger): void {
@@ -216,12 +226,24 @@ function validateProps(
const cleanInput = !isNil(input) ? Object.fromEntries(
schemaKeys.map(key => [key, input?.[key]]),
) : undefined
+ const parsed = propsSchema.safeParse(cleanInput)
return {
- valid: propsSchema.safeParse(cleanInput).success,
+ valid: parsed.success,
cleanInput,
+ invalidInputs: parsed.success ? [] : describeInvalidInputs({ issues: parsed.error.issues, input: cleanInput }),
}
}
+function describeInvalidInputs({ issues, input }: { issues: z.ZodError['issues'], input: Record<string, unknown> | undefined }): string[] {
+ const keys = unique(issues.flatMap((issue) => typeof issue.path[0] === 'string' ? [issue.path[0]] : []))
+ return keys.map((key) => {
+ const label = key === 'auth' ? 'connection' : key
+ const value = input?.[key]
+ const missing = isNil(value) || value === ''
+ return missing ? `${label} is missing` : `${label} has an invalid value`
+ })
+}
+
type PrepareRequestParams = {
platformId?: PlatformId
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.ts
index e960735e45a..e913d4aece1 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
@@ -1,8 +1,9 @@
-import { isNil, Permission } from '@activepieces/core-utils'
+import { isNil, Permission, tryCatch } from '@activepieces/core-utils'
import { FlowActionType, FlowCreatorType, FlowOperationType, flowStructureUtil, FlowTriggerType, McpToolContext, McpToolDefinition, PieceTrigger, StepLocationRelativeToParent, UpdateActionRequest } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { z } from 'zod'
import { flowService } from '../../flows/flow/flow.service'
+import { flowVersionValidationUtil } from '../../flows/flow-version/flow-version-validator-util'
import { domainHelper } from '../../helper/domain-helper'
import { projectService } from '../../project/project-service'
import { mcpUtils } from './mcp-utils'
@@ -193,7 +194,12 @@ export const apBuildFlowTool = ({ mcp, userId }: McpToolContext, log: FastifyBas
const allSteps = flowStructureUtil.getAllSteps(currentFlow.version.trigger)
const validCount = allSteps.filter(s => s.valid).length
- const invalidSteps = allSteps.filter(s => !s.valid).map(s => s.name)
+ const invalidStepList = allSteps.filter(s => !s.valid)
+ const invalidSteps = invalidStepList.map(s => s.name)
+ const describedInvalidSteps = await Promise.all(invalidStepList.map(async (step) => {
+ const { data: reasons } = await tryCatch(() => flowVersionValidationUtil(log).invalidPieceInputs({ platformId, step }))
+ return describeInvalidStep({ name: step.name, reasons: reasons ?? [] })
+ }))
const stepWord = allSteps.length === 1 ? 'step' : 'steps'
const skippedHint = skippedSteps.length > 0 ? ` Skipped: ${skippedSteps.join(', ')}.` : ''
@@ -216,7 +222,7 @@ export const apBuildFlowTool = ({ mcp, userId }: McpToolContext, log: FastifyBas
if (invalidSteps.length === 0 && skippedSteps.length === 0) {
return { content: [{ type: 'text', text: `✅ Flow "${flowName}" created (id: ${flowId})${createdIn} with ${allSteps.length} ${stepWord}, all valid. Open: ${flowUrl}${solutionCheckHint}` }], structuredContent: structured }
}
- return { content: [{ type: 'text', text: `⚠️ Flow "${flowName}" created (id: ${flowId})${createdIn} with ${allSteps.length} ${stepWord} (${validCount} valid, ${invalidSteps.length} invalid: ${invalidSteps.join(', ')}).${skippedHint} Use ap_update_step or ap_update_trigger to fix. Open: ${flowUrl}${solutionCheckHint}` }], structuredContent: structured }
+ return { content: [{ type: 'text', text: `⚠️ Flow "${flowName}" created (id: ${flowId})${createdIn} with ${allSteps.length} ${stepWord} (${validCount} valid, ${invalidSteps.length} invalid: ${describedInvalidSteps.join(', ')}).${skippedHint} Use ap_update_step or ap_update_trigger to fix. Open: ${flowUrl}${solutionCheckHint}` }], structuredContent: structured }
}
catch (err) {
if (flowId) {
@@ -228,6 +234,10 @@ export const apBuildFlowTool = ({ mcp, userId }: McpToolContext, log: FastifyBas
}
}
+function describeInvalidStep({ name, reasons }: { name: string, reasons: string[] }): string {
+ return reasons.length === 0 ? name : `${name} (${reasons.join('; ')})`
+}
+
async function stepPropertySettings({ actionName, pieceName, pieceVersion, input, projectId, platformId, log }: {
actionName: string | undefined
pieceName: string | undefined
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.ts
index c0e7146d177..1946735f9d6 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
@@ -1272,6 +1272,77 @@ describe('MCP Tools integration', () => {
expect(text(result)).toContain('invalid')
})
+ it('47b. ap_build_flow — says why each invalid step is invalid', async () => {
+ const ctx = await createTestContext(app)
+ const mcp = makeMcp(ctx.project.id)
+
+ const result = await apBuildFlowTool({ mcp }, mockLog).execute({
+ flowName: 'Build Test Reasons',
+ trigger: { pieceName: '@activepieces/piece-test-email', triggerName: 'new_email' },
+ steps: [{
+ type: FlowActionType.PIECE,
+ displayName: 'Send Email',
+ pieceName: '@activepieces/piece-test-email',
+ actionName: 'send_email',
+ input: { to: '[email protected]' },
+ }],
+ })
+
+ expect(text(result)).toMatch(/step_1 \([^)]*subject is missing/)
+ })
+
+ it('47b2. ap_build_flow — says when only the connection is missing', async () => {
+ const ctx = await createTestContext(app)
+ const mcp = makeMcp(ctx.project.id)
+ await db.save('piece_metadata', createMockPieceMetadata({
+ name: '@activepieces/piece-test-keyed',
+ displayName: 'Test Keyed',
+ version: '0.1.0',
+ pieceType: PieceType.CUSTOM,
+ packageType: PackageType.REGISTRY,
+ platformId: ctx.platform.id,
+ auth: { type: 'SECRET_TEXT', displayName: 'API key', required: true },
+ actions: { ping: { name: 'ping', displayName: 'Ping', description: 'Ping', requireAuth: true, props: {} } },
+ triggers: {},
+ }))
+
+ const result = await apBuildFlowTool({ mcp }, mockLog).execute({
+ flowName: 'Build Test Connection Reason',
+ trigger: { pieceName: '@activepieces/piece-test-email', triggerName: 'new_email' },
+ steps: [{ type: FlowActionType.PIECE, displayName: 'Ping', pieceName: '@activepieces/piece-test-keyed', actionName: 'ping', input: {} }],
+ })
+
+ expect(text(result)).toContain('step_1 (connection is missing)')
+ })
+
+ it('47c. ap_build_flow — explains an empty or incomplete required array', async () => {
+ const ctx = await createTestContext(app)
+ const mcp = makeMcp(ctx.project.id)
+ const buildWithItems = (items: unknown[]) => apBuildFlowTool({ mcp }, mockLog).execute({
+ flowName: 'Build Test Array Reasons',
+ trigger: { pieceName: '@activepieces/piece-test-email', triggerName: 'new_email' },
+ steps: [{ type: FlowActionType.PIECE, displayName: 'With Array', pieceName: '@activepieces/piece-test-array', actionName: 'action_with_array', input: { items } }],
+ })
+
+ const incomplete = text(await buildWithItems([{}]))
+
+ expect(incomplete).toContain('step_1 (items has an invalid value)')
+ })
+
+ it('47d. ap_build_flow — never blames a dropdown that holds a step reference', async () => {
+ const ctx = await createTestContext(app)
+ const mcp = makeMcp(ctx.project.id)
+
+ const result = await apBuildFlowTool({ mcp }, mockLog).execute({
+ flowName: 'Build Test Reference Reasons',
+ trigger: { pieceName: '@activepieces/piece-test-email', triggerName: 'new_email' },
+ steps: [{ type: FlowActionType.PIECE, displayName: 'Send Email', pieceName: '@activepieces/piece-test-email', actionName: 'send_email', input: { to: '[email protected]', folder: "{{trigger['output'].folder}}" } }],
+ })
+
+ expect(text(result)).toMatch(/step_1 \([^)]*subject is missing/)
+ expect(text(result)).not.toContain('folder')
+ })
+
it('48. ap_build_flow — empty steps array creates trigger-only flow', async () => {
const ctx = await createTestContext(app)
const mcp = makeMcp(ctx.project.id)