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

13.9 KB
Raw Blame
import { isNil, Permission } from '@activepieces/core-utils'
import { BranchExecutionType, FlowActionType, FlowOperationRequest, FlowOperationType, flowStructureUtil, McpToolContext, McpToolDefinition, RouterExecutionType, StepLocationRelativeToParent, UpdateActionRequest } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { z } from 'zod'
import { flowService } from '../../flows/flow/flow.service'
import { projectService } from '../../project/project-service'
import { mcpUtils } from './mcp-utils'

const addStepInput = z.object({
    flowId: z.string(),
    parentStepName: z.string(),
    stepLocationRelativeToParent: z.enum(Object.values(StepLocationRelativeToParent) as [StepLocationRelativeToParent, ...StepLocationRelativeToParent[]]),
    branchIndex: z.number().optional(),
    stepType: z.enum([FlowActionType.CODE, FlowActionType.PIECE, FlowActionType.LOOP_ON_ITEMS, FlowActionType.ROUTER]),
    displayName: z.string(),
    pieceName: z.string().optional(),
    actionName: z.string().optional(),
    input: z.record(z.string(), z.unknown()).optional(),
    auth: z.string().optional(),
    sourceCode: z.string().optional(),
    packageJson: z.string().optional(),
    loopItems: z.string().optional(),
    continueOnFailure: z.boolean().optional(),
    retryOnFailure: z.boolean().optional(),
})

export const apAddStepTool = ({ mcp, userId }: McpToolContext, log: FastifyBaseLogger): McpToolDefinition => {
    return {
        title: 'ap_add_step',
        permission: Permission.WRITE_FLOW,
        description: 'Add a new step to a flow. Optionally configure it in the same call by providing input/auth/sourceCode. Prefer PIECE actions and inline formula expressions over CODE.',
        inputSchema: {
            flowId: z.string().describe('The id of the flow'),
            parentStepName: z.string().describe('The step name to insert after/into (e.g. "trigger", "step_1"). Use ap_flow_structure to get valid values.'),
            stepLocationRelativeToParent: z.enum(Object.values(StepLocationRelativeToParent) as [string, ...string[]]).describe('Where to place the step: AFTER = after the parent, INSIDE_LOOP = first action inside a loop, INSIDE_BRANCH = first action inside a router branch, INSIDE_ON_SUCCESS_BRANCH / INSIDE_ON_FAILURE_BRANCH = first action inside the On success / On failure branch of a continue-on-failure step (set continueOnFailure on the parent first).'),
            branchIndex: z.number().optional().describe('Branch index (required when stepLocationRelativeToParent is INSIDE_BRANCH)'),
            stepType: z.enum([FlowActionType.CODE, FlowActionType.PIECE, FlowActionType.LOOP_ON_ITEMS, FlowActionType.ROUTER]).describe('The type of step to add. Prefer PIECE over CODE — only use CODE when no piece fits and the logic can\'t be done with an inline formula expression (in a free-text/value input) or a router condition.'),
            displayName: z.string().describe('Display name for the step'),
            pieceName: z.string().optional().describe('For PIECE steps: the piece name (e.g. "@activepieces/piece-gmail"). Use ap_research_pieces to get valid values.'),
            actionName: z.string().optional().describe('For PIECE steps: the action name within the piece. Use ap_research_pieces with includeActions=true to get valid values.'),
            input: z.record(z.string(), z.unknown()).optional().describe(`For PIECE/CODE steps: input config (key-value pairs). ${mcpUtils.STEP_REFERENCE_HINT}`),
            auth: z.string().optional().describe('Connection externalId from ap_list_connections. Pass the plain id, not a template.'),
            sourceCode: z.string().optional().describe('For CODE steps: JavaScript/TypeScript source. Must export a `code` function.'),
            packageJson: z.string().optional().describe('For CODE steps: package.json as JSON string. Defaults to "{}".'),
            loopItems: z.string().optional().describe('For LOOP steps: expression for items to iterate (e.g. "{{step_1[\'output\'].items}}").'),
            continueOnFailure: z.boolean().optional().describe('For CODE/PIECE steps: set true on the step that can fail (the one whose failure you want to react to), NOT on the recovery step. Defaults to false. When true the flow keeps running on failure and the step gains On success / On failure branches — add handler steps into them with stepLocationRelativeToParent INSIDE_ON_SUCCESS_BRANCH / INSIDE_ON_FAILURE_BRANCH and parentStepName = this step.'),
            retryOnFailure: z.boolean().optional().describe('For CODE/PIECE steps: whether to retry this step on failure. Defaults to false.'),
        },
        annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
        execute: async (args) => {
            const { flowId, parentStepName, stepLocationRelativeToParent, branchIndex, stepType, displayName, pieceName, actionName, input, auth: rawAuth, sourceCode, packageJson, loopItems, continueOnFailure, retryOnFailure } = addStepInput.parse(args)
            const auth = mcpUtils.normalizeAuth(rawAuth)

            const [flow, project] = await Promise.all([
                flowService(log).getOnePopulated({ id: flowId, projectId: mcp.projectId }),
                projectService(log).getOneOrThrow(mcp.projectId),
            ])
            if (isNil(flow)) {
                return { content: [{ type: 'text', text: '❌ Flow not found' }] }
            }

            const stepName = flowStructureUtil.findUnusedName(flow.version.trigger)

            const authError = mcpUtils.validateAuth(auth)
            if (authError) {
                return authError
            }

            const rewritten = mcpUtils.rewriteAllReferences({ input, loopItems, trigger: flow.version.trigger })

            const resolvedInput = {
                ...(rewritten.input ?? {}),
                ...(auth !== undefined && { auth: `{{connections['${auth}']}}` }),
            }

            let skeletonAction: Record<string, unknown>
            switch (stepType) {
                case FlowActionType.CODE:
                    skeletonAction = {
                        type: FlowActionType.CODE,
                        name: stepName,
                        displayName,
                        valid: false,
                        settings: {
                            sourceCode: {
                                code: sourceCode ?? 'export const code = async (inputs) => { return {} }',
                                packageJson: packageJson ?? '{}',
                            },
                            input: resolvedInput,
                            errorHandlingOptions: mcpUtils.buildErrorHandlingOptions({ continueOnFailure, retryOnFailure }),
                            useDeno: true,
                        },
                    }
                    break
                case FlowActionType.PIECE: {
                    if (!pieceName) {
                        return {
                            content: [{
                                type: 'text',
                                text: '❌ pieceName is required for PIECE steps. Use ap_research_pieces to get valid values.',
                            }],
                        }
                    }
                    const versionResult = await mcpUtils.resolveLatestPieceVersion({ pieceName, projectId: mcp.projectId, platformId: project.platformId, log })
                    if (versionResult.error) {
                        return versionResult.error
                    }
                    const pieceSettings: Record<string, unknown> = {
                        pieceName: versionResult.normalizedPieceName,
                        pieceVersion: versionResult.pieceVersion,
                        actionName: actionName ?? '',
                        input: resolvedInput,
                        propertySettings: {},
                        errorHandlingOptions: mcpUtils.buildErrorHandlingOptions({ continueOnFailure, retryOnFailure }),
                    }
                    if (input !== undefined) {
                        await mcpUtils.fillDefaultsForMissingOptionalProps({ settings: pieceSettings, platformId: project.platformId, log })
                        if (typeof actionName === 'string' && actionName.length > 0) {
                            const unknownPropsError = await mcpUtils.rejectUnknownInputProps({ pieceName: versionResult.normalizedPieceName, pieceVersion: versionResult.pieceVersion, componentName: actionName, componentType: 'action', input: pieceSettings.input, platformId: project.platformId, log })
                            if (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 = {
                        type: FlowActionType.PIECE,
                        name: stepName,
                        displayName,
                        valid: false,
                        settings: pieceSettings,
                    }
                    break
                }
                case FlowActionType.LOOP_ON_ITEMS:
                    skeletonAction = {
                        type: FlowActionType.LOOP_ON_ITEMS,
                        name: stepName,
                        displayName,
                        valid: false,
                        settings: {
                            items: rewritten.loopItems ?? '',
                        },
                    }
                    break
                case FlowActionType.ROUTER:
                    skeletonAction = {
                        type: FlowActionType.ROUTER,
                        name: stepName,
                        displayName,
                        valid: false,
                        settings: {
                            branches: [
                                { branchName: 'Branch 1', branchType: BranchExecutionType.CONDITION, conditions: [[]] },
                                { branchName: 'Otherwise', branchType: BranchExecutionType.FALLBACK },
                            ],
                            executionType: RouterExecutionType.EXECUTE_FIRST_MATCH,
                        },
                    }
                    break
                default:
                    return {
                        content: [{ type: 'text', text: `❌ Unknown step type: ${stepType}` }],
                    }
            }

            if (stepLocationRelativeToParent === StepLocationRelativeToParent.INSIDE_BRANCH && branchIndex === undefined) {
                return {
                    content: [{ type: 'text', text: '❌ branchIndex is required when stepLocationRelativeToParent is INSIDE_BRANCH. Use ap_flow_structure to get valid branch indices.' }],
                }
            }

            const parseResult = UpdateActionRequest.safeParse(skeletonAction)
            if (!parseResult.success) {
                const message = parseResult.error.issues.map(e => `${e.path.join('.')}: ${e.message}`).join('; ')
                return {
                    content: [{ type: 'text', text: `❌ Invalid step: ${message}` }],
                }
            }

            const operation: FlowOperationRequest = {
                type: FlowOperationType.ADD_ACTION,
                request: {
                    parentStep: parentStepName,
                    stepLocationRelativeToParent,
                    ...(branchIndex !== undefined && { branchIndex }),
                    action: parseResult.data,
                },
            }

            try {
                const updatedFlow = await flowService(log).update({
                    id: flow.id,
                    projectId: mcp.projectId,
                    userId,
                    previousFlow: flow,
                    platformId: project.platformId,
                    operation,
                })

                const draftWarning = mcpUtils.publishedFlowWarning(flow.publishedVersionId)
                const hasConfig = input !== undefined || auth !== undefined || sourceCode !== undefined || loopItems !== undefined
                const addedStep = flowStructureUtil.getStep(stepName, updatedFlow.version.trigger)
                const stepValid = hasConfig && addedStep ? addedStep.valid : false
                const structured = { stepName, displayName, valid: stepValid }
                if (hasConfig && addedStep && !addedStep.valid) {
                    return {
                        content: [{
                            type: 'text',
                            text: `⚠️ Step "${displayName}" (${stepName}) added but still invalid. Use ap_get_piece_props to check required fields, then ap_update_step to fix.${draftWarning}`,
                        }],
                        structuredContent: structured,
                    }
                }
                if (hasConfig) {
                    return {
                        content: [{
                            type: 'text',
                            text: `✅ Step "${displayName}" (${stepName}) added and configured.${draftWarning}`,
                        }],
                        structuredContent: { ...structured, valid: true },
                    }
                }
                return {
                    content: [{
                        type: 'text',
                        text: `✅ Step "${displayName}" (${stepName}) added. Now use ap_update_step with stepName="${stepName}" to configure its settings.${draftWarning}`,
                    }],
                    structuredContent: structured,
                }
            }
            catch (err) {
                return mcpUtils.mcpToolError('Step add failed', err)
            }
        },
    }
}