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

8.4 KB
Raw Blame
import { isNil, Permission } from '@activepieces/core-utils'
import { FlowOperationRequest, FlowOperationType, FlowTriggerType, McpToolContext, McpToolDefinition, PieceTrigger } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { z } from 'zod'
import { flowService } from '../../flows/flow/flow.service'
import { pieceMetadataService } from '../../pieces/metadata/piece-metadata-service'
import { projectService } from '../../project/project-service'
import { mcpUtils } from './mcp-utils'

const updateTriggerInput = z.object({
    flowId: z.string(),
    pieceName: z.string(),
    triggerName: z.string(),
    input: z.record(z.string(), z.unknown()).optional(),
    auth: z.string().optional(),
    displayName: z.string().optional(),
})

export const apUpdateTriggerTool = ({ mcp, userId }: McpToolContext, log: FastifyBaseLogger): McpToolDefinition => {
    return {
        title: 'ap_update_trigger',
        permission: Permission.WRITE_FLOW,
        description: 'Set or update the trigger for a flow.',
        inputSchema: {
            flowId: z.string().describe('The id of the flow'),
            pieceName: z.string().describe('The piece name for the trigger (e.g. "@activepieces/piece-gmail"). Use ap_research_pieces to get valid values.'),
            triggerName: z.string().describe('The trigger name within the piece (e.g. "new_email"). Use ap_research_pieces with includeTriggers=true to get valid values.'),
            input: z.record(z.string(), z.unknown()).optional().describe(`Input settings for the trigger (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.'),
            displayName: z.string().optional().describe('Display name for the trigger step'),
        },
        annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
        execute: async (args) => {
            const { flowId, pieceName, triggerName, input: rawInput, auth: rawAuth, displayName: rawDisplayName } = updateTriggerInput.parse(args)
            const auth = mcpUtils.normalizeAuth(rawAuth)

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

            const displayName = rawDisplayName ?? triggerName

            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 versionResult = await mcpUtils.resolveLatestPieceVersion({ pieceName, projectId: mcp.projectId, platformId: project.platformId, log })
            if (versionResult.error) {
                return versionResult.error
            }
            const pieceVersion = versionResult.pieceVersion
            const resolvedPieceName = versionResult.normalizedPieceName

            const existingTrigger = flow.version.trigger
            const existingPieceSettings = existingTrigger.type === FlowTriggerType.PIECE
                && existingTrigger.settings.pieceName === resolvedPieceName
                && existingTrigger.settings.triggerName === triggerName
                ? existingTrigger.settings
                : null

            const { auth: _rawAuth, ...rawInputWithoutAuth } = rawInput ?? {}
            const rewritten = mcpUtils.rewriteAllReferences({ input: rawInputWithoutAuth, trigger: flow.version.trigger })
            const callerInput = {
                ...(rewritten.input ?? {}),
                ...(auth !== undefined && { auth: `{{connections['${auth}']}}` }),
            }
            const { input, error: unknownPropsError } = await mcpUtils.keepKnownInputProps({ pieceName: resolvedPieceName, pieceVersion, componentName: triggerName, componentType: 'trigger', input: { ...(existingPieceSettings?.input ?? {}), ...callerInput }, callerInput, platformId: project.platformId, log })
            if (unknownPropsError) {
                return unknownPropsError
            }

            const triggerPayload = {
                name: flow.version.trigger.name,
                displayName,
                valid: false,
                lastUpdatedDate: new Date().toISOString(),
                type: FlowTriggerType.PIECE,
                settings: {
                    pieceName: resolvedPieceName,
                    pieceVersion,
                    triggerName,
                    input,
                    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 }),
                },
            }

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

            const operation: FlowOperationRequest = {
                type: FlowOperationType.UPDATE_TRIGGER,
                request: parseResult.data,
            }

            try {
                const updatedFlow = await flowService(log).update({
                    id: flow.id,
                    projectId: mcp.projectId,
                    userId,
                    previousFlow: flow,
                    platformId: project.platformId,
                    operation,
                })
                const trigger = updatedFlow.version.trigger
                const draftWarning = mcpUtils.publishedFlowWarning(flow.publishedVersionId)
                if (!trigger.valid) {
                    const diagnosis = await diagnoseMissingTriggerInputs({ pieceName: resolvedPieceName, pieceVersion, triggerName, input, platformId: project.platformId, log })
                    const hint = diagnosis ?? 'Check that triggerName is correct and all required inputs are provided. Use ap_list_connections to get a valid connection externalId for auth.'
                    return {
                        content: [{
                            type: 'text',
                            text: `⚠️ Trigger updated but still invalid. ${hint}${draftWarning}`,
                        }],
                    }
                }
                return {
                    content: [{ type: 'text', text: `✅ Successfully updated trigger to "${resolvedPieceName}/${triggerName}".${draftWarning}` }],
                }
            }
            catch (err) {
                return mcpUtils.mcpToolError('Trigger update failed', err)
            }
        },
    }
}

async function diagnoseMissingTriggerInputs({ pieceName, pieceVersion, triggerName, input, platformId, log }: {
    pieceName: string
    pieceVersion: string
    triggerName: string
    input: Record<string, unknown>
    platformId: string
    log: FastifyBaseLogger
}): Promise<string | null> {
    try {
        const piece = await pieceMetadataService(log).getOrThrow({ platformId, name: pieceName, version: pieceVersion })
        const trigger = piece.triggers[triggerName]
        if (isNil(trigger)) {
            return `Trigger "${triggerName}" not found in piece "${pieceName}". Use ap_research_pieces with includeTriggers=true to get valid trigger names.`
        }
        const { parts, missing, uiRequired, hasAuth } = mcpUtils.diagnosePieceProps({ props: trigger.props, input, pieceAuth: piece.auth, requireAuth: trigger.requireAuth, componentType: 'trigger' })
        if (missing.length === 0 && uiRequired.length === 0 && !hasAuth) {
            return 'All inputs are provided but the trigger may need sample data. Ask the user to send a test event or configure the trigger in the Activepieces UI.'
        }
        return parts.join(' ')
    }
    catch (err) {
        log.warn({ error: err, piece: { name: pieceName }, trigger: { name: triggerName } }, 'diagnoseMissingTriggerInputs: failed to fetch piece metadata')
        return null
    }
}