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

143 KB
Raw Blame
import { apId, isObject } from '@activepieces/core-utils'
import { EngineResponseStatus, FlowActionType, FlowCreatorType, FlowOperationType, FlowRunStatus, flowStructureUtil, FlowTriggerType, McpServerType, PackageType, PieceType, ProjectScopedMcpServer, RunEnvironment, StepLocationRelativeToParent, TriggerStrategy, TriggerTestStrategy } from '@activepieces/shared'
import { FastifyBaseLogger, FastifyInstance } from 'fastify'
import { StatusCodes } from 'http-status-codes'
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'
import { system } from '../../../../src/app/helper/system/system'
import { AppSystemProp } from '../../../../src/app/helper/system/system-props'
import { apBuildFlowTool } from '../../../../src/app/mcp/tools/ap-build-flow'
import { apCreateFlowTool } from '../../../../src/app/mcp/tools/ap-create-flow'
import { apCreateFolderTool } from '../../../../src/app/mcp/tools/ap-create-folder'
import { apCreateTableTool } from '../../../../src/app/mcp/tools/ap-create-table'
import { apFlowStructureTool } from '../../../../src/app/mcp/tools/ap-flow-structure'
import { apResearchPiecesTool } from '../../../../src/app/mcp/tools/ap-research-pieces'
import { apAddStepTool } from '../../../../src/app/mcp/tools/ap-add-step'
import { apUpdateStepTool } from '../../../../src/app/mcp/tools/ap-update-step'
import { apRenameFlowTool } from '../../../../src/app/mcp/tools/ap-rename-flow'
import { apDeleteStepTool } from '../../../../src/app/mcp/tools/ap-delete-step'
import { apLockAndPublishTool } from '../../../../src/app/mcp/tools/ap-lock-and-publish'
import { apAddBranchTool } from '../../../../src/app/mcp/tools/ap-add-branch'
import { apDeleteBranchTool } from '../../../../src/app/mcp/tools/ap-delete-branch'
import { apGetPiecePropsTool } from '../../../../src/app/mcp/tools/ap-get-piece-props'
import { apValidateStepConfigTool } from '../../../../src/app/mcp/tools/ap-validate-step-config'
import { apValidateFlowTool } from '../../../../src/app/mcp/tools/ap-validate-flow'
import { apUpdateTriggerTool } from '../../../../src/app/mcp/tools/ap-update-trigger'
import { apDuplicateFlowTool } from '../../../../src/app/mcp/tools/ap-duplicate-flow'
import { apUpdateBranchTool } from '../../../../src/app/mcp/tools/ap-update-branch'
import { apListRunsTool } from '../../../../src/app/mcp/tools/ap-list-runs'
import { apGetRunTool } from '../../../../src/app/mcp/tools/ap-get-run'
import { apListFlowsTool } from '../../../../src/app/mcp/tools/ap-list-flows'
import { apListFoldersTool } from '../../../../src/app/mcp/tools/ap-list-folders'
import { apMoveFlowToFolderTool } from '../../../../src/app/mcp/tools/ap-move-flow-to-folder'
import { apReadStepSettingsTool } from '../../../../src/app/mcp/tools/ap-read-step-settings'
import { 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'
import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'

let app: FastifyInstance
let mockLog: FastifyBaseLogger

beforeAll(async () => {
    app = await setupTestEnvironment()
    mockLog = app.log

    // Save a shared piece needed by PIECE-step tests. No platformId = OFFICIAL (visible to all platforms).
    // In test environment the piece cache is bypassed, so DB records are read directly.
    const gmailPiece = createMockPieceMetadata({
        name: '@activepieces/piece-test-email',
        displayName: 'Test Email',
        version: '0.1.0',
        pieceType: PieceType.OFFICIAL,
        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',
                description: 'Send an email',
                requireAuth: true,
                props: {
                    to: { type: 'SHORT_TEXT', displayName: 'To', required: true },
                    subject: { type: 'SHORT_TEXT', displayName: 'Subject', required: true },
                    folder: { type: 'DROPDOWN', displayName: 'Folder', required: false, refreshers: ['auth'] },
                },
            },
        },
        triggers: {
            new_email: {
                name: 'new_email',
                displayName: 'New Email',
                description: 'Triggers on new email',
                requireAuth: false,
                props: {
                    folder: { type: 'SHORT_TEXT', displayName: 'Folder', required: false },
                    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',
                description: 'Triggers on new email with a label',
                requireAuth: false,
                props: {
                    folder: { type: 'SHORT_TEXT', displayName: 'Folder', required: false },
                    label: { type: 'SHORT_TEXT', displayName: 'Label', required: true },
                },
            },
            new_attachment: {
                name: 'new_attachment',
                displayName: 'New Attachment',
                description: 'Triggers on new attachment',
                requireAuth: false,
                props: {},
            },
        },
    })
    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',
        displayName: 'Test Array',
        version: '0.1.0',
        pieceType: PieceType.OFFICIAL,
        packageType: PackageType.REGISTRY,
        platformId: undefined,
        actions: {
            action_with_array: {
                name: 'action_with_array',
                displayName: 'Action With Array',
                description: 'Action with array property',
                requireAuth: false,
                props: {
                    items: {
                        type: 'ARRAY',
                        displayName: 'Items',
                        required: true,
                        properties: {
                            name: { type: 'SHORT_TEXT', displayName: 'Name', required: true },
                            value: { type: 'NUMBER', displayName: 'Value', required: false },
                        },
                    },
                },
            },
        },
        triggers: {},
    })
    await db.save('piece_metadata', arrayPiece)

    const dynamicPiece = createMockPieceMetadata({
        name: '@activepieces/piece-test-dynamic',
        displayName: 'Test Dynamic',
        version: '0.1.0',
        pieceType: PieceType.OFFICIAL,
        packageType: PackageType.REGISTRY,
        platformId: undefined,
        actions: {
            test_action: {
                name: 'test_action',
                displayName: 'Test Action',
                description: 'Action with dynamic props',
                requireAuth: false,
                props: {
                    mode: { type: 'STATIC_DROPDOWN', displayName: 'Mode', required: true, options: { options: [{ label: 'A', value: 'a' }, { label: 'B', value: 'b' }] } },
                    dynamicField: { type: 'DYNAMIC', displayName: 'Dynamic Field', required: false, refreshers: ['mode'] },
                },
            },
        },
        triggers: {},
    })
    await db.save('piece_metadata', dynamicPiece)
})

afterAll(async () => {
    await teardownTestEnvironment()
})

function makeMcp(projectId: string): ProjectScopedMcpServer {
    return {
        id: apId(),
        created: new Date().toISOString(),
        updated: new Date().toISOString(),
        projectId,
        platformId: null,
        type: McpServerType.PROJECT,
        token: apId(),
        disabledTools: null,
    }
}

function text(result: { content: Array<{ type: 'text', text: string }> }): string {
    return result.content.map(c => c.text).join('\n')
}

function structured<T extends z.ZodType>({ result, schema }: { result: { structuredContent?: unknown }, schema: T }): z.infer<T> {
    return schema.parse(result.structuredContent)
}

async function createFlowAndGetId(mcp: ProjectScopedMcpServer, flowName: string): Promise<string> {
    const result = await apCreateFlowTool({ mcp }, mockLog).execute({ flowName })
    const match = text(result).match(/\(id: (\S+?)\)/)
    if (!match) throw new Error(`Could not extract flowId from: ${text(result)}`)
    return match[1]
}

describe('MCP Tools integration', () => {
    it('1. ap_list_flows — lists flows in the project', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        await apCreateFlowTool({ mcp }, mockLog).execute({ flowName: 'Flow Alpha' })
        await apCreateFlowTool({ mcp }, mockLog).execute({ flowName: 'Flow Beta' })

        const result = await apListFlowsTool(mcp, mockLog).execute({})

        expect(text(result)).toContain('✅')
        expect(text(result)).toContain('Flow Alpha')
        expect(text(result)).toContain('Flow Beta')
    })

    it('2. ap_create_flow — creates a flow and returns its ID', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apCreateFlowTool({ mcp }, mockLog).execute({ flowName: 'My Test Flow' })

        expect(text(result)).toContain('✅')
        expect(text(result)).toContain('My Test Flow')

        // Verify the flow exists via list
        const listResult = await apListFlowsTool(mcp, mockLog).execute({})
        expect(text(listResult)).toContain('My Test Flow')
    })

    it('3. ap_flow_structure — new flow has empty unconfigured trigger', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const flowId = await createFlowAndGetId(mcp, 'Structure Test Flow')

        const result = await apFlowStructureTool(mcp, mockLog).execute({ flowId })

        expect(text(result)).toContain('[TRIGGER]')
        expect(text(result)).toContain('EMPTY')
        expect(text(result)).toContain('unconfigured')
    })

    it('4. ap_research_pieces — lists pieces matching search query', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apResearchPiecesTool(mcp, mockLog).execute({ searchQuery: 'test-email' })

        expect(text(result)).toContain('✅')
        expect(text(result).toLowerCase()).toContain('test-email')
    })

    it('5. ap_add_step — adds a PIECE skeleton step after trigger', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Add Step Flow')

        const result = await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'trigger',
            stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER,
            stepType: FlowActionType.PIECE,
            displayName: 'Send Email',
            pieceName: '@activepieces/piece-test-email',
        })

        expect(text(result)).toContain('✅')
        expect(text(result)).toContain('step_1')

        const structure = await apFlowStructureTool(mcp, mockLog).execute({ flowId })
        expect(text(structure)).toContain('step_1')
        expect(text(structure)).toContain('PIECE')
    })

    it('6. ap_update_step — sets skip flag on a step', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Update Step Flow')

        await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'trigger',
            stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER,
            stepType: FlowActionType.PIECE,
            displayName: 'Send Email',
            pieceName: '@activepieces/piece-test-email',
        })

        // Update the step: set skip=true. The step is still invalid (no actionName configured)
        // so the tool returns ⚠️, not ❌ — the update itself succeeded.
        const result = await apUpdateStepTool({ mcp }, mockLog).execute({
            flowId,
            stepName: 'step_1',
            displayName: 'Send Welcome Email',
            skip: true,
        })

        expect(text(result)).not.toContain('❌')

        // Flow structure should now show the step as skipped
        const structure = await apFlowStructureTool(mcp, mockLog).execute({ flowId })
        expect(text(structure)).toContain('skipped')
    })

    it('7. ap_rename_flow — renames a flow', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Original Name')

        const result = await apRenameFlowTool({ mcp }, mockLog).execute({ flowId, displayName: 'Renamed Flow' })

        expect(text(result)).toContain('✅')
        expect(text(result)).toContain('Renamed Flow')

        // Flow structure header should reflect the new name
        const structure = await apFlowStructureTool(mcp, mockLog).execute({ flowId })
        expect(text(structure)).toContain('Renamed Flow')
    })

    it('ap_add_step and ap_update_step mark a list or JSON field holding one whole reference as dynamic, and a real value back as manual', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        await db.save('piece_metadata', createMockPieceMetadata({
            name: '@activepieces/piece-test-containers',
            displayName: 'Test Containers',
            version: '0.1.0',
            pieceType: PieceType.CUSTOM,
            packageType: PackageType.REGISTRY,
            platformId: ctx.platform.id,
            actions: {
                locate: {
                    name: 'locate',
                    displayName: 'Locate',
                    description: 'Locates assets',
                    requireAuth: false,
                    props: {
                        assetIds: { type: 'ARRAY', displayName: 'Asset Ids', required: true },
                        body: { type: 'JSON', displayName: 'Body', required: false },
                    },
                },
            },
            triggers: {},
        }))
        const flowId = await createFlowAndGetId(mcp, 'Whole reference flow')

        await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'trigger',
            stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER,
            stepType: FlowActionType.PIECE,
            displayName: 'Locate',
            pieceName: '@activepieces/piece-test-containers',
            actionName: 'locate',
            input: { assetIds: '{{trigger.body.assetIds}}', body: '{{trigger.body}}' },
        })
        const added = flowStructureUtil.getStep('step_1', (await flowService(mockLog).getOnePopulatedOrThrow({ id: flowId, projectId: ctx.project.id })).version.trigger)
        await apUpdateStepTool({ mcp }, mockLog).execute({ flowId, stepName: 'step_1', input: { assetIds: ['a', 'b'] } })
        const updated = flowStructureUtil.getStep('step_1', (await flowService(mockLog).getOnePopulatedOrThrow({ id: flowId, projectId: ctx.project.id })).version.trigger)

        expect(added?.settings.propertySettings).toMatchObject({ assetIds: { type: 'DYNAMIC' }, body: { type: 'DYNAMIC' } })
        expect(updated?.settings.propertySettings).toMatchObject({ assetIds: { type: 'MANUAL' }, body: { type: 'DYNAMIC' } })
    })

    it('8. ap_delete_step — removes a step from a flow', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Delete Step Flow')

        await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'trigger',
            stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER,
            stepType: FlowActionType.CODE,
            displayName: 'My Code Step',
        })

        const result = await apDeleteStepTool({ mcp }, mockLog).execute({ flowId, stepName: 'step_1' })

        expect(text(result)).toContain('✅')

        // step_1 should no longer appear in the flow structure
        const structure = await apFlowStructureTool(mcp, mockLog).execute({ flowId })
        expect(text(structure)).not.toContain('step_1')
    })

    it('9. ap_lock_and_publish — fails gracefully when flow has invalid steps', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Unpublishable Flow')

        // A new flow has only an empty/unconfigured trigger — publishing should fail
        const result = await apLockAndPublishTool({ mcp }, mockLog).execute({ flowId })

        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('invalid')
    })

    it('10. ap_add_step + ap_add_branch + ap_delete_branch — router workflow', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Router Flow')

        // Add a ROUTER step (skeleton starts with Branch 1 at [0] and Otherwise fallback at [1])
        const routerResult = await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'trigger',
            stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER,
            stepType: FlowActionType.ROUTER,
            displayName: 'My Router',
        })
        expect(text(routerResult)).toContain('✅')

        // ap_add_branch inserts before the fallback (last) branch.
        // Router has 2 branches → insert at index max(0, 2-1) = 1
        // Result: Branch 1[0], VIP Customer[1], Otherwise[2]
        const addBranchResult = await apAddBranchTool({ mcp }, mockLog).execute({
            flowId,
            routerStepName: 'step_1',
            branchName: 'VIP Customer',
        })
        expect(text(addBranchResult)).toContain('✅')
        expect(text(addBranchResult)).toContain('VIP Customer')

        // Delete Branch 1 at index 0 (a non-fallback branch)
        // Result after delete: VIP Customer[0], Otherwise[1]
        const deleteBranchResult = await apDeleteBranchTool({ mcp }, mockLog).execute({
            flowId,
            routerStepName: 'step_1',
            branchIndex: 0,
        })
        expect(text(deleteBranchResult)).toContain('✅')

        // Attempting to delete the fallback branch (the only remaining non-first branch) must fail.
        // With 2 branches remaining, index 1 is the fallback → deletion blocked.
        const errorResult = await apDeleteBranchTool({ mcp }, mockLog).execute({
            flowId,
            routerStepName: 'step_1',
            branchIndex: 1,
        })
        expect(text(errorResult)).toContain('❌')
    })

    it('11. ap_get_piece_props — returns field schemas for a piece action', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apGetPiecePropsTool(mcp, mockLog).execute({
            pieceName: '@activepieces/piece-test-email',
            actionOrTriggerName: 'send_email',
            type: 'action',
        })

        expect(text(result)).toContain('✅')
        expect(text(result)).toContain('send_email')
        expect(text(result)).toContain('to')
        expect(text(result)).toContain('subject')
    })

    it('11b. ap_get_piece_props — a guessed name that clearly means one action returns that action', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const resolved = await apGetPiecePropsTool(mcp, mockLog).execute({ pieceName: '@activepieces/piece-test-email', actionOrTriggerName: 'sendEmail', type: 'action' })
        const unclear = await apGetPiecePropsTool(mcp, mockLog).execute({ pieceName: '@activepieces/piece-test-email', actionOrTriggerName: 'send', type: 'action' })
        const ambiguous = await apGetPiecePropsTool(mcp, mockLog).execute({ pieceName: '@activepieces/piece-test-email', actionOrTriggerName: 'email', type: 'trigger' })
        const blank = await apGetPiecePropsTool(mcp, mockLog).execute({ pieceName: '@activepieces/piece-test-array', actionOrTriggerName: '__', type: 'action' })

        expect(text(resolved)).toContain('✅')
        expect(text(resolved)).toContain('/send_email')
        expect(text(unclear)).toContain('❌')
        expect(text(ambiguous)).toContain('❌')
        expect(text(blank)).toContain('❌')
    })

    it('12. ap_get_piece_props — returns error for non-existent piece', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apGetPiecePropsTool(mcp, mockLog).execute({
            pieceName: '@activepieces/piece-nonexistent',
            actionOrTriggerName: 'fake_action',
            type: 'action',
        })

        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('not found')
    })

    it('13. ap_validate_step_config — CODE with valid source returns valid', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apValidateStepConfigTool(mcp, mockLog).execute({
            stepType: 'CODE',
            sourceCode: 'export const code = async () => { return true; };',
        })

        expect(text(result)).toContain('✅')
        expect(text(result)).toContain('Valid CODE')
    })

    it('14. ap_validate_step_config — CODE with empty source returns invalid', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apValidateStepConfigTool(mcp, mockLog).execute({
            stepType: 'CODE',
        })

        expect(text(result)).toContain('⚠️')
        expect(text(result)).toContain('Invalid CODE')
    })

    it('15. ap_validate_step_config — LOOP with items returns valid', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apValidateStepConfigTool(mcp, mockLog).execute({
            stepType: 'LOOP_ON_ITEMS',
            loopItems: '{{step_1.output}}',
        })

        expect(text(result)).toContain('✅')
        expect(text(result)).toContain('Valid LOOP')
    })

    it('16. ap_validate_step_config — LOOP without items returns invalid', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apValidateStepConfigTool(mcp, mockLog).execute({
            stepType: 'LOOP_ON_ITEMS',
        })

        expect(text(result)).toContain('⚠️')
        expect(text(result)).toContain('Invalid LOOP')
    })

    it('17. ap_validate_step_config — PIECE_ACTION missing pieceName returns error', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apValidateStepConfigTool(mcp, mockLog).execute({
            stepType: 'PIECE_ACTION',
            actionName: 'send_email',
        })

        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('pieceName')
    })

    it('18. ap_validate_flow — new flow with empty trigger has issues', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Validate Flow Test')

        const result = await apValidateFlowTool({ mcp }, mockLog).execute({ flowId })

        expect(text(result)).toContain('⚠️')
        expect(text(result)).toContain('not configured')
    })

    it('19. ap_validate_flow — flow with configured trigger and valid CODE step is ready', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Valid Flow Test')

        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.CODE,
            displayName: 'My Code',
        })

        await apUpdateStepTool({ mcp }, mockLog).execute({
            flowId,
            stepName: 'step_1',
            sourceCode: 'export const code = async () => { return { ok: true }; };',
            input: {},
        })

        const result = await apValidateFlowTool({ mcp }, mockLog).execute({ flowId })

        expect(text(result)).toContain('✅')
        expect(text(result)).toContain('ready to publish')
        expect(text(result)).not.toContain('⚠️')
        expect(text(result)).not.toContain('issue')
    })

    it('20. ap_validate_flow — flow with invalid step lists it', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Invalid Step Flow')

        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: 'Unconfigured Piece',
            pieceName: '@activepieces/piece-test-email',
        })

        const result = await apValidateFlowTool({ mcp }, mockLog).execute({ flowId })

        expect(text(result)).toContain('⚠️')
        expect(text(result)).toContain('Step Validity')
        expect(text(result)).toContain('Unconfigured Piece')
        expect(text(result)).toContain('invalid')
        expect(text(result)).toContain('1 invalid')
    })

    it('21. ap_validate_flow — detects empty router branches', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Router Validate Flow')

        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.ROUTER,
            displayName: 'My Router',
        })

        const result = await apValidateFlowTool({ mcp }, mockLog).execute({ flowId })

        expect(text(result)).toContain('⚠️')
        expect(text(result)).toContain('Empty Branches')
        expect(text(result)).toContain('My Router')
        expect(text(result)).toContain('empty branch')
    })

    it('22. ap_get_piece_props — without auth returns note for dropdown fields', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apGetPiecePropsTool(mcp, mockLog).execute({
            pieceName: '@activepieces/piece-test-email',
            actionOrTriggerName: 'send_email',
            type: 'action',
        })

        expect(text(result)).toContain('✅')
        expect(text(result)).toContain('folder')
        expect(text(result)).toContain('DROPDOWN')
        expect(text(result)).toContain('ap_resolve_property_options')
    })

    it('23. ap_get_piece_props — schema includes all fields regardless of auth', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apGetPiecePropsTool(mcp, mockLog).execute({
            pieceName: '@activepieces/piece-test-email',
            actionOrTriggerName: 'send_email',
            type: 'action',
        })

        expect(text(result)).toContain('✅')
        expect(text(result)).toContain('folder')
        expect(text(result)).toContain('DROPDOWN')
        expect(text(result)).toContain('to')
        expect(text(result)).toContain('subject')
    })

    it('24. ap_get_piece_props — with auth on piece with no dropdowns returns clean schema', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apGetPiecePropsTool(mcp, mockLog).execute({
            pieceName: '@activepieces/piece-test-email',
            actionOrTriggerName: 'new_email',
            type: 'trigger',
            auth: 'fake-connection-id',
        })

        expect(text(result)).toContain('✅')
        expect(text(result)).not.toContain('DROPDOWN')
        expect(text(result)).not.toContain('ap_resolve_property_options')
    })

    it('25. ap_get_piece_props — with auth and invalid piece returns error before resolution', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apGetPiecePropsTool(mcp, mockLog).execute({
            pieceName: '@activepieces/piece-nonexistent',
            actionOrTriggerName: 'fake_action',
            type: 'action',
            auth: 'some-connection',
        })

        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('not found')
    })

    it('26. ap_get_piece_props — with auth and invalid action returns error with available list', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apGetPiecePropsTool(mcp, mockLog).execute({
            pieceName: '@activepieces/piece-test-email',
            actionOrTriggerName: 'nonexistent_action',
            type: 'action',
            auth: 'some-connection',
        })

        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('not found')
        expect(text(result)).toContain('send_email')
    })

    it('27. ap_get_piece_props — static fields always present regardless of auth parameter', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apGetPiecePropsTool(mcp, mockLog).execute({
            pieceName: '@activepieces/piece-test-email',
            actionOrTriggerName: 'send_email',
            type: 'action',
        })

        expect(text(result)).toContain('to')
        expect(text(result)).toContain('subject')
        expect(text(result)).toContain('folder')
    })

    // ── Fix 1: Step output reference format ───────────────────────────

    it('28. ap_flow_structure — reference hint uses {{stepName[\'output\'].field}} bracket notation', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Reference Format Test')

        const result = await apFlowStructureTool(mcp, mockLog).execute({ flowId })
        const output = text(result)

        expect(output).toContain('{{stepName[\'output\'].field}}')
        expect(output).not.toContain('{{stepName.output.field}}')
    })

    it('29. ap_update_step — input description uses {{stepName[\'output\'].field}} bracket notation', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const tool = apUpdateStepTool({ mcp }, mockLog)
        const inputDesc = tool.inputSchema.input.description ?? ''

        expect(inputDesc).toContain('{{stepName[\'output\'].field}}')
        expect(inputDesc).not.toContain('{{stepName.output.field}}')
    })

    it('30. ap_update_trigger — input description uses {{stepName[\'output\'].field}} bracket notation', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const tool = apUpdateTriggerTool({ mcp }, mockLog)
        const inputDesc = tool.inputSchema.input.description ?? ''

        expect(inputDesc).toContain('{{stepName[\'output\'].field}}')
        expect(inputDesc).not.toContain('{{stepName.output.field}}')
    })

    it('31a. step with {{stepName.field}} references is accepted as valid', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Reference Behavior Test')

        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.CODE,
            displayName: 'Use Trigger Data',
        })

        const result = await apUpdateStepTool({ mcp }, mockLog).execute({
            flowId,
            stepName: 'step_1',
            sourceCode: 'export const code = async (inputs) => { return { email: inputs.email }; };',
            input: { email: '{{trigger.body.email}}' },
        })

        expect(text(result)).toContain('✅')

        const validation = await apValidateFlowTool({ mcp }, mockLog).execute({ flowId })
        expect(text(validation)).toContain('✅')
        expect(text(validation)).toContain('ready to publish')
    })

    // ── Fix 2: Sample data preservation on trigger updates ────────────

    it('31. ap_update_trigger — partial update preserves existing input when same trigger', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Trigger Merge Test')

        await apUpdateTriggerTool({ mcp }, mockLog).execute({
            flowId,
            pieceName: '@activepieces/piece-test-email',
            triggerName: 'new_email',
        })

        const validAfterSet = await apValidateFlowTool({ mcp }, mockLog).execute({ flowId })
        expect(text(validAfterSet)).toContain('✅')

        const renameResult = await apUpdateTriggerTool({ mcp }, mockLog).execute({
            flowId,
            pieceName: '@activepieces/piece-test-email',
            triggerName: 'new_email',
            displayName: 'Renamed Trigger',
        })

        expect(text(renameResult)).toContain('✅')

        const validAfterRename = await apValidateFlowTool({ mcp }, mockLog).execute({ flowId })
        expect(text(validAfterRename)).toContain('✅')
    })

    it('32. ap_update_trigger — switching to different triggerName discards old input', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Trigger Switch Test')

        await apUpdateTriggerTool({ mcp }, mockLog).execute({
            flowId,
            pieceName: '@activepieces/piece-test-email',
            triggerName: 'new_email',
            input: { customField: 'should-be-discarded' },
        })

        const switchResult = await apUpdateTriggerTool({ mcp }, mockLog).execute({
            flowId,
            pieceName: '@activepieces/piece-test-email',
            triggerName: 'new_attachment',
        })
        expect(text(switchResult)).toContain('✅')

        const structure = await apFlowStructureTool(mcp, mockLog).execute({ flowId })
        expect(text(structure)).toContain('new_attachment')
        expect(text(structure)).not.toContain('new_email')
    })

    it('33. ap_update_trigger — additive input merge: new fields added without overwriting existing', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Additive Merge Test')

        await apUpdateTriggerTool({ mcp }, mockLog).execute({
            flowId,
            pieceName: '@activepieces/piece-test-email',
            triggerName: 'new_email',
            input: { folder: 'inbox' },
        })

        const addFieldResult = await apUpdateTriggerTool({ mcp }, mockLog).execute({
            flowId,
            pieceName: '@activepieces/piece-test-email',
            triggerName: 'new_email',
            input: { label: 'important' },
        })
        expect(text(addFieldResult)).toContain('✅')

        const stillValid = await apValidateFlowTool({ mcp }, mockLog).execute({ flowId })
        expect(text(stillValid)).toContain('✅')
    })

    // ── Fix 3: Dynamic property resolution ────────────────────────────

    it('34. ap_get_piece_props — DYNAMIC properties show note when refreshers not provided', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apGetPiecePropsTool(mcp, mockLog).execute({
            pieceName: '@activepieces/piece-test-dynamic',
            actionOrTriggerName: 'test_action',
            type: 'action',
        })

        const output = text(result)
        expect(output).toContain('✅')
        expect(output).toContain('DYNAMIC')
        expect(output).toContain('ap_get_piece_props')
        expect(output).not.toContain('dynamicFields')
    })

    it('35. ap_get_piece_props — input parameter is accepted without error', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apGetPiecePropsTool(mcp, mockLog).execute({
            pieceName: '@activepieces/piece-test-dynamic',
            actionOrTriggerName: 'test_action',
            type: 'action',
            input: { unrelated_key: 'value' },
        })

        expect(text(result)).toContain('✅')
        expect(text(result)).toContain('test_action')
    })

    it('36. ap_delete_step — description warns about sample data loss', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const tool = apDeleteStepTool({ mcp }, mockLog)

        expect(tool.description).toContain('sample data')
        expect(tool.description).toContain('ap_update_step')
    })

    // ── Real-world agent scenarios (from MCP comparison report) ───────

    it('37. Scenario 2 — Webhook → Code step: full 2-step flow built and validated', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Webhook to Code')

        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.CODE,
            displayName: 'Process Message',
        })

        await apUpdateStepTool({ mcp }, mockLog).execute({
            flowId,
            stepName: 'step_1',
            sourceCode: 'export const code = async (inputs) => { return { processed: true, from: inputs.sender }; };',
            input: { sender: '{{trigger.from}}' },
        })

        const validation = await apValidateFlowTool({ mcp }, mockLog).execute({ flowId })
        expect(text(validation)).toContain('✅')
        expect(text(validation)).toContain('ready to publish')
    })

    it('38. Scenario 3 — Loop iteration: trigger → code → loop → code inside loop', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Loop Flow')

        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.CODE,
            displayName: 'Build List',
        })

        await apUpdateStepTool({ mcp }, mockLog).execute({
            flowId,
            stepName: 'step_1',
            sourceCode: 'export const code = async () => { return { items: [1, 2, 3] }; };',
            input: {},
        })

        await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'step_1',
            stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER,
            stepType: FlowActionType.LOOP_ON_ITEMS,
            displayName: 'Loop Items',
        })

        await apUpdateStepTool({ mcp }, mockLog).execute({
            flowId,
            stepName: 'step_2',
            loopItems: '{{step_1.items}}',
        })

        await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'step_2',
            stepLocationRelativeToParent: StepLocationRelativeToParent.INSIDE_LOOP,
            stepType: FlowActionType.CODE,
            displayName: 'Process Item',
        })

        await apUpdateStepTool({ mcp }, mockLog).execute({
            flowId,
            stepName: 'step_3',
            sourceCode: 'export const code = async (inputs) => { return { doubled: inputs.val * 2 }; };',
            input: { val: '{{step_2.item}}' },
        })

        const validation = await apValidateFlowTool({ mcp }, mockLog).execute({ flowId })
        expect(text(validation)).toContain('✅')
        expect(text(validation)).toContain('ready to publish')
    })

    it('39. Scenario 5 — Loop + Router: multi-branch flow with cross-references', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Loop Router Flow')

        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.LOOP_ON_ITEMS,
            displayName: 'Loop',
        })

        await apUpdateStepTool({ mcp }, mockLog).execute({
            flowId,
            stepName: 'step_1',
            loopItems: '{{trigger.items}}',
        })

        await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'step_1',
            stepLocationRelativeToParent: StepLocationRelativeToParent.INSIDE_LOOP,
            stepType: FlowActionType.ROUTER,
            displayName: 'Priority Router',
        })

        await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'step_2',
            stepLocationRelativeToParent: StepLocationRelativeToParent.INSIDE_BRANCH,
            branchIndex: 0,
            stepType: FlowActionType.CODE,
            displayName: 'High Priority',
        })

        await apUpdateStepTool({ mcp }, mockLog).execute({
            flowId,
            stepName: 'step_3',
            sourceCode: 'export const code = async (inputs) => { return { priority: "high", item: inputs.item }; };',
            input: { item: '{{step_1.item}}' },
        })

        await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'step_2',
            stepLocationRelativeToParent: StepLocationRelativeToParent.INSIDE_BRANCH,
            branchIndex: 1,
            stepType: FlowActionType.CODE,
            displayName: 'Low Priority',
        })

        await apUpdateStepTool({ mcp }, mockLog).execute({
            flowId,
            stepName: 'step_4',
            sourceCode: 'export const code = async (inputs) => { return { priority: "low", item: inputs.item }; };',
            input: { item: '{{step_1.item}}' },
        })

        const structure = await apFlowStructureTool(mcp, mockLog).execute({ flowId })
        const output = text(structure)
        expect(output).toContain('Loop')
        expect(output).toContain('Priority Router')
        expect(output).toContain('High Priority')
        expect(output).toContain('Low Priority')
        expect(output).toContain('inside_loop')
        expect(output).toContain('branch 0')
        expect(output).toContain('branch 1')

        const validation = await apValidateFlowTool({ mcp }, mockLog).execute({ flowId })
        expect(text(validation)).toContain('✅')
        expect(text(validation)).toContain('ready to publish')
    })

    it('40. Scenario 6 — Full lifecycle: create → configure → validate → structure check', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Lifecycle Test')

        const emptyValidation = await apValidateFlowTool({ mcp }, mockLog).execute({ flowId })
        expect(text(emptyValidation)).toContain('⚠️')

        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.CODE,
            displayName: 'Transform',
        })

        await apUpdateStepTool({ mcp }, mockLog).execute({
            flowId,
            stepName: 'step_1',
            sourceCode: 'export const code = async () => { return { result: 42 * 2 }; };',
            input: {},
        })

        const validation = await apValidateFlowTool({ mcp }, mockLog).execute({ flowId })
        expect(text(validation)).toContain('✅')
        expect(text(validation)).toContain('ready to publish')
        expect(text(validation)).toContain('2 valid')

        const structure = await apFlowStructureTool(mcp, mockLog).execute({ flowId })
        expect(text(structure)).toContain('configured')
        expect(text(structure)).not.toContain('invalid')
        expect(text(structure)).not.toContain('unconfigured')
    })

    it('41. ap_get_piece_props — schema introspection returns field keys, types, and required status', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apGetPiecePropsTool(mcp, mockLog).execute({
            pieceName: '@activepieces/piece-test-email',
            actionOrTriggerName: 'send_email',
            type: 'action',
        })

        const output = text(result)
        expect(output).toContain('"name": "to"')
        expect(output).toContain('"required": true')
        expect(output).toContain('"type": "SHORT_TEXT"')
        expect(output).toContain('"name": "subject"')
        expect(output).toContain('"name": "folder"')
        expect(output).toContain('"type": "DROPDOWN"')
        expect(output).toContain('"required": false')
    })

    it('42. ap_validate_step_config — PIECE action with missing required fields returns specific field names', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apValidateStepConfigTool(mcp, mockLog).execute({
            stepType: 'PIECE_ACTION',
            pieceName: '@activepieces/piece-test-email',
            actionName: 'send_email',
            input: {},
        })

        const output = text(result)
        expect(output).toContain('to')
        expect(output).toContain('subject')
    })

    it('43. ap_list_flows — returns success response', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apListFlowsTool(mcp, mockLog).execute({})
        expect(text(result)).toContain('✅')
    })

    it('44. Trigger update repeatedly without losing config — simulates agent retry loop', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Retry Loop Test')

        await apUpdateTriggerTool({ mcp }, mockLog).execute({
            flowId,
            pieceName: '@activepieces/piece-test-email',
            triggerName: 'new_email',
        })

        for (let i = 0; i < 5; i++) {
            await apUpdateTriggerTool({ mcp }, mockLog).execute({
                flowId,
                pieceName: '@activepieces/piece-test-email',
                triggerName: 'new_email',
                displayName: `Attempt ${i + 1}`,
            })
        }

        const validation = await apValidateFlowTool({ mcp }, mockLog).execute({ flowId })
        expect(text(validation)).toContain('✅')

        const structure = await apFlowStructureTool(mcp, mockLog).execute({ flowId })
        expect(text(structure)).toContain('Attempt 5')
        expect(text(structure)).toContain('configured')
    })

    // ── ap_build_flow — batch flow creation ──────────────────────────

    it('45. ap_build_flow — creates trigger + CODE step, all valid', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apBuildFlowTool({ mcp }, mockLog).execute({
            flowName: 'Build Test 1',
            trigger: {
                pieceName: '@activepieces/piece-test-email',
                triggerName: 'new_email',
            },
            steps: [
                {
                    type: FlowActionType.CODE,
                    displayName: 'Process',
                    sourceCode: 'export const code = async () => { return { ok: true }; };',
                    input: {},
                },
            ],
        })

        expect(text(result)).toContain('✅')
        expect(text(result)).toContain('2 steps')
        expect(text(result)).toContain('all valid')
    })

    it('46. ap_build_flow — creates trigger + multiple steps in correct order', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apBuildFlowTool({ mcp }, mockLog).execute({
            flowName: 'Build Test 2',
            trigger: {
                pieceName: '@activepieces/piece-test-email',
                triggerName: 'new_email',
            },
            steps: [
                {
                    type: FlowActionType.CODE,
                    displayName: 'Step A',
                    sourceCode: 'export const code = async () => { return { a: 1 }; };',
                    input: {},
                },
                {
                    type: FlowActionType.CODE,
                    displayName: 'Step B',
                    sourceCode: 'export const code = async () => { return { b: 2 }; };',
                    input: {},
                },
                {
                    type: FlowActionType.LOOP_ON_ITEMS,
                    displayName: 'Loop',
                    loopItems: '{{step_1.items}}',
                },
            ],
        })

        expect(text(result)).toContain('✅')
        expect(text(result)).toContain('4 steps')

        const flowId = text(result).match(/\(id: (\S+?)\)/)?.[1]
        expect(flowId).toBeDefined()

        const structure = await apFlowStructureTool(mcp, mockLog).execute({ flowId: flowId! })
        const output = text(structure)
        expect(output).toContain('Step A')
        expect(output).toContain('Step B')
        expect(output).toContain('Loop')
        expect(output).toContain('step_1')
        expect(output).toContain('step_2')
        expect(output).toContain('step_3')
    })

    it('47. ap_build_flow — partial success: invalid steps reported', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apBuildFlowTool({ mcp }, mockLog).execute({
            flowName: 'Build Test Partial',
            trigger: {
                pieceName: '@activepieces/piece-test-email',
                triggerName: 'new_email',
            },
            steps: [
                {
                    type: FlowActionType.CODE,
                    displayName: 'Valid Code',
                    sourceCode: 'export const code = async () => { return {}; };',
                    input: {},
                },
                {
                    type: FlowActionType.PIECE,
                    displayName: 'Invalid Piece',
                    pieceName: '@activepieces/piece-test-email',
                },
            ],
        })

        expect(text(result)).toContain('⚠️')
        expect(text(result)).toContain('step_2')
        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)

        const result = await apBuildFlowTool({ mcp }, mockLog).execute({
            flowName: 'Build Test Empty',
            trigger: {
                pieceName: '@activepieces/piece-test-email',
                triggerName: 'new_email',
            },
            steps: [],
        })

        expect(text(result)).toContain('✅')
        expect(text(result)).toContain('1 step')
    })

    it('49. ap_build_flow — flow can be validated and published after creation', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apBuildFlowTool({ mcp }, mockLog).execute({
            flowName: 'Build Test Lifecycle',
            trigger: {
                pieceName: '@activepieces/piece-test-email',
                triggerName: 'new_email',
            },
            steps: [
                {
                    type: FlowActionType.CODE,
                    displayName: 'Compute',
                    sourceCode: 'export const code = async () => { return { x: 42 }; };',
                    input: {},
                },
            ],
        })

        expect(text(result)).toContain('✅')
        const flowId = text(result).match(/\(id: (\S+?)\)/)?.[1]
        expect(flowId).toBeDefined()

        const validation = await apValidateFlowTool({ mcp }, mockLog).execute({ flowId: flowId! })
        expect(text(validation)).toContain('✅')
        expect(text(validation)).toContain('ready to publish')
    })

    // ── ap_flow_structure — step input visibility ────────────────────

    it('50. ap_flow_structure — shows CODE step sourceCode and input in output', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Structure Input Test')

        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.CODE,
            displayName: 'My Code',
        })

        await apUpdateStepTool({ mcp }, mockLog).execute({
            flowId,
            stepName: 'step_1',
            sourceCode: 'export const code = async (inputs) => { return { msg: inputs.name }; };',
            input: { name: '{{trigger.from}}' },
        })

        const result = await apFlowStructureTool(mcp, mockLog).execute({ flowId })
        const output = text(result)

        expect(output).toContain('sourceCode:')
        expect(output).toContain('inputs.name')
        expect(output).toContain('input:')
        expect(output).toContain('{{trigger[\'output\'].from}}')
    })

    it('51. ap_flow_structure — shows LOOP step loopItems expression', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Loop Items Visibility Test')

        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.LOOP_ON_ITEMS,
            displayName: 'My Loop',
        })

        await apUpdateStepTool({ mcp }, mockLog).execute({
            flowId,
            stepName: 'step_1',
            loopItems: '{{trigger.items}}',
        })

        const result = await apFlowStructureTool(mcp, mockLog).execute({ flowId })
        const output = text(result)

        expect(output).toContain('loopItems: {{trigger[\'output\'].items}}')
    })

    it('52. ap_flow_structure — shows router branch conditions', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Router Condition Visibility Test')

        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.ROUTER,
            displayName: 'My Router',
        })

        await apAddBranchTool({ mcp }, mockLog).execute({
            flowId,
            routerStepName: 'step_1',
            branchName: 'VIP',
            conditions: [[{
                firstValue: '{{trigger.type}}',
                operator: 'TEXT_EXACTLY_MATCHES',
                secondValue: 'vip',
            }]],
        })

        const result = await apFlowStructureTool(mcp, mockLog).execute({ flowId })
        const output = text(result)

        expect(output).toContain('VIP')
        expect(output).toContain('conditions:')
        expect(output).toContain('{{trigger[\'output\'].type}}')
        expect(output).toContain('TEXT_EXACTLY_MATCHES')
        expect(output).toContain('vip')
    })

    // ── ap_duplicate_flow ────────────────────────────────────────────

    it('53. ap_duplicate_flow — duplicates a flow with all steps preserved', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Original Flow')

        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.CODE,
            displayName: 'Transform',
        })

        await apUpdateStepTool({ mcp }, mockLog).execute({
            flowId,
            stepName: 'step_1',
            sourceCode: 'export const code = async () => { return { x: 42 }; };',
            input: {},
        })

        const dupResult = await apDuplicateFlowTool({ mcp }, mockLog).execute({ flowId })
        const dupOutput = text(dupResult)

        expect(dupOutput).toContain('✅')
        expect(dupOutput).toContain('Copy of Original Flow')

        const copyFlowId = dupOutput.match(/Copy: ".*?" \(id: (\S+?)\)/)?.[1]
        expect(copyFlowId).toBeDefined()

        const structure = await apFlowStructureTool(mcp, mockLog).execute({ flowId: copyFlowId! })
        const structOutput = text(structure)
        expect(structOutput).toContain('Copy of Original Flow')
        expect(structOutput).toContain('step_1')
        expect(structOutput).toContain('Transform')
        expect(structOutput).toContain('configured')
    })

    it('54. ap_duplicate_flow — uses custom name when provided', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Source Flow')

        const dupResult = await apDuplicateFlowTool({ mcp }, mockLog).execute({
            flowId,
            name: 'My Custom Copy',
        })

        expect(text(dupResult)).toContain('✅')
        expect(text(dupResult)).toContain('My Custom Copy')
    })

    it('55. ap_duplicate_flow — returns error for non-existent flow', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apDuplicateFlowTool({ mcp }, mockLog).execute({ flowId: 'nonexistent123' })

        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('not found')
    })

    it('56. ap_duplicate_flow — original flow is not modified', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Immutable Original')

        await apUpdateTriggerTool({ mcp }, mockLog).execute({
            flowId,
            pieceName: '@activepieces/piece-test-email',
            triggerName: 'new_email',
        })

        const structBefore = text(await apFlowStructureTool(mcp, mockLog).execute({ flowId }))

        await apDuplicateFlowTool({ mcp }, mockLog).execute({ flowId })

        const structAfter = text(await apFlowStructureTool(mcp, mockLog).execute({ flowId }))

        expect(structAfter).toContain('Immutable Original')
        expect(structBefore).toEqual(structAfter)
    })

    it('57. ap_duplicate_flow — preserves router with branches and steps inside', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Router Dup Source')

        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.ROUTER,
            displayName: 'My Router',
        })

        await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'step_1',
            stepLocationRelativeToParent: StepLocationRelativeToParent.INSIDE_BRANCH,
            branchIndex: 0,
            stepType: FlowActionType.CODE,
            displayName: 'Branch Code',
        })

        await apUpdateStepTool({ mcp }, mockLog).execute({
            flowId,
            stepName: 'step_2',
            sourceCode: 'export const code = async () => { return { branch: true }; };',
            input: {},
        })

        const dupResult = await apDuplicateFlowTool({ mcp }, mockLog).execute({ flowId })
        const copyFlowId = text(dupResult).match(/Copy: ".*?" \(id: (\S+?)\)/)?.[1]
        expect(copyFlowId).toBeDefined()

        const structure = await apFlowStructureTool(mcp, mockLog).execute({ flowId: copyFlowId! })
        const output = text(structure)
        expect(output).toContain('My Router')
        expect(output).toContain('ROUTER')
        expect(output).toContain('Branch Code')
        expect(output).toContain('branch 0')
    })

    // ── ap_update_branch ─────────────────────────────────────────────

    it('58. ap_update_branch — sets conditions on a branch', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Update Branch Test')

        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.ROUTER,
            displayName: 'My Router',
        })

        const result = await apUpdateBranchTool({ mcp }, mockLog).execute({
            flowId,
            routerStepName: 'step_1',
            branchIndex: 0,
            branchName: 'VIP Branch',
            conditions: [[{
                firstValue: '{{trigger.type}}',
                operator: 'TEXT_EXACTLY_MATCHES',
                secondValue: 'vip',
            }]],
        })

        expect(text(result)).toContain('✅')
        expect(text(result)).toContain('VIP Branch')
        expect(text(result)).toContain('1 OR group')

        const structure = await apFlowStructureTool(mcp, mockLog).execute({ flowId })
        const output = text(structure)
        expect(output).toContain('VIP Branch')
        expect(output).toContain('{{trigger[\'output\'].type}}')
        expect(output).toContain('TEXT_EXACTLY_MATCHES')
    })

    it('59. ap_update_branch — renames a branch without changing conditions', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Rename Branch Test')

        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.ROUTER,
            displayName: 'My Router',
        })

        const result = await apUpdateBranchTool({ mcp }, mockLog).execute({
            flowId,
            routerStepName: 'step_1',
            branchIndex: 0,
            branchName: 'Renamed Branch',
        })

        expect(text(result)).toContain('✅')
        expect(text(result)).toContain('Renamed Branch')

        const structure = await apFlowStructureTool(mcp, mockLog).execute({ flowId })
        expect(text(structure)).toContain('Renamed Branch')
    })

    it('60. ap_update_branch — rejects setting conditions on fallback branch', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Fallback Guard Test')

        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.ROUTER,
            displayName: 'My Router',
        })

        // Branch 1 is the fallback (Otherwise)
        const result = await apUpdateBranchTool({ mcp }, mockLog).execute({
            flowId,
            routerStepName: 'step_1',
            branchIndex: 1,
            conditions: [[{ firstValue: 'test', operator: 'EXISTS' }]],
        })

        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('fallback')
    })

    it('61. ap_update_branch — allows renaming the fallback branch', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Fallback Rename Test')

        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.ROUTER,
            displayName: 'My Router',
        })

        const result = await apUpdateBranchTool({ mcp }, mockLog).execute({
            flowId,
            routerStepName: 'step_1',
            branchIndex: 1,
            branchName: 'Default Case',
        })

        expect(text(result)).toContain('✅')
        expect(text(result)).toContain('Default Case')
    })

    it('62. ap_update_branch — rejects non-router step', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Non-Router Test')

        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.CODE,
            displayName: 'My Code',
        })

        const result = await apUpdateBranchTool({ mcp }, mockLog).execute({
            flowId,
            routerStepName: 'step_1',
            branchIndex: 0,
            branchName: 'Test',
        })

        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('not a ROUTER')
    })

    it('63. ap_update_branch — rejects out-of-range branch index', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'OOB Index Test')

        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.ROUTER,
            displayName: 'My Router',
        })

        const result = await apUpdateBranchTool({ mcp }, mockLog).execute({
            flowId,
            routerStepName: 'step_1',
            branchIndex: 99,
            branchName: 'Test',
        })

        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('out of range')
    })

    it('64. ap_update_branch — rejects empty update (no name or conditions)', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Empty Update Test')

        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.ROUTER,
            displayName: 'My Router',
        })

        const result = await apUpdateBranchTool({ mcp }, mockLog).execute({
            flowId,
            routerStepName: 'step_1',
            branchIndex: 0,
        })

        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('Nothing to update')
    })

    it('65. ap_update_branch — preserves steps inside the branch after condition update', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Preserve Steps Test')

        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.ROUTER,
            displayName: 'My Router',
        })

        await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'step_1',
            stepLocationRelativeToParent: StepLocationRelativeToParent.INSIDE_BRANCH,
            branchIndex: 0,
            stepType: FlowActionType.CODE,
            displayName: 'Inner Code',
        })

        await apUpdateStepTool({ mcp }, mockLog).execute({
            flowId,
            stepName: 'step_2',
            sourceCode: 'export const code = async () => { return { inside: true }; };',
            input: {},
        })

        // Update the branch conditions — step_2 should survive
        await apUpdateBranchTool({ mcp }, mockLog).execute({
            flowId,
            routerStepName: 'step_1',
            branchIndex: 0,
            branchName: 'Updated Branch',
            conditions: [[{
                firstValue: '{{trigger.status}}',
                operator: 'TEXT_EXACTLY_MATCHES',
                secondValue: 'active',
            }]],
        })

        const structure = await apFlowStructureTool(mcp, mockLog).execute({ flowId })
        const output = text(structure)

        expect(output).toContain('Updated Branch')
        expect(output).toContain('Inner Code')
        expect(output).toContain('step_2')
        expect(output).toContain('branch 0')
        expect(output).toContain('{{trigger[\'output\'].status}}')
    })

    it('66. ap_update_branch — handles complex multi-group conditions', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Complex Conditions Test')

        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.ROUTER,
            displayName: 'Complex Router',
        })

        // Set conditions with 2 OR groups, first group has 2 AND conditions
        const result = await apUpdateBranchTool({ mcp }, mockLog).execute({
            flowId,
            routerStepName: 'step_1',
            branchIndex: 0,
            conditions: [
                [
                    { firstValue: '{{trigger.status}}', operator: 'TEXT_EXACTLY_MATCHES', secondValue: 'active' },
                    { firstValue: '{{trigger.role}}', operator: 'TEXT_CONTAINS', secondValue: 'admin' },
                ],
                [
                    { firstValue: '{{trigger.override}}', operator: 'EXISTS' },
                ],
            ],
        })

        expect(text(result)).toContain('✅')
        expect(text(result)).toContain('2 OR group')

        const structure = await apFlowStructureTool(mcp, mockLog).execute({ flowId })
        const output = text(structure)
        expect(output).toContain('TEXT_EXACTLY_MATCHES')
        expect(output).toContain('TEXT_CONTAINS')
        expect(output).toContain('AND')
        expect(output).toContain('OR')
        expect(output).toContain('EXISTS')
    })

    // ── ARRAY item schema exposure ───────────────────────────────────

    it('67. ap_get_piece_props — ARRAY property includes item sub-schemas', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apGetPiecePropsTool(mcp, mockLog).execute({
            pieceName: '@activepieces/piece-test-array',
            actionOrTriggerName: 'action_with_array',
            type: 'action',
        })

        const output = text(result)
        expect(output).toContain('✅')
        expect(output).toContain('ARRAY')
        expect(output).toContain('"items"')
        expect(output).toContain('"name": "name"')
        expect(output).toContain('"name": "value"')
        expect(output).toContain('SHORT_TEXT')
        expect(output).toContain('NUMBER')
    })

    // ── ap_list_flows with filters ───────────────────────────────────

    it('68. ap_list_flows — respects limit parameter', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        await apCreateFlowTool({ mcp }, mockLog).execute({ flowName: 'Flow 1' })
        await apCreateFlowTool({ mcp }, mockLog).execute({ flowName: 'Flow 2' })
        await apCreateFlowTool({ mcp }, mockLog).execute({ flowName: 'Flow 3' })

        const result = await apListFlowsTool(mcp, mockLog).execute({ limit: 2 })
        const output = text(result)

        expect(output).toContain('✅')
        expect(output).toContain('2 flow(s)')
    })

    it('69. ap_list_flows — filters by name', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        await apCreateFlowTool({ mcp }, mockLog).execute({ flowName: 'Alpha Flow' })
        await apCreateFlowTool({ mcp }, mockLog).execute({ flowName: 'Beta Flow' })
        await apCreateFlowTool({ mcp }, mockLog).execute({ flowName: 'Alpha Two' })

        const result = await apListFlowsTool(mcp, mockLog).execute({ name: 'Alpha' })
        const output = text(result)

        expect(output).toContain('filtered')
        expect(output).toContain('Alpha')
        expect(output).not.toContain('Beta Flow')
    })

    // ── ROUTER validation UX ─────────────────────────────────────────

    it('70. ap_validate_step_config — ROUTER with empty settings gives helpful example', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apValidateStepConfigTool(mcp, mockLog).execute({
            stepType: 'ROUTER',
        })

        const output = text(result)
        expect(output).toContain('⚠️')
        expect(output).toContain('executionType')
        expect(output).toContain('EXECUTE_FIRST_MATCH')
        expect(output).toContain('CONDITION')
        expect(output).toContain('FALLBACK')
    })

    it('71. ap_validate_step_config — ROUTER with valid settings passes', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apValidateStepConfigTool(mcp, mockLog).execute({
            stepType: 'ROUTER',
            settings: {
                branches: [
                    { branchName: 'B1', branchType: 'CONDITION', conditions: [[{ firstValue: '{{trigger.x}}', operator: 'EXISTS' }]] },
                    { branchName: 'Otherwise', branchType: 'FALLBACK' },
                ],
                executionType: 'EXECUTE_FIRST_MATCH',
            },
        })

        expect(text(result)).toContain('✅')
    })

    // ── Published flow warning ────────────────────────────────────────

    it('72. ap_add_step — warns when flow is published', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Published Flow Test')

        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.CODE,
            displayName: 'Pre-publish Code',
        })

        await apUpdateStepTool({ mcp }, mockLog).execute({
            flowId,
            stepName: 'step_1',
            sourceCode: 'export const code = async () => { return { ok: true }; };',
            input: {},
        })

        await apLockAndPublishTool({ mcp }, mockLog).execute({ flowId })

        const result = await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'step_1',
            stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER,
            stepType: FlowActionType.CODE,
            displayName: 'Post-publish Code',
        })

        expect(text(result)).toContain('published')
        expect(text(result)).toContain('draft')
        expect(text(result)).toContain('ap_lock_and_publish')
    })

    // ── Error sanitization ───────────────────────────────────────────

    it('73. mcpToolError — sanitizes internal paths from error messages', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        // Simulate what mcpUtils.mcpToolError does with internal paths
        const fakeError = new Error('Cannot find module at /root/codes/abc123/step_1/index.js and /root/common/node_modules/.bun/@[email protected]/lib.js')
        const result = mcpUtils.mcpToolError('Test', fakeError)
        const output = text(result)

        expect(output).not.toContain('/root/codes/')
        expect(output).not.toContain('/root/common/')
        expect(output).not.toContain('.bun/')
        expect(output).toContain('<sandbox>')
        expect(output).toContain('<internal>')
    })

    // ── Router branch condition validation ───────────────────────────

    it('74. ap_update_branch — rejects empty firstValue', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Empty firstValue')

        await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'trigger',
            stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER,
            stepType: FlowActionType.ROUTER,
            displayName: 'Router',
        })

        const result = await apUpdateBranchTool({ mcp }, mockLog).execute({
            flowId,
            routerStepName: 'step_1',
            branchIndex: 0,
            conditions: [[{ firstValue: '', secondValue: 'urgent', operator: 'TEXT_CONTAINS' }]],
        })

        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('firstValue')
    })

    it('75. ap_update_branch — rejects empty secondValue with non-single-value operator', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Empty secondValue')

        await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'trigger',
            stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER,
            stepType: FlowActionType.ROUTER,
            displayName: 'Router',
        })

        const result = await apUpdateBranchTool({ mcp }, mockLog).execute({
            flowId,
            routerStepName: 'step_1',
            branchIndex: 0,
            conditions: [[{ firstValue: '{{trigger.subject}}', secondValue: '', operator: 'TEXT_CONTAINS' }]],
        })

        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('secondValue')
    })

    it('76. ap_update_branch — rejects missing secondValue with non-single-value operator', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Missing secondValue')

        await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'trigger',
            stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER,
            stepType: FlowActionType.ROUTER,
            displayName: 'Router',
        })

        const result = await apUpdateBranchTool({ mcp }, mockLog).execute({
            flowId,
            routerStepName: 'step_1',
            branchIndex: 0,
            conditions: [[{ firstValue: '{{trigger.subject}}', operator: 'TEXT_CONTAINS' }]],
        })

        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('secondValue')
        expect(text(result)).toContain('TEXT_CONTAINS')
    })

    it('77. ap_update_branch — accepts single-value operator without secondValue', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'EXISTS works')

        await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'trigger',
            stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER,
            stepType: FlowActionType.ROUTER,
            displayName: 'Router',
        })

        const result = await apUpdateBranchTool({ mcp }, mockLog).execute({
            flowId,
            routerStepName: 'step_1',
            branchIndex: 0,
            conditions: [[{ firstValue: '{{trigger.subject}}', operator: 'EXISTS' }]],
        })

        expect(text(result)).toContain('✅')
        expect(text(result)).not.toContain('Incomplete')
        expect(text(result)).not.toContain('invalid')
    })

    it('78. ap_add_branch — rejects empty firstValue at input layer', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'AddBranch firstValue')

        await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'trigger',
            stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER,
            stepType: FlowActionType.ROUTER,
            displayName: 'Router',
        })

        const result = await apAddBranchTool({ mcp }, mockLog).execute({
            flowId,
            routerStepName: 'step_1',
            branchName: 'New',
            conditions: [[{ firstValue: '', operator: 'EXISTS' }]],
        })

        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('firstValue')
    })

    it('79. ap_update_branch — rejects secondValue provided without operator', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'secondValue without operator')

        await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'trigger',
            stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER,
            stepType: FlowActionType.ROUTER,
            displayName: 'Router',
        })

        const result = await apUpdateBranchTool({ mcp }, mockLog).execute({
            flowId,
            routerStepName: 'step_1',
            branchIndex: 0,
            conditions: [[{ firstValue: '{{trigger.subject}}', secondValue: 'urgent' }]],
        })

        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('operator')
    })

    it('80. ap_list_runs — defaults environment to PRODUCTION when no flowId is given', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const flowId = await createFlowAndGetId(mcp, 'Run Listing Defaults')
        const flowVersion = await db.findOneByOrFail<{ id: string }>('flow_version', { flowId })

        const prodRunId = apId()
        const testRunId = apId()
        await db.save('flow_run', [
            {
                id: prodRunId,
                projectId: ctx.project.id,
                flowId,
                flowVersionId: flowVersion.id,
                environment: RunEnvironment.PRODUCTION,
                status: FlowRunStatus.SUCCEEDED,
                stepsCount: 0,
                failParentOnFailure: true,
            },
            {
                id: testRunId,
                projectId: ctx.project.id,
                flowId,
                flowVersionId: flowVersion.id,
                environment: RunEnvironment.TESTING,
                status: FlowRunStatus.SUCCEEDED,
                stepsCount: 0,
                failParentOnFailure: true,
            },
        ])

        const result = await apListRunsTool(mcp, mockLog).execute({})

        expect(text(result)).toContain(prodRunId)
        expect(text(result)).not.toContain(testRunId)
    })

    it('81. ap_list_runs — caller-supplied environment overrides the PRODUCTION default', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const flowId = await createFlowAndGetId(mcp, 'Run Listing Override')
        const flowVersion = await db.findOneByOrFail<{ id: string }>('flow_version', { flowId })

        const prodRunId = apId()
        const testRunId = apId()
        await db.save('flow_run', [
            {
                id: prodRunId,
                projectId: ctx.project.id,
                flowId,
                flowVersionId: flowVersion.id,
                environment: RunEnvironment.PRODUCTION,
                status: FlowRunStatus.SUCCEEDED,
                stepsCount: 0,
                failParentOnFailure: true,
            },
            {
                id: testRunId,
                projectId: ctx.project.id,
                flowId,
                flowVersionId: flowVersion.id,
                environment: RunEnvironment.TESTING,
                status: FlowRunStatus.SUCCEEDED,
                stepsCount: 0,
                failParentOnFailure: true,
            },
        ])

        const result = await apListRunsTool(mcp, mockLog).execute({ environment: RunEnvironment.TESTING })

        expect(text(result)).toContain(testRunId)
        expect(text(result)).not.toContain(prodRunId)
    })

    it('82. ap_get_run — surfaces a clear "purged" message when run is past retention', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const flowId = await createFlowAndGetId(mcp, 'Expired Run')
        const flowVersion = await db.findOneByOrFail<{ id: string }>('flow_version', { flowId })

        const expiredRunId = apId()
        await db.save('flow_run', {
            id: expiredRunId,
            projectId: ctx.project.id,
            flowId,
            flowVersionId: flowVersion.id,
            environment: RunEnvironment.PRODUCTION,
            status: FlowRunStatus.SUCCEEDED,
            stepsCount: 0,
            failParentOnFailure: true,
        })
        await db.update('flow_run', expiredRunId, { created: '2024-01-01T00:00:00.000Z' })

        const result = await apGetRunTool(mcp, mockLog).execute({ flowRunId: expiredRunId })
        const retentionDays = system.getNumberOrThrow(AppSystemProp.EXECUTION_DATA_RETENTION_DAYS)

        expect(text(result)).toContain('purged')
        expect(text(result)).toContain(`${retentionDays} days`)
    })

    it('83. ap_get_run — reports "still in progress" when a non-terminal run has no step data', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const flowId = await createFlowAndGetId(mcp, 'Running Run')
        const flowVersion = await db.findOneByOrFail<{ id: string }>('flow_version', { flowId })

        const runningRunId = apId()
        await db.save('flow_run', {
            id: runningRunId,
            projectId: ctx.project.id,
            flowId,
            flowVersionId: flowVersion.id,
            environment: RunEnvironment.PRODUCTION,
            status: FlowRunStatus.RUNNING,
            stepsCount: 0,
            failParentOnFailure: true,
        })

        const result = await apGetRunTool(mcp, mockLog).execute({ flowRunId: runningRunId })

        expect(text(result)).toContain('still in progress')
    })

    // ── ap_run_action ────────────────────────────────────────────────

    it('84. ap_run_action — returns error for non-existent piece', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apRunActionTool(mcp, mockLog).execute({
            pieceName: '@activepieces/piece-nonexistent',
            actionName: 'any_action',
            input: {},
        })

        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('not found')
        expect(text(result)).toContain('ap_research_pieces')
    })

    it('85. ap_run_action — returns error for non-existent action on a valid piece', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apRunActionTool(mcp, mockLog).execute({
            pieceName: '@activepieces/piece-test-array',
            actionName: 'action_that_does_not_exist',
            input: {},
        })

        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('not found')
        expect(text(result)).toContain('action_with_array')
    })

    it('86. ap_run_action — returns error when required input is missing', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apRunActionTool(mcp, mockLog).execute({
            pieceName: '@activepieces/piece-test-array',
            actionName: 'action_with_array',
            input: {},
        })

        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('Missing required inputs')
        expect(text(result)).toContain('items')
    })

    it.skip('87. ap_run_action — returns error when auth-required action has no connection', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apRunActionTool(mcp, mockLog).execute({
            pieceName: '@activepieces/piece-test-email',
            actionName: 'send_email',
            input: { to: '[email protected]', subject: 'hi' },
        })

        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('auth')
        expect(text(result)).toContain('ap_list_connections')
    })

    it.skip('88. ap_run_action — rejects connectionExternalId containing special characters', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apRunActionTool(mcp, mockLog).execute({
            pieceName: '@activepieces/piece-test-email',
            actionName: 'send_email',
            input: { to: '[email protected]', subject: 'hi' },
            connectionExternalId: 'bad\'; evil',
        })

        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('special characters')
    })

    it.skip('89. ap_run_action — accepts a plain connectionExternalId without validation error', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apRunActionTool(mcp, mockLog).execute({
            pieceName: '@activepieces/piece-test-email',
            actionName: 'send_email',
            input: { to: '[email protected]', subject: 'hi' },
            connectionExternalId: 'valid_external_id_123',
        })

        expect(text(result)).not.toContain('special characters')
    })

    // ── Private (CUSTOM) pieces visibility ───────────────────────────
    // MCP tools must resolve the caller's platformId so pieces created
    // on that platform (pieceType: CUSTOM) are discoverable. Without the
    // platformId filter, `pieceCache.filterPieceBasedOnType` drops them.

    it('90. ap_research_pieces — includes CUSTOM pieces belonging to the caller\'s platform', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const privatePiece = createMockPieceMetadata({
            name: '@activepieces/piece-private-custom',
            displayName: 'Private Custom Piece',
            version: '0.1.0',
            pieceType: PieceType.CUSTOM,
            packageType: PackageType.REGISTRY,
            platformId: ctx.platform.id,
            actions: {
                run: {
                    name: 'run',
                    displayName: 'Run',
                    description: 'Runs the private action',
                    requireAuth: false,
                    props: {},
                },
            },
            triggers: {},
        })
        await db.save('piece_metadata', privatePiece)

        const result = await apResearchPiecesTool(mcp, mockLog).execute({
            searchQuery: 'private-custom',
        })

        expect(text(result)).toContain('✅')
        expect(text(result)).toContain('@activepieces/piece-private-custom')
    })

    it('91. ap_get_piece_props — resolves CUSTOM pieces on the caller\'s platform via lookupPieceComponent', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const privatePiece = createMockPieceMetadata({
            name: '@activepieces/piece-private-lookup',
            displayName: 'Private Lookup Piece',
            version: '0.1.0',
            pieceType: PieceType.CUSTOM,
            packageType: PackageType.REGISTRY,
            platformId: ctx.platform.id,
            actions: {
                do_thing: {
                    name: 'do_thing',
                    displayName: 'Do Thing',
                    description: 'Does a thing on the private piece',
                    requireAuth: false,
                    props: {
                        note: { type: 'SHORT_TEXT', displayName: 'Note', required: false },
                    },
                },
            },
            triggers: {},
        })
        await db.save('piece_metadata', privatePiece)

        const result = await apGetPiecePropsTool(mcp, mockLog).execute({
            pieceName: '@activepieces/piece-private-lookup',
            actionOrTriggerName: 'do_thing',
            type: 'action',
        })

        // If the platformId resolution is broken, lookupPieceComponent returns
        // "Piece not found" here. With the fix, the schema is returned.
        expect(text(result)).not.toContain('not found')
        expect(text(result)).toContain('do_thing')
    })

    it('92. ap_research_pieces — does NOT include CUSTOM pieces from a different platform', async () => {
        // Two independent projects on two different platforms. Each platform's
        // private piece must stay invisible to the other.
        const ctxA = await createTestContext(app)
        const ctxB = await createTestContext(app)
        const mcpA = makeMcp(ctxA.project.id)

        const privateOfB = createMockPieceMetadata({
            name: '@activepieces/piece-private-only-b',
            displayName: 'Private Piece Only for Platform B',
            version: '0.1.0',
            pieceType: PieceType.CUSTOM,
            packageType: PackageType.REGISTRY,
            platformId: ctxB.platform.id,
            actions: {
                run: {
                    name: 'run',
                    displayName: 'Run',
                    description: 'Only visible on platform B',
                    requireAuth: false,
                    props: {},
                },
            },
            triggers: {},
        })
        await db.save('piece_metadata', privateOfB)

        const result = await apResearchPiecesTool(mcpA, mockLog).execute({
            searchQuery: 'private-only-b',
        })

        // Require the call to have succeeded (not errored) — otherwise an error response
        // (which also wouldn't contain the piece name) would falsely pass. A cross-platform
        // piece is invisible here, so the correct successful result is "no pieces matched".
        expect(text(result)).not.toContain('❌')
        expect(text(result)).not.toContain('@activepieces/piece-private-only-b')
    })

    it('93. ap_research_pieces — with an intent, only the matching actions and triggers carry their full description', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const component = ({ name, displayName, description, aiDescription }: { name: string, displayName: string, description: string, aiDescription: string }) => ({ name, displayName, description, requireAuth: false, props: {}, aiMetadata: { description: aiDescription } })
        const trigger = (fields: Parameters<typeof component>[0]) => ({ ...component(fields), type: TriggerStrategy.POLLING, sampleData: {}, testStrategy: TriggerTestStrategy.SIMULATION })
        await db.save('piece_metadata', createMockPieceMetadata({
            name: '@activepieces/piece-intent-mail',
            displayName: 'Intent Mail',
            version: '0.1.0',
            pieceType: PieceType.CUSTOM,
            packageType: PackageType.REGISTRY,
            platformId: ctx.platform.id,
            actions: {
                send_email: component({ name: 'send_email', displayName: 'Send Email', description: 'Send an email to a recipient', aiDescription: 'AI hint for sending email' }),
                archive_thread: component({ name: 'archive_thread', displayName: 'Archive Thread', description: 'Move a thread out of the inbox', aiDescription: 'AI hint for archiving' }),
            },
            triggers: {
                new_email: trigger({ name: 'new_email', displayName: 'New Email', description: 'Fires when an email arrives', aiDescription: 'AI hint for incoming email' }),
                new_label: trigger({ name: 'new_label', displayName: 'New Label', description: 'Fires when a label is created', aiDescription: 'AI hint for labels' }),
            },
        }))

        const matched = text(await apResearchPiecesTool(mcp, mockLog).execute({ pieceNames: ['@activepieces/piece-intent-mail'], forIntent: 'send an email' }))
        const unmatched = text(await apResearchPiecesTool(mcp, mockLog).execute({ pieceNames: ['@activepieces/piece-intent-mail'], forIntent: 'translate a document' }))
        const noIntent = text(await apResearchPiecesTool(mcp, mockLog).execute({ pieceNames: ['@activepieces/piece-intent-mail'] }))

        expect(matched).toContain('AI hint for sending email')
        expect(matched).toContain('AI hint for incoming email')
        expect(matched).toContain('archive_thread')
        expect(matched).not.toContain('AI hint for archiving')
        expect(matched).not.toContain('AI hint for labels')
        expect(unmatched).toContain('new_label')
        expect(unmatched).not.toContain('AI hint')
        expect(noIntent).toContain('AI hint for archiving')
        expect(noIntent).toContain('AI hint for labels')
    })

    // ── Flow attribution (createdBy / ownerId) ───────────────────────

    it('ap_create_flow — stamps createdBy=MCP and ownerId=connected user', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apCreateFlowTool({ mcp, userId: ctx.user.id }, mockLog).execute({ flowName: 'Attributed Flow' })
        const flowId = text(result).match(/\(id: (\S+?)\)/)?.[1]
        const flow = await flowService(mockLog).getOnePopulatedOrThrow({ id: flowId!, projectId: ctx.project.id })

        expect(flow.createdBy).toEqual({ type: FlowCreatorType.MCP, id: mcp.id })
        expect(flow.ownerId).toBe(ctx.user.id)
    })

    it('ap_build_flow — stamps createdBy=MCP and ownerId=connected user', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apBuildFlowTool({ mcp, userId: ctx.user.id }, mockLog).execute({
            flowName: 'Built Attributed Flow',
            trigger: { pieceName: '@activepieces/piece-test-email', triggerName: 'new_email' },
            steps: [],
        })
        const flowId = text(result).match(/\(id: (\S+?)\)/)?.[1]
        const flow = await flowService(mockLog).getOnePopulatedOrThrow({ id: flowId!, projectId: ctx.project.id })

        expect(flow.createdBy).toEqual({ type: FlowCreatorType.MCP, id: mcp.id })
        expect(flow.ownerId).toBe(ctx.user.id)
    })

    it('ap_duplicate_flow — copy inherits MCP attribution, not the source flow owner', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const context = { mcp, userId: ctx.user.id }
        const sourceResult = await apCreateFlowTool(context, mockLog).execute({ flowName: 'Dup Source' })
        const sourceId = text(sourceResult).match(/\(id: (\S+?)\)/)?.[1]

        const dupResult = await apDuplicateFlowTool(context, mockLog).execute({ flowId: sourceId!, name: 'Dup Copy' })
        const copyId = text(dupResult).match(/Copy: ".*?" \(id: (\S+?)\)/)?.[1]
        const copy = await flowService(mockLog).getOnePopulatedOrThrow({ id: copyId!, projectId: ctx.project.id })

        expect(copy.createdBy).toEqual({ type: FlowCreatorType.MCP, id: mcp.id })
        expect(copy.ownerId).toBe(ctx.user.id)
    })

    it('REST POST /v1/flows — createdBy is null (human-created)', async () => {
        const ctx = await createTestContext(app)

        const response = await ctx.post('/v1/flows', {
            displayName: 'Hand-built Flow',
            projectId: ctx.project.id,
        }, { query: { projectId: ctx.project.id } })

        expect(response.statusCode).toBe(StatusCodes.CREATED)
        expect(response.json().createdBy ?? null).toBeNull()
    })

    it('REST POST /v1/flows — createdBy cannot be injected through the request body', async () => {
        const ctx = await createTestContext(app)

        const response = await ctx.post('/v1/flows', {
            displayName: 'Spoof Attempt',
            projectId: ctx.project.id,
            createdBy: { type: FlowCreatorType.MCP, id: apId() },
        }, { query: { projectId: ctx.project.id } })

        expect(response.statusCode).toBe(StatusCodes.CREATED)
        const flow = await flowService(mockLog).getOnePopulatedOrThrow({ id: response.json().id, projectId: ctx.project.id })
        expect(flow.createdBy ?? null).toBeNull()
    })

    it('ap_read_step_settings — returns full untruncated input for a PIECE step', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Read Settings Flow')

        const longValue = 'recipient-'.repeat(80)
        await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'trigger',
            stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER,
            stepType: FlowActionType.PIECE,
            displayName: 'Send Email',
            pieceName: '@activepieces/piece-test-email',
            actionName: 'send_email',
            input: { to: longValue, subject: 'Hello' },
        })

        const structure = await apFlowStructureTool(mcp, mockLog).execute({ flowId })
        expect(text(structure)).toContain('(truncated)')
        expect(text(structure)).not.toContain(longValue)

        const result = await apReadStepSettingsTool(mcp, mockLog).execute({ flowId, stepName: 'step_1' })
        expect(text(result)).not.toContain('❌')
        expect(text(result)).toContain(longValue)
        expect(text(result)).toContain('send_email')
    })

    it('ap_read_step_settings — returns sourceCode and packageJson for a CODE step', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Read Code Settings Flow')

        const sourceCode = 'export const code = async (inputs) => { return inputs.value * 2 }'
        await apAddStepTool({ mcp }, mockLog).execute({
            flowId,
            parentStepName: 'trigger',
            stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER,
            stepType: FlowActionType.CODE,
            displayName: 'Double It',
            sourceCode,
            input: { value: '{{trigger}}' },
        })

        const result = await apReadStepSettingsTool(mcp, mockLog).execute({ flowId, stepName: 'step_1' })
        expect(text(result)).not.toContain('❌')
        expect(text(result)).toContain('inputs.value * 2')
        expect(text(result)).toContain('packageJson')
    })

    it('ap_read_step_settings — reads the trigger step', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Read Trigger Settings Flow')

        const result = await apReadStepSettingsTool(mcp, mockLog).execute({ flowId, stepName: 'trigger' })
        expect(text(result)).not.toContain('❌')
        expect(text(result)).toContain('EMPTY')
        expect(text(result)).toContain('ap_update_trigger')
    })

    it('ap_read_step_settings — unknown step returns available step names', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Read Missing Step Flow')

        const result = await apReadStepSettingsTool(mcp, mockLog).execute({ flowId, stepName: 'step_99' })
        expect(text(result)).toContain('❌')
        expect(text(result)).toContain('Available steps')
        expect(text(result)).toContain('trigger')
    })

    it('ap_read_step_settings — cannot read a flow from another project', async () => {
        const ctx1 = await createTestContext(app)
        const ctx2 = await createTestContext(app)
        const mcp2 = makeMcp(ctx2.project.id)
        const flowId = await createFlowAndGetId(mcp2, 'Other Project Flow')

        const mcp1 = makeMcp(ctx1.project.id)
        const result = await apReadStepSettingsTool(mcp1, mockLog).execute({ flowId, stepName: 'trigger' })
        expect(text(result)).toContain('❌ Flow not found')
    })

    it('ap_create_flow, ap_build_flow and ap_create_table place a solution in one folder and return each flow externalId', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        await apCreateFolderTool(mcp, mockLog).execute({ folderName: 'Order intake' })
        const created = await apCreateFlowTool({ mcp }, mockLog).execute({ flowName: 'Enrich customer', folderName: 'Order intake' })
        const built = await apBuildFlowTool({ mcp }, mockLog).execute({
            flowName: 'Receive order',
            folderName: 'order INTAKE',
            trigger: { pieceName: '@activepieces/piece-test-email', triggerName: 'new_email' },
            steps: [{ type: FlowActionType.CODE, displayName: 'Process', sourceCode: 'export const code = async () => { return { ok: true }; };', input: {} }],
        })

        const tableResult = await apCreateTableTool(mcp, mockLog).execute({
            name: 'Orders',
            folderName: 'Order intake',
            fields: [{ name: 'Order id', type: 'TEXT' }],
        })

        const flowContent = z.object({ flowId: z.string(), externalId: z.string(), folderName: z.string() })
        const createdContent = structured({ result: created, schema: flowContent })
        const builtContent = structured({ result: built, schema: flowContent })
        const tableId = structured({ result: tableResult, schema: z.object({ id: z.string() }) }).id
        const table = await tableService.getOneOrThrow({ id: tableId, projectId: ctx.project.id })
        const createdFlow = await flowService(mockLog).getOne({ id: createdContent.flowId, projectId: ctx.project.id })
        const builtFlow = await flowService(mockLog).getOne({ id: builtContent.flowId, projectId: ctx.project.id })

        expect(createdFlow?.folderId).toBeTruthy()
        expect(builtFlow?.folderId).toBe(createdFlow?.folderId)
        expect(table.folderId).toBe(createdFlow?.folderId)
        expect(createdContent.externalId).toBe(createdFlow?.externalId)
        expect(builtContent.externalId).toBe(builtFlow?.externalId)
        expect(builtContent.folderName).toBe('Order intake')
        expect(text(created)).toContain('in folder "Order intake"')
        expect(text(built)).toContain(`externalId ${builtFlow?.externalId}`)
        expect(text(built)).toContain('ap_validate_flow({ folderName: "Order intake" })')
        await apCreateFolderTool(mcp, mockLog).execute({ folderName: 'Order "rush"' })
        const quoted = await apBuildFlowTool({ mcp }, mockLog).execute({
            flowName: 'Quoted folder',
            folderName: 'Order "rush"',
            trigger: { pieceName: '@activepieces/piece-test-email', triggerName: 'new_email' },
            steps: [],
        })
        expect(text(quoted)).toContain('ap_validate_flow({ folderName: "Order \\"rush\\"" })')
    })

    it('ap_build_flow into a folder that does not exist creates nothing', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const result = await apBuildFlowTool({ mcp }, mockLog).execute({
            flowName: 'Unfiled build',
            folderName: 'Never created',
            trigger: { pieceName: '@activepieces/piece-test-email', triggerName: 'new_email' },
            steps: [],
        })

        const folder = await flowFolderService(mockLog).getOneByDisplayNameCaseInsensitive({ projectId: ctx.project.id, displayName: 'Never created' })
        const flowCount = await flowService(mockLog).count({ projectId: ctx.project.id, folderId: undefined })
        expect(text(result)).toContain('ap_create_folder')
        expect(folder).toBeNull()
        expect(flowCount).toBe(0)
    })

    it('ap_create_folder returns the same folder for the same name in any case, without renaming it', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const first = await apCreateFolderTool(mcp, mockLog).execute({ folderName: 'Order intake' })
        const second = await apCreateFolderTool(mcp, mockLog).execute({ folderName: 'order INTAKE' })

        const folderSchema = z.object({ folderId: z.string() })
        const folder = await flowFolderService(mockLog).getOneByDisplayNameCaseInsensitive({ projectId: ctx.project.id, displayName: 'Order intake' })
        expect(structured({ result: second, schema: folderSchema }).folderId).toBe(structured({ result: first, schema: folderSchema }).folderId)
        expect(folder?.displayName).toBe('Order intake')
    })

    it('ap_create_folder called concurrently with different casing creates one folder', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const results = await Promise.all([
            apCreateFolderTool(mcp, mockLog).execute({ folderName: 'Parallel solution' }),
            apCreateFolderTool(mcp, mockLog).execute({ folderName: 'PARALLEL solution' }),
            apCreateFolderTool(mcp, mockLog).execute({ folderName: 'parallel Solution' }),
        ])

        const folderIds = results.map((result) => structured({ result, schema: z.object({ folderId: z.string() }) }).folderId)
        expect(new Set(folderIds).size).toBe(1)
    })

    it('ap_move_flow_to_folder creates a folder by name, reuses it in any case, and takes the flow back out', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Folder flow')
        const otherFlowId = await createFlowAndGetId(mcp, 'Folder flow 2')
        const moveSchema = z.object({ folderId: z.string().nullable(), folderName: z.string().nullable(), moved: z.boolean() })
        const move = apMoveFlowToFolderTool({ mcp }, mockLog).execute

        const created = await move({ flowId, folderName: 'Order intake' })
        const reused = await move({ flowId: otherFlowId, folderName: 'order INTAKE' })
        const again = await move({ flowId, folderName: 'Order intake' })
        const listed = await apListFoldersTool(mcp, mockLog).execute({})
        const out = await move({ flowId, uncategorized: true })

        const createdContent = structured({ result: created, schema: moveSchema })
        const otherFlow = await flowService(mockLog).getOneOrThrow({ id: otherFlowId, projectId: ctx.project.id })
        const flow = await flowService(mockLog).getOneOrThrow({ id: flowId, projectId: ctx.project.id })
        expect(createdContent).toMatchObject({ folderName: 'Order intake', moved: true })
        expect(text(created)).toContain('to folder "Order intake"')
        expect(structured({ result: reused, schema: moveSchema })).toMatchObject({ folderId: createdContent.folderId, folderName: 'Order intake' })
        expect(otherFlow.folderId).toBe(createdContent.folderId)
        expect(structured({ result: again, schema: moveSchema }).moved).toBe(false)
        expect(text(listed)).toContain('Order intake')
        expect(text(listed)).toContain('2 flows')
        expect(text(out)).toContain('out of its folder')
        expect(flow.folderId).toBeNull()
    })

    it('ap_move_flow_to_folder called concurrently into a new name in different casing files both flows into one folder', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowIds = await Promise.all([createFlowAndGetId(mcp, 'Parallel move 1'), createFlowAndGetId(mcp, 'Parallel move 2')])

        const results = await Promise.all([
            apMoveFlowToFolderTool({ mcp }, mockLog).execute({ flowId: flowIds[0], folderName: 'Parallel move' }),
            apMoveFlowToFolderTool({ mcp }, mockLog).execute({ flowId: flowIds[1], folderName: 'PARALLEL move' }),
        ])

        const folderIds = results.map((result) => structured({ result, schema: z.object({ folderId: z.string() }) }).folderId)
        const flows = await Promise.all(flowIds.map((id) => flowService(mockLog).getOneOrThrow({ id, projectId: ctx.project.id })))
        expect(new Set(folderIds).size).toBe(1)
        expect(flows.map((flow) => flow.folderId)).toEqual([folderIds[0], folderIds[0]])
    })

    it('ap_move_flow_to_folder needs exactly one target and only moves flows in its own project', async () => {
        const ctx = await createTestContext(app)
        const other = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Guarded flow')
        const foreignFlowId = await createFlowAndGetId(makeMcp(other.project.id), 'Other project flow')
        const move = apMoveFlowToFolderTool({ mcp }, mockLog).execute

        const none = await move({ flowId })
        const both = await move({ flowId, folderName: 'A', uncategorized: true })
        const foreign = await move({ flowId: foreignFlowId, folderName: 'Mine' })

        const foreignFlow = await flowService(mockLog).getOneOrThrow({ id: foreignFlowId, projectId: other.project.id })
        expect(text(none)).toContain('exactly one')
        expect(text(both)).toContain('exactly one')
        expect(text(foreign)).toContain('Flow not found')
        expect(foreignFlow.folderId).toBeNull()
    })

    it('ap_list_folders returns every folder past the first page', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        await Promise.all(Array.from({ length: 105 }, (_, i) => flowFolderService(mockLog).upsert({ projectId: ctx.project.id, request: { projectId: ctx.project.id, displayName: `Folder ${i}` } })))

        const listed = await apListFoldersTool(mcp, mockLog).execute({})

        expect(structured({ result: listed, schema: z.object({ count: z.number() }) }).count).toBe(105)
    })

    it('ap_create_flow without a folder leaves the flow unfiled', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const created = await apCreateFlowTool({ mcp }, mockLog).execute({ flowName: 'Loose flow' })
        const flow = await flowService(mockLog).getOne({ id: structured({ result: created, schema: z.object({ flowId: z.string() }) }).flowId, projectId: ctx.project.id })

        expect(flow?.folderId).toBeNull()
        expect(text(created)).not.toContain('in folder')
    })

    it('ap_build_flow drops unknown properties from steps that are not valid yet, so a later update is not rejected for them', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)

        const built = await apBuildFlowTool({ mcp }, mockLog).execute({
            flowName: 'Unknown props',
            trigger: { pieceName: '@activepieces/piece-test-email', triggerName: 'new_labeled_email', input: { folder: 'INBOX', method: 'POST' } },
            steps: [{ type: FlowActionType.PIECE, displayName: 'Send', pieceName: '@activepieces/piece-test-email', actionName: 'send_email', input: { to: '[email protected]', bogus: 'x' } }],
        })
        const { flowId } = structured({ result: built, schema: z.object({ flowId: z.string() }) })
        const builtFlow = await flowService(mockLog).getOnePopulatedOrThrow({ id: flowId, projectId: ctx.project.id })

        const triggerUpdate = await apUpdateTriggerTool({ mcp }, mockLog).execute({ flowId, pieceName: '@activepieces/piece-test-email', triggerName: 'new_labeled_email', input: { label: 'urgent' } })
        const stepUpdate = await apUpdateStepTool({ mcp }, mockLog).execute({ flowId, stepName: 'step_1', input: { subject: 'Hello' } })
        const rejected = await apUpdateStepTool({ mcp }, mockLog).execute({ flowId, stepName: 'step_1', input: { nope: 'x' } })
        const updatedFlow = await flowService(mockLog).getOnePopulatedOrThrow({ id: flowId, projectId: ctx.project.id })

        expect(text(built)).toContain('dropped')
        expect(builtFlow.version.trigger.valid).toBe(false)
        expect(builtFlow.version.trigger.settings.input).not.toHaveProperty('method')
        expect(flowStructureUtil.getStepOrThrow('step_1', builtFlow.version.trigger).settings.input).not.toHaveProperty('bogus')
        expect(text(triggerUpdate)).not.toContain('Unknown properties')
        expect(text(stepUpdate)).not.toContain('Unknown properties')
        expect(text(rejected)).toContain("Unknown properties: 'nope'")
        expect(updatedFlow.version.trigger.settings.input).toMatchObject({ folder: 'INBOX', label: 'urgent' })
        expect(flowStructureUtil.getStepOrThrow('step_1', updatedFlow.version.trigger).settings.input).toMatchObject({ to: '[email protected]', subject: 'Hello' })
    })

    it('ap_update_trigger clears a stale unknown property saved on a trigger that is not valid yet', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Stale props')
        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 Labeled Email',
                    valid: false,
                    type: FlowTriggerType.PIECE,
                    settings: { pieceName: '@activepieces/piece-test-email', pieceVersion: '0.1.0', triggerName: 'new_labeled_email', input: { folder: 'INBOX', method: 'POST' }, propertySettings: {} },
                },
            },
        })
        const stale = await flowService(mockLog).getOnePopulatedOrThrow({ id: flowId, projectId: ctx.project.id })

        const triggerUpdate = await apUpdateTriggerTool({ mcp }, mockLog).execute({ flowId, pieceName: '@activepieces/piece-test-email', triggerName: 'new_labeled_email', input: { label: 'urgent' } })
        const updatedFlow = await flowService(mockLog).getOnePopulatedOrThrow({ id: flowId, projectId: ctx.project.id })

        expect(stale.version.trigger.settings.input).toHaveProperty('method')
        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 } })
    })

    it('ap_update_step moves a piece step to an exact piece version, or back to latest', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Step version change')
        await apAddStepTool({ mcp }, mockLog).execute({ flowId, parentStepName: 'trigger', stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER, stepType: FlowActionType.PIECE, displayName: 'Send', pieceName: '@activepieces/piece-test-email', actionName: 'send_template' })
        const readVersion = async (): Promise<unknown> => {
            const flow = await flowService(mockLog).getOnePopulatedOrThrow({ id: flowId, projectId: ctx.project.id })
            return flowStructureUtil.getStep('step_1', flow.version.trigger)?.settings.pieceVersion
        }

        const pinned = await apUpdateStepTool({ mcp }, mockLog).execute({ flowId, stepName: 'step_1', pieceVersion: '0.0.9' })
        const pinnedVersion = await readVersion()
        await apUpdateStepTool({ mcp }, mockLog).execute({ flowId, stepName: 'step_1', displayName: 'Renamed' })
        const untouchedVersion = await readVersion()
        await apUpdateStepTool({ mcp }, mockLog).execute({ flowId, stepName: 'step_1', pieceVersion: 'latest' })

        expect(text(pinned)).not.toContain('❌')
        expect(pinnedVersion).toBe('0.0.9')
        expect(untouchedVersion).toBe('0.0.9')
        expect(await readVersion()).toBe('0.1.0')
    })

    it('ap_update_step rejects a piece version that does not exist, or one set on a non-piece step', async () => {
        const ctx = await createTestContext(app)
        const mcp = makeMcp(ctx.project.id)
        const flowId = await createFlowAndGetId(mcp, 'Step version reject')
        await apAddStepTool({ mcp }, mockLog).execute({ flowId, parentStepName: 'trigger', stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER, stepType: FlowActionType.PIECE, displayName: 'Send', pieceName: '@activepieces/piece-test-email', actionName: 'send_template' })
        await apAddStepTool({ mcp }, mockLog).execute({ flowId, parentStepName: 'step_1', stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER, stepType: FlowActionType.CODE, displayName: 'Code' })

        const missing = await apUpdateStepTool({ mcp }, mockLog).execute({ flowId, stepName: 'step_1', pieceVersion: '9.9.9' })
        const onCode = await apUpdateStepTool({ mcp }, mockLog).execute({ flowId, stepName: 'step_2', pieceVersion: 'latest' })
        const flow = await flowService(mockLog).getOnePopulatedOrThrow({ id: flowId, projectId: ctx.project.id })

        expect(missing.isError).toBe(true)
        expect(text(missing)).toContain('9.9.9')
        expect(onCode.isError).toBe(true)
        expect(text(onCode)).toContain('PIECE')
        expect(flowStructureUtil.getStep('step_1', flow.version.trigger)?.settings.pieceVersion).toBe('0.1.0')
    })

    it('ap_update_step drops inputs the new piece version lacks and refreshes its dynamic schemas, and leaves them alone when the version is unchanged', 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 versionedPiece = (version: string, props: Record<string, unknown>): ReturnType<typeof createMockPieceMetadata> => createMockPieceMetadata({
            name: '@activepieces/piece-test-versioned',
            displayName: 'Test Versioned',
            version,
            pieceType: PieceType.CUSTOM,
            packageType: PackageType.REGISTRY,
            platformId: ctx.platform.id,
            actions: { send: { name: 'send', displayName: 'Send', description: 'Send', requireAuth: false, props } },
            triggers: {},
        })
        const keep = { type: 'SHORT_TEXT', displayName: 'Keep', required: true }
        const fields = { type: 'DYNAMIC', displayName: 'Fields', required: false, refreshers: ['keep'] }
        await db.save('piece_metadata', versionedPiece('1.0.0', { keep, legacy: { type: 'SHORT_TEXT', displayName: 'Legacy', required: false }, fields }))
        const flowId = await createFlowAndGetId(mcp, 'Step version cleanup')
        const resolve = vi.spyOn(userInteractionWatcher, 'submitAndWaitForResponse').mockResolvedValue({ status: EngineResponseStatus.OK, response: { options: oldSchema } })
        await apAddStepTool({ mcp }, mockLog).execute({ flowId, parentStepName: 'trigger', stepLocationRelativeToParent: StepLocationRelativeToParent.AFTER, stepType: FlowActionType.PIECE, displayName: 'Send', pieceName: '@activepieces/piece-test-versioned', actionName: 'send', input: { keep: 'a', legacy: 'old', fields: { count: '3' } } })
        await db.save('piece_metadata', versionedPiece('1.1.0', { keep, fields }))
        resolve.mockResolvedValue({ status: EngineResponseStatus.OK, response: { options: newSchema } })
        const readStep = async (): Promise<ReturnType<typeof flowStructureUtil.getStep>> => flowStructureUtil.getStep('step_1', (await flowService(mockLog).getOnePopulatedOrThrow({ id: flowId, projectId: ctx.project.id })).version.trigger)

        await apUpdateStepTool({ mcp }, mockLog).execute({ flowId, stepName: 'step_1', pieceVersion: 'latest' })
        const upgraded = await readStep()
        resolve.mockClear()
        await apUpdateStepTool({ mcp }, mockLog).execute({ flowId, stepName: 'step_1', pieceVersion: 'latest' })
        const refreshesOnSameVersion = resolve.mock.calls.length
        resolve.mockRestore()

        expect(upgraded?.settings.pieceVersion).toBe('1.1.0')
        expect(upgraded?.settings.input).toEqual(expect.not.objectContaining({ legacy: expect.anything() }))
        expect(upgraded?.settings.input).toMatchObject({ keep: 'a', fields: { count: '3' } })
        expect(upgraded?.settings.propertySettings).toMatchObject({ fields: { schema: newSchema } })
        expect(refreshesOnSameVersion).toBe(0)
    })
})