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

feat(chat): put a solution's flows and tables in one folder (#16095)

Hazem Adelf8fd90b924f0
diff --git a/brain/knowledge/decisions/000045-chat-uses-an-orchestrator-with-stateless-single-writer-sub-agents.md b/brain/knowledge/decisions/000045-chat-uses-an-orchestrator-with-stateless-single-writer-sub-agents.md
new file mode 100644
index 00000000000..4ae4382620b
--- /dev/null
+++ b/brain/knowledge/decisions/000045-chat-uses-an-orchestrator-with-stateless-single-writer-sub-agents.md
@@ -0,0 +1,22 @@
+---
+status: superseded by 000046-chat-cost-is-cut-in-the-cache-and-build-loop-not-with-sub-agents
+icon: 🪆
+---
+
+# Chat uses an orchestrator with stateless, single-writer sub-agents
+
+## Decision
+
+The user talks to a small orchestrator on the `smart` tier. Its prompt is about 3k tokens, identical for every user, and it has a stable set of about 6 tools. It delegates to a fixed catalog of children: Explorer (read-only, `fast` tier), Flow builder (the only writer of flows), Task runner, and Agent builder. A child runs as a nested `runAgentTurn` inside the same worker job. It gets a typed brief that quotes the user's asks verbatim, returns a typed result (`done | needs_input | failed`), and keeps no state between delegations. The real artifacts (the flow, the build plan) hold the state.
+
+## Context
+
+A "hello" cost about $0.20 because every request sent a 22k-token system prompt plus 12-18k tokens of tool definitions, across two models, with frequent cache misses. The free plan's 100 credits are worth about $0.05, so a free user couldn't afford one turn.
+
+## Why
+
+Small contexts on cheaper tiers cost far less than trimming one big agent. We avoided the known failure modes. A weak primary model can't tell when to escalate (Cognition), so the orchestrator stays on `smart`. Parallel writers make conflicting decisions, so there is only one writer. A child given only a summary misreads the task, so the brief quotes the user verbatim. We rejected a generic "spawn any sub-agent" tool: the orchestrator would need to know every tool, which brings the big context back.
+
+## Consequences
+
+The design binds to tiers, never to model names. The tier file gets a per-provider id map, because `nativeModelId` is Anthropic-only and OpenAI, Google, Azure and Bedrock otherwise resolve `fast` and `smart` to the same model. A provider missing from the map runs children on the orchestrator's model; the smaller context still carries most of the saving. On own-key providers, child tool calls must be persisted into the turn (tagged `delegationId`) and the child must get the outer turn's `creditsLeft`, or per-turn billing and the mid-turn credit check would miss them. Managed bills each child model call at cost through `billedLanguageModel` with no change. Only the orchestrator renders `ap_show_*` widgets. Rollout is per conversation through `getAgentConfig` (`single | subagents`), A/B tested on cloud free first. The gate is cost per message, cost per completed eval scenario, and the share of free users who reach a first flow within budget.
diff --git a/brain/knowledge/decisions/000046-chat-cost-is-cut-in-the-cache-and-build-loop-not-with-sub-agents.md b/brain/knowledge/decisions/000046-chat-cost-is-cut-in-the-cache-and-build-loop-not-with-sub-agents.md
new file mode 100644
index 00000000000..eaa2142a100
--- /dev/null
+++ b/brain/knowledge/decisions/000046-chat-cost-is-cut-in-the-cache-and-build-loop-not-with-sub-agents.md
@@ -0,0 +1,53 @@
+---
+title: The chat builds composed solutions by default, one sub-agent per flow
+status: proposed
+icon: 💸
+---
+
+# The chat builds composed solutions by default, one sub-agent per flow
+
+## Decision
+
+Whenever a use case has more than one job (intake, processing, storage, reporting, approval), the chat agent becomes an architect. The result is a folder of small, well-named flows, subflows and tables, not one big flow. The architect:
+- writes a Solution Blueprint: artifacts, connections, and a JSON Schema contract per connection;
+- pre-creates flow shells and builds tables in code;
+- runs one builder sub-agent per flow in parallel, each the only writer of its flow;
+- lets code check every contract before a verifier runs the solution end to end.
+
+A single-purpose flow stays on the single agent. A verifier sub-agent reviews and test-runs every build, single or composed, and a debug sub-agent handles failed production runs.
+
+General cost optimisation is a separate track, owned by a teammate. It covers:
+- a system-prompt cache breakpoint on managed;
+- refusal handling;
+- a fixed tool list and per-user data out of the prefix;
+- a Sonnet 5.5 migration with effort levels.
+
+Everything ships behind a per-conversation flag, after a live multi-turn, multi-artifact eval gate.
+
+## Context
+
+Users ask the chat for connected solutions: flows, callable subflows, tables, agents, forms, approvals. One agent building all of that in one context produced huge flows, mounting bugs, and $2-4 per solution on managed.
+
+## Why
+
+Production data (2026-10-04, read-only replica):
+- 0 of 1,417 chat conversations used subflows, because the chat never offers composition;
+- 56% of `ap_build_flow` calls returned invalid steps;
+- about 4% of chat-built flows had a successful production run.
+
+So the bigger problem is correctness, not the share of big requests: big tool outputs crowd one shared context. The team lead's product call is that composition is held back by supply, not demand. Earlier, five adversarial review rounds with a cost simulator found:
+- **Splitting a single flow's builder saves ~1%.** The earlier sub-agent design, 000045, is superseded.
+- **One builder per artifact pays off on four or more artifacts:** ~25% cheaper and 30-35% faster in parallel. It loses on one flow, hence the router.
+
+Most of the correctness gain comes from deterministic contract checks, so those ship first and serve the single agent too.
+
+## Consequences
+
+Required before builders ship:
+- `ap_create_flow` must return the flow externalId, which Call Flow stores;
+- per-builder `phaseState`, taint state and emitter;
+- builder tool calls persisted so own-key billing counts them;
+- one credit reservation shared by parallel builders;
+- agent, knowledge-base and flow-tool chat tools before agent nodes are buildable.
+
+The blueprint is intent: contracts are re-derived from live flows before edits.
diff --git a/brain/knowledge/flows-execution/chat.md b/brain/knowledge/flows-execution/chat.md
index 14e6baff8e7..d51a5b1c957 100644
--- a/brain/knowledge/flows-execution/chat.md
+++ b/brain/knowledge/flows-execution/chat.md
@@ -31,6 +31,12 @@ A turn is kept alive / reclaimed by three separate mechanisms in `execute-agent-
- **Stream idle watchdog** (`STREAM_IDLE_TIMEOUT_MS` 90s, in `streamChunksToClient`): aborts the turn if the drain-stream reader is silent 90s. It must be SUSPENDED while legitimate silent work is in flight — pending tool calls AND in-flight reasoning (`reasoning-start`→`reasoning-end`). **Reasoning-awareness was missing and caused the bug where long "thinking" on the Expert tier randomly aborted a healthy turn** (a >90s gap between reasoning deltas looked like a wedge). Backstop for a genuine mid-reasoning wedge is `MAX_TURN_WALL_CLOCK_MS` (20 min).
### Gotchas
+- **Compaction is not metered.** `getAgentConfig` builds the compaction model with `aiUtils.createModel` and no `billing`, so the summarizing call on the main model never reaches credits or usage reporting. Count it by hand when measuring cost per turn.
+- **Bedrock ignores our cache and thinking options.** `agentProviderOptions` sends `anthropic.cacheControl` and `anthropic.thinking` for BEDROCK, but `@ai-sdk/amazon-bedrock` reads only `bedrock`/`amazonBedrock` keys (`cachePoint`, `reasoningConfig`). Bedrock chat therefore runs with no prompt caching and default thinking.
+- **Tiers only resolve on Anthropic-shaped providers.** `PublishedTier.nativeModelId` is a single Anthropic id. On OpenAI and Google both `fast` and `smart` fall to the first curated model; on Azure and Bedrock the fast model is passed `fallbackModelId: resolvedModelId`, so it equals the main model.
+- **Managed chat has no system-prompt cache breakpoint.** `buildSystemPromptWithCaching` sets one only for ANTHROPIC/BEDROCK; managed/OpenRouter rely on automatic caching at the end of the request. So any change to the tool list or thinking settings (the discovery→build flip swaps `activeTools`) rewrites the whole ~22k-token prefix. `@openrouter/ai-sdk-provider` does honor `cacheControl` on system messages.
+- **Refusals aren't handled.** Nothing branches on `content-filter`. A refused step with no visible output hits `decideLoopAction` → `continue_empty` and re-sends the full context with "Continue".
+- **The per-user tail breaks the prompt cache.** The date, memory, connection inventory and `{{PROJECT_LIST}}` sit inside the same single system block as the ~22k-token static prompt. Any change re-writes the whole cached prefix, and the prompt is effectively unique per user.
- **A step's `response.messages` holds only that step's messages (AI SDK v7).** The older SDK made it cumulative, so `collectStepMessages` once took the last step; under v7 that saved only a turn's closing text and dropped every tool call and result. The next turn then saw replies like "New agent is updated" with no tool call behind them, and repeated the pattern by claiming changes it never made. It now joins every step, and `run-agent-turn-history.test.ts` runs a real `streamText` turn so a future SDK change to these semantics fails loudly.
- **Chat has no fixed step cap.** A chat turn is bounded by credits (checked after every step), the runaway-token ceiling (`RUNAWAY_TURN_CONTEXT_MULTIPLE` × the context window), the identical-failure guard and the 2-hour `MAX_AGENT_TURN_WALL_CLOCK_MS`, so it finishes long jobs. A saved agent's author-set `maxSteps` is still honored on its last step: an agent with structured output is forced to call `TASK_COMPLETION_TOOL_NAME` so the flow gets a result, and any other agent runs with `toolChoice: 'none'` plus a wrap-up note, so it replies with what's done and what's left. Never a silent stop or an error.
- **The streaming lock is per run, not per conversation.** A re-send can claim `activeRunId` before the first job reaches `getAgentConfig`. `agentHelpers.acquireStreamingLock` only lets the owning run set STREAMING; an older run gets `AGENT_RUN_SUPERSEDED` and the worker exits quietly, with no ERROR save and no events. A lock that ignored `runId` let the old run stream unowned while the new one was rejected as busy and marked ERROR, which is how users saw nothing after tapping a starter card twice.
diff --git a/brain/knowledge/flows-execution/folders.md b/brain/knowledge/flows-execution/folders.md
index 3f7be46a7fb..177d550fb3b 100644
--- a/brain/knowledge/flows-execution/folders.md
+++ b/brain/knowledge/flows-execution/folders.md
@@ -19,6 +19,7 @@ Folders are a lightweight organizational layer for flows within a project. Each
- Audit events: `FOLDER_CREATED`, `FOLDER_UPDATED`, `FOLDER_DELETED` (fetched before delete so the event has full data).
### Gotchas
+- **Folder names are unique case-insensitively, and `flowFolderService.upsert` returns a match as-is.** Upserting "order INTAKE" when "Order intake" exists returns the existing folder unchanged. It used to rename it to the request's casing. Chat create tools (`ap_create_flow`, `ap_build_flow`, `ap_create_table`) only file into an existing folder by name and never create one; `ap_create_folder` creates it, so a failed build leaves no folder behind.
- **`UncategorizedFolderId`** is the string literal `"NULL"` — a sentinel in the flow list query matching flows with no folder.
- **The `folderId` FK does not enforce the project boundary, and a foreign folder id makes the row vanish from the Automations page while it keeps running.** `fk_flow_folder_id` only requires the folder row to exist *somewhere*, so any write path that trusts a caller-supplied `folderId` can point a flow or table at another project's folder. The page renders exactly two buckets — flows whose `folderId` is in this project's folder list, and flows with `folderId IS NULL` — so a cross-project id matches neither: the flow disappears from the tree, from uncategorized, and from find-in-page, while staying ENABLED and burning task quota (GIT-1871, hit in production). Name search still finds it, because `flowService.list` has no folder restriction. Every write of a caller-supplied `folderId` must call `flowFolderService.getOneOrThrow({ projectId, folderId })` first, and must normalize the `UncategorizedFolderId` sentinel to `null` before the write — the literal `"NULL"` otherwise hits the FK and 500s. Client-side re-rooting cannot rescue an orphan: the root query asks the server for `folderId IS NULL`, so the orphan is never fetched.
- **Deleting a folder does NOT delete its flows** — they become uncategorized (the flow's `folderId` FK is nullable; not nulled automatically by the service).
diff --git a/packages/core/shared/package.json b/packages/core/shared/package.json
index 6ddecbf2e2a..21d1e2c0cdf 100644
--- a/packages/core/shared/package.json
+++ b/packages/core/shared/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/shared",
- "version": "0.191.0",
+ "version": "0.191.1",
"type": "commonjs",
"sideEffects": false,
"main": "./dist/src/index.js",
diff --git a/packages/core/shared/src/lib/ee/agent/tool-phases.ts b/packages/core/shared/src/lib/ee/agent/tool-phases.ts
index b1462f48b75..2f3b63f436f 100644
--- a/packages/core/shared/src/lib/ee/agent/tool-phases.ts
+++ b/packages/core/shared/src/lib/ee/agent/tool-phases.ts
@@ -7,6 +7,7 @@
const BUILD_ONLY_TOOL_NAMES = new Set<string>([
'ap_build_flow',
+ 'ap_create_folder',
'ap_create_flow',
'ap_add_step',
'ap_update_step',
diff --git a/packages/server/api/src/app/flows/folder/folder.service.ts b/packages/server/api/src/app/flows/folder/folder.service.ts
index b04863ceb05..db2b44bf0d7 100644
--- a/packages/server/api/src/app/flows/folder/folder.service.ts
+++ b/packages/server/api/src/app/flows/folder/folder.service.ts
@@ -2,6 +2,7 @@ import { ActivepiecesError, apId, Cursor, ErrorCode, isNil, ProjectId, SeekPage
import { CreateFolderRequest, Folder, FolderDto, FolderId, UpdateFolderRequest } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { repoFactory } from '../../core/db/repo-factory'
+import { distributedLock } from '../../database/redis-connections'
import { buildPaginator } from '../../helper/pagination/build-paginator'
import { paginationHelper } from '../../helper/pagination/pagination-utils'
import { tableService } from '../../tables/table/table.service'
@@ -39,30 +40,36 @@ export const flowFolderService = (log: FastifyBaseLogger) => ({
},
async upsert(params: UpsertParams): Promise<FolderDto> {
const { projectId, request } = params
- const folderWithDisplayName = await this.getOneByDisplayNameCaseInsensitive({
- projectId,
- displayName: request.displayName,
- })
- if (!isNil(folderWithDisplayName)) {
- return this.update({
- projectId,
- folderId: folderWithDisplayName.id,
- request,
- })
- }
- const folderId = apId()
- await folderRepo().upsert({
- id: folderId,
- projectId,
- displayName: request.displayName,
- externalId: folderId,
- }, ['projectId', 'displayName'])
- const folder = await folderRepo().findOneByOrFail({ projectId, id: folderId })
- return {
- ...folder,
- numberOfFlows: 0,
- numberOfTables: 0,
+ const existingFolder = await this.getOneByDisplayNameCaseInsensitive({ projectId, displayName: request.displayName })
+ if (!isNil(existingFolder)) {
+ return this.getOneOrThrow({ projectId, folderId: existingFolder.id })
}
+ return distributedLock(log).runExclusive({
+ key: folderUpsertLockKey({ projectId, displayName: request.displayName }),
+ timeoutInSeconds: FOLDER_UPSERT_LOCK_TIMEOUT_SECONDS,
+ fn: async () => {
+ const folderWithDisplayName = await this.getOneByDisplayNameCaseInsensitive({
+ projectId,
+ displayName: request.displayName,
+ })
+ if (!isNil(folderWithDisplayName)) {
+ return this.getOneOrThrow({ projectId, folderId: folderWithDisplayName.id })
+ }
+ const folderId = apId()
+ await folderRepo().upsert({
+ id: folderId,
+ projectId,
+ displayName: request.displayName,
+ externalId: folderId,
+ }, ['projectId', 'displayName'])
+ const folder = await folderRepo().findOneByOrFail({ projectId, id: folderId })
+ return {
+ ...folder,
+ numberOfFlows: 0,
+ numberOfTables: 0,
+ }
+ },
+ })
},
async listAllByProject(params: ListAllParams): Promise<Folder[]> {
const { projectId } = params
@@ -154,6 +161,12 @@ export const flowFolderService = (log: FastifyBaseLogger) => ({
},
})
+function folderUpsertLockKey({ projectId, displayName }: { projectId: ProjectId, displayName: string }): string {
+ return `folder-upsert-${projectId}-${displayName.trim().toLowerCase()}`
+}
+
+const FOLDER_UPSERT_LOCK_TIMEOUT_SECONDS = 30
+
type DeleteParams = {
projectId: ProjectId
folderId: FolderId
diff --git a/packages/server/api/src/app/mcp/tools/ap-build-flow.ts b/packages/server/api/src/app/mcp/tools/ap-build-flow.ts
index 27f03abad4e..6de0a0c4b7e 100644
--- a/packages/server/api/src/app/mcp/tools/ap-build-flow.ts
+++ b/packages/server/api/src/app/mcp/tools/ap-build-flow.ts
@@ -36,6 +36,7 @@ const buildFlowInput = z.object({
auth: z.string().optional(),
}),
steps: z.array(stepSpec),
+ folderName: mcpUtils.FOLDER_NAME_SCHEMA,
})
export const apBuildFlowTool = ({ mcp, userId }: McpToolContext, log: FastifyBaseLogger): McpToolDefinition => {
@@ -51,6 +52,7 @@ export const apBuildFlowTool = ({ mcp, userId }: McpToolContext, log: FastifyBas
input: z.record(z.string(), z.unknown()).optional().describe('Trigger input config'),
auth: z.string().optional().describe('Connection externalId for trigger auth'),
}).describe('Trigger configuration'),
+ folderName: mcpUtils.FOLDER_NAME_SCHEMA,
steps: z.array(stepSpec).describe('Array of steps. By default added sequentially after trigger. Use parentStepName + stepLocationRelativeToParent to nest steps inside loops. Each step supports: PIECE (pieceName+actionName+input), CODE (sourceCode+input), LOOP_ON_ITEMS (loopItems). Prefer PIECE and inline formula expressions (in free-text/value inputs, not dropdowns) over CODE — reach for a CODE step only when no piece fits and the transform exceeds the inline formula functions. ROUTER is not supported here — add it afterwards with ap_add_step + ap_add_branch.'),
},
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
@@ -58,7 +60,7 @@ export const apBuildFlowTool = ({ mcp, userId }: McpToolContext, log: FastifyBas
let flowId: string | undefined
const projectId = mcp.projectId
try {
- const { flowName, trigger, steps } = buildFlowInput.parse(args)
+ const { flowName, trigger, steps, folderName } = buildFlowInput.parse(args)
const triggerAuthError = mcpUtils.validateAuth(trigger.auth)
if (triggerAuthError) {
return triggerAuthError
@@ -70,16 +72,21 @@ export const apBuildFlowTool = ({ mcp, userId }: McpToolContext, log: FastifyBas
}
}
- const [platformId, flow] = await Promise.all([
+ const [platformId, folder] = await Promise.all([
projectService(log).getPlatformId(projectId),
- flowService(log).create({
- projectId,
- ownerId: userId,
- createdBy: { type: FlowCreatorType.MCP, id: mcp.id },
- request: { displayName: flowName, projectId },
- }),
+ mcpUtils.resolveFolder({ projectId, folderName, log }),
])
+ if (folder.error) {
+ return folder.error
+ }
+ const flow = await flowService(log).create({
+ projectId,
+ ownerId: userId,
+ createdBy: { type: FlowCreatorType.MCP, id: mcp.id },
+ request: { displayName: flowName, projectId, folderId: folder.folderId },
+ })
flowId = flow.id
+ const createdIn = `${mcpUtils.folderSuffix(folder.folderName)}, externalId ${flow.externalId}`
const triggerVersionResult = await mcpUtils.resolveLatestPieceVersion({ pieceName: trigger.pieceName, projectId, platformId, log })
if (triggerVersionResult.error) {
@@ -193,6 +200,8 @@ export const apBuildFlowTool = ({ mcp, userId }: McpToolContext, log: FastifyBas
const flowUrl = await domainHelper.getPublicUrl({ path: `/projects/${projectId}/flows/${flowId}` })
const structured = {
flowId: flowId!,
+ externalId: flow.externalId,
+ folderName: folder.folderName ?? null,
flowUrl,
displayName: flowName,
stepCount: allSteps.length,
@@ -202,12 +211,12 @@ export const apBuildFlowTool = ({ mcp, userId }: McpToolContext, log: FastifyBas
unknownProps: unknownPropFindings,
}
if (unknownPropFindings.length > 0) {
- return { content: [{ type: 'text', text: `❌ Flow "${flowName}" created (id: ${flowId}), but some settings used property names that do NOT exist on the piece and were dropped — the flow does NOT behave as configured. Do NOT tell the user these settings were applied. Fix each with ap_update_step / ap_update_trigger using the correct property names:\n${unknownPropFindings.join('\n')}\nOpen: ${flowUrl}` }], structuredContent: structured }
+ return { content: [{ type: 'text', text: `❌ Flow "${flowName}" created (id: ${flowId})${createdIn}, but some settings used property names that do NOT exist on the piece and were dropped — the flow does NOT behave as configured. Do NOT tell the user these settings were applied. Fix each with ap_update_step / ap_update_trigger using the correct property names:\n${unknownPropFindings.join('\n')}\nOpen: ${flowUrl}` }], structuredContent: structured }
}
if (invalidSteps.length === 0 && skippedSteps.length === 0) {
- return { content: [{ type: 'text', text: `✅ Flow "${flowName}" created (id: ${flowId}) with ${allSteps.length} ${stepWord}, all valid. Open: ${flowUrl}` }], structuredContent: structured }
+ return { content: [{ type: 'text', text: `✅ Flow "${flowName}" created (id: ${flowId})${createdIn} with ${allSteps.length} ${stepWord}, all valid. Open: ${flowUrl}` }], structuredContent: structured }
}
- return { content: [{ type: 'text', text: `⚠️ Flow "${flowName}" created (id: ${flowId}) with ${allSteps.length} ${stepWord} (${validCount} valid, ${invalidSteps.length} invalid: ${invalidSteps.join(', ')}).${skippedHint} Use ap_update_step or ap_update_trigger to fix. Open: ${flowUrl}` }], structuredContent: structured }
+ return { content: [{ type: 'text', text: `⚠️ Flow "${flowName}" created (id: ${flowId})${createdIn} with ${allSteps.length} ${stepWord} (${validCount} valid, ${invalidSteps.length} invalid: ${invalidSteps.join(', ')}).${skippedHint} Use ap_update_step or ap_update_trigger to fix. Open: ${flowUrl}` }], structuredContent: structured }
}
catch (err) {
if (flowId) {
diff --git a/packages/server/api/src/app/mcp/tools/ap-create-flow.ts b/packages/server/api/src/app/mcp/tools/ap-create-flow.ts
index ec154f19dc0..86c14b28911 100644
--- a/packages/server/api/src/app/mcp/tools/ap-create-flow.ts
+++ b/packages/server/api/src/app/mcp/tools/ap-create-flow.ts
@@ -5,18 +5,25 @@ import { z } from 'zod'
import { flowService } from '../../flows/flow/flow.service'
import { mcpUtils } from './mcp-utils'
+const createFlowInput = z.object({
+ flowName: z.string().trim().min(1, 'Flow name cannot be empty').max(255, 'Flow name must be 255 characters or less').describe('The name of the flow'),
+ folderName: mcpUtils.FOLDER_NAME_SCHEMA,
+})
+
export const apCreateFlowTool = ({ mcp, userId }: McpToolContext, log: FastifyBaseLogger): McpToolDefinition => {
return {
title: 'ap_create_flow',
permission: Permission.WRITE_FLOW,
description: 'Create a new flow in Activepieces',
- inputSchema: {
- flowName: z.string().trim().min(1, 'Flow name cannot be empty').max(255, 'Flow name must be 255 characters or less').describe('The name of the flow'),
- },
+ inputSchema: createFlowInput.shape,
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
execute: async (args) => {
- const { flowName } = z.object({ flowName: z.string().trim().min(1).max(255) }).parse(args)
+ const { flowName, folderName } = createFlowInput.parse(args)
try {
+ const folder = await mcpUtils.resolveFolder({ projectId: mcp.projectId, folderName, log })
+ if (folder.error) {
+ return folder.error
+ }
const flow = await flowService(log).create({
projectId: mcp.projectId,
ownerId: userId,
@@ -24,14 +31,15 @@ export const apCreateFlowTool = ({ mcp, userId }: McpToolContext, log: FastifyBa
request: {
displayName: flowName,
projectId: mcp.projectId,
+ folderId: folder.folderId,
},
})
return {
content: [{
type: 'text',
- text: `✅ Created flow "${flow.version.displayName}" (id: ${flow.id}). The flow has an empty trigger. Next steps:\n1. Use ap_update_trigger to set the trigger (e.g. webhook, schedule, or a piece trigger)\n2. Use ap_add_step to add action steps after the trigger\n3. Use ap_update_step to configure each step's inputs`,
+ text: `✅ Created flow "${flow.version.displayName}" (id: ${flow.id})${mcpUtils.folderSuffix(folder.folderName)}. Another flow's Call Flow step references it by externalId ${flow.externalId}. The flow has an empty trigger. Next steps:\n1. Use ap_update_trigger to set the trigger (e.g. webhook, schedule, or a piece trigger)\n2. Use ap_add_step to add action steps after the trigger\n3. Use ap_update_step to configure each step's inputs`,
}],
- structuredContent: { flowId: flow.id, displayName: flow.version.displayName },
+ structuredContent: { flowId: flow.id, externalId: flow.externalId, displayName: flow.version.displayName, folderName: folder.folderName ?? null },
}
}
catch (err) {
@@ -39,4 +47,4 @@ export const apCreateFlowTool = ({ mcp, userId }: McpToolContext, log: FastifyBa
}
},
}
-}
\ No newline at end of file
+}
diff --git a/packages/server/api/src/app/mcp/tools/ap-create-folder.ts b/packages/server/api/src/app/mcp/tools/ap-create-folder.ts
new file mode 100644
index 00000000000..1ad03c4e0ff
--- /dev/null
+++ b/packages/server/api/src/app/mcp/tools/ap-create-folder.ts
@@ -0,0 +1,36 @@
+import { Permission } from '@activepieces/core-utils'
+import { McpToolDefinition, ProjectScopedMcpServer } from '@activepieces/shared'
+import { FastifyBaseLogger } from 'fastify'
+import { z } from 'zod'
+import { flowFolderService } from '../../flows/folder/folder.service'
+import { mcpUtils } from './mcp-utils'
+
+const createFolderInput = z.object({
+ folderName: mcpUtils.FOLDER_NAME_SCHEMA.unwrap().describe('The folder name, e.g. the solution being built ("Order intake")'),
+})
+
+export const apCreateFolderTool = (mcp: ProjectScopedMcpServer, log: FastifyBaseLogger): McpToolDefinition => {
+ return {
+ title: 'ap_create_folder',
+ permission: Permission.WRITE_FLOW,
+ description: 'Create a folder to hold one solution\'s flows and tables, or get it if a folder with that name already exists. Call it once before building a solution of several flows and tables, then pass the same folderName to ap_create_flow, ap_build_flow and ap_create_table.',
+ inputSchema: createFolderInput.shape,
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
+ execute: async (args) => {
+ try {
+ const { folderName } = createFolderInput.parse(args)
+ const folder = await flowFolderService(log).upsert({
+ projectId: mcp.projectId,
+ request: { projectId: mcp.projectId, displayName: folderName },
+ })
+ return {
+ content: [{ type: 'text', text: `✅ Folder "${folder.displayName}" is ready (id: ${folder.id}). Pass folderName "${folder.displayName}" when creating this solution's flows and tables.` }],
+ structuredContent: { folderId: folder.id, folderName: folder.displayName },
+ }
+ }
+ catch (err) {
+ return mcpUtils.mcpToolError('Failed to create folder', err)
+ }
+ },
+ }
+}
diff --git a/packages/server/api/src/app/mcp/tools/ap-create-table.ts b/packages/server/api/src/app/mcp/tools/ap-create-table.ts
index 19d406be7b0..dbfcdc4da73 100644
--- a/packages/server/api/src/app/mcp/tools/ap-create-table.ts
+++ b/packages/server/api/src/app/mcp/tools/ap-create-table.ts
@@ -14,6 +14,7 @@ const createTableInput = z.object({
type: fieldTypeSchema.describe('Field type'),
options: z.array(z.string()).optional().describe('Dropdown options (required when type is STATIC_DROPDOWN)'),
})).describe('Fields to create. Max 100 fields per table.'),
+ folderName: mcpUtils.FOLDER_NAME_SCHEMA,
})
export const apCreateTableTool = (mcp: ProjectScopedMcpServer, log: FastifyBaseLogger): McpToolDefinition => {
@@ -25,7 +26,7 @@ export const apCreateTableTool = (mcp: ProjectScopedMcpServer, log: FastifyBaseL
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
execute: async (args) => {
try {
- const { name, fields } = createTableInput.parse(args)
+ const { name, fields, folderName } = createTableInput.parse(args)
for (const field of fields) {
if (field.type === FieldType.STATIC_DROPDOWN && (!field.options || field.options.length === 0)) {
@@ -33,6 +34,11 @@ export const apCreateTableTool = (mcp: ProjectScopedMcpServer, log: FastifyBaseL
}
}
+ const folder = await mcpUtils.resolveFolder({ projectId: mcp.projectId, folderName, log })
+ if (folder.error) {
+ return folder.error
+ }
+
const fieldStates = fields.map(f => ({
name: f.name,
type: f.type,
@@ -48,6 +54,7 @@ export const apCreateTableTool = (mcp: ProjectScopedMcpServer, log: FastifyBaseL
projectId: mcp.projectId,
name,
fields: fieldStates,
+ folderId: folder.folderId,
},
})
@@ -60,12 +67,13 @@ export const apCreateTableTool = (mcp: ProjectScopedMcpServer, log: FastifyBaseL
return {
content: [{
type: 'text',
- text: `✅ Table "${name}" created (id: ${table.id}, externalId: ${table.externalId})\nFields:\n${fieldLines}\n\nℹ️ Use "id" with the record/field tools; use "externalId" as table_id when configuring a Tables piece step in a flow.`,
+ text: `✅ Table "${name}" created (id: ${table.id}, externalId: ${table.externalId})${mcpUtils.folderSuffix(folder.folderName)}\nFields:\n${fieldLines}\n\nℹ️ Use "id" with the record/field tools; use "externalId" as table_id when configuring a Tables piece step in a flow.`,
}],
structuredContent: {
id: table.id,
externalId: table.externalId,
name: table.name,
+ folderName: folder.folderName ?? null,
fields: createdFields.map(f => ({ id: f.id, externalId: f.externalId, name: f.name, type: f.type })),
},
}
diff --git a/packages/server/api/src/app/mcp/tools/index.ts b/packages/server/api/src/app/mcp/tools/index.ts
index 45317e7e84e..d25510d4c97 100644
--- a/packages/server/api/src/app/mcp/tools/index.ts
+++ b/packages/server/api/src/app/mcp/tools/index.ts
@@ -6,6 +6,7 @@ import { apAddStepTool } from './ap-add-step'
import { apBuildFlowTool } from './ap-build-flow'
import { apChangeFlowStatusTool } from './ap-change-flow-status'
import { apCreateFlowTool } from './ap-create-flow'
+import { apCreateFolderTool } from './ap-create-folder'
import { apCreateTableTool } from './ap-create-table'
import { apDeleteBranchTool } from './ap-delete-branch'
import { apDeleteFlowTool } from './ap-delete-flow'
@@ -85,6 +86,7 @@ export const PLATFORM_LEVEL_TOOL_NAMES = [
export const ALL_CONTROLLABLE_TOOL_NAMES = [
'ap_build_flow',
'ap_create_flow',
+ 'ap_create_folder',
'ap_duplicate_flow',
'ap_rename_flow',
'ap_update_trigger',
@@ -113,6 +115,7 @@ export const ALL_CONTROLLABLE_TOOL_NAMES = [
export const activepiecesTools = (mcp: ProjectScopedMcpServer, userId: string | undefined, log: FastifyBaseLogger): McpToolDefinition[] => [
apBuildFlowTool({ mcp, userId }, log),
apCreateFlowTool({ mcp, userId }, log),
+ apCreateFolderTool(mcp, log),
apDuplicateFlowTool({ mcp, userId }, log),
apRenameFlowTool({ mcp, userId }, log),
apListFlowsTool(mcp, log),
diff --git a/packages/server/api/src/app/mcp/tools/mcp-utils.ts b/packages/server/api/src/app/mcp/tools/mcp-utils.ts
index 837f16c896b..97606d74269 100644
--- a/packages/server/api/src/app/mcp/tools/mcp-utils.ts
+++ b/packages/server/api/src/app/mcp/tools/mcp-utils.ts
@@ -5,6 +5,7 @@ import type { BranchedAction, Step } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { z } from 'zod'
import { expressionRewriter } from '../../flows/flow-version/migrations/expression-rewriter'
+import { flowFolderService } from '../../flows/folder/folder.service'
import { getPiecePackageWithoutArchive, pieceMetadataService } from '../../pieces/metadata/piece-metadata-service'
import { projectService } from '../../project/project-service'
import { userInteractionWatcher } from '../../workers/user-interaction-watcher'
@@ -504,6 +505,21 @@ function resolveConnectionExternalId({ connectionExternalId, input }: { connecti
return typeof inlineAuth === 'string' ? inlineAuth : undefined
}
+async function resolveFolder({ projectId, folderName, log }: { projectId: string, folderName: string | undefined, log: FastifyBaseLogger }): Promise<ResolveFolderResult> {
+ if (isNil(folderName)) {
+ return { folderId: undefined, folderName: undefined }
+ }
+ const folder = await flowFolderService(log).getOneByDisplayNameCaseInsensitive({ projectId, displayName: folderName })
+ if (isNil(folder)) {
+ return { error: { content: [{ type: 'text', text: `❌ Folder "${folderName}" does not exist. Create it with ap_create_folder first, then retry.` }], isError: true } }
+ }
+ return { folderId: folder.id, folderName: folder.displayName }
+}
+
+function folderSuffix(folderName: string | undefined): string {
+ return isNil(folderName) ? '' : ` in folder "${folderName}"`
+}
+
function validateAuth(auth: string | undefined): McpToolResult | null {
if (auth !== undefined && /['{}\[\]]/.test(auth)) {
return { content: [{ type: 'text', text: '❌ auth must be a plain externalId with no special characters. Use the exact value from ap_list_connections.' }], isError: true }
@@ -625,6 +641,8 @@ function extractOptionsArray(options: unknown): Array<{ label: string, value: un
const RESOLVE_TIMEOUT_MS = 30_000
+const FOLDER_NAME_SCHEMA = z.string().trim().min(1).max(255).optional().describe('Name of an existing folder to place it in. For a solution of several flows and tables, create the folder once with ap_create_folder, then pass the same folderName to each of them.')
+
async function executePropertyResolution({ pieceName, pieceVersion, actionOrTriggerName, propertyName, auth, input, searchValue, projectId, platformId, log }: {
pieceName: string
pieceVersion: string
@@ -800,6 +818,8 @@ export const mcpUtils = {
findResolvableProps,
resolveConnectionExternalId,
validateAuth,
+ folderSuffix,
+ resolveFolder,
fillDefaultsForMissingOptionalProps,
buildErrorHandlingOptions,
resolveLatestPieceVersion,
@@ -812,6 +832,7 @@ export const mcpUtils = {
RESOLVE_TIMEOUT_MS,
STEP_REFERENCE_HINT,
BRANCH_CONDITIONS_INPUT_SCHEMA,
+ FOLDER_NAME_SCHEMA,
}
export type { PropSummary }
@@ -881,6 +902,10 @@ type LookupPieceComponentResult =
| { piece: PieceMetadataModel, component: { props: PiecePropertyMap, requireAuth: boolean, name: string, displayName: string, description: string, outputSchema?: OutputSchema, aiMetadata?: AiMetadata, sampleData?: unknown }, pieceName: string, error?: never }
| { error: McpToolResult, piece?: never, component?: never, pieceName?: never }
+type ResolveFolderResult =
+ | { folderId: string | undefined, folderName: string | undefined, error?: never }
+ | { error: McpToolResult, folderId?: never, folderName?: never }
+
type ResolveRouterStepResult =
| { routerStep: BranchedAction, error?: never }
| { error: McpToolResult, routerStep?: never }
diff --git a/packages/server/api/test/integration/ce/flows/folder/folder-events.test.ts b/packages/server/api/test/integration/ce/flows/folder/folder-events.test.ts
index ba1e342cceb..c7bbe525660 100644
--- a/packages/server/api/test/integration/ce/flows/folder/folder-events.test.ts
+++ b/packages/server/api/test/integration/ce/flows/folder/folder-events.test.ts
@@ -1,6 +1,7 @@
import { ApplicationEventName } from '@activepieces/shared'
import { FastifyInstance } from 'fastify'
import { StatusCodes } from 'http-status-codes'
+import * as redisConnectionsModule from '../../../../../src/app/database/redis-connections'
import * as applicationEventsModule from '../../../../../src/app/helper/application-events'
import { actionsEmitted } from '../../../../helpers/application-events'
import { db } from '../../../../helpers/db'
@@ -51,6 +52,30 @@ describe('Folder application events', () => {
])
})
+ it('POST /v1/folders with an existing name in another casing returns that folder without renaming it', async () => {
+ const ctx = await createTestContext(app)
+
+ const first = await ctx.post('/v1/folders', { displayName: 'Order intake', projectId: ctx.project.id })
+ const second = await ctx.post('/v1/folders', { displayName: 'order INTAKE', projectId: ctx.project.id })
+
+ expect(second?.statusCode).toBe(StatusCodes.OK)
+ expect(second?.json().id).toBe(first?.json().id)
+ expect(second?.json().displayName).toBe('Order intake')
+ })
+
+ it('POST /v1/folders returns an existing folder without needing the upsert lock', async () => {
+ const ctx = await createTestContext(app)
+ const first = await ctx.post('/v1/folders', { displayName: 'Lock free', projectId: ctx.project.id })
+ vi.spyOn(redisConnectionsModule, 'distributedLock').mockImplementation(() => {
+ throw new Error('redis unavailable')
+ })
+
+ const second = await ctx.post('/v1/folders', { displayName: 'lock FREE', projectId: ctx.project.id })
+
+ expect(second?.statusCode).toBe(StatusCodes.OK)
+ expect(second?.json().id).toBe(first?.json().id)
+ })
+
it('emits FOLDER_UPDATED on POST /v1/folders/:id', async () => {
const ctx = await createTestContext(app)
const folder = createMockFolder({ projectId: ctx.project.id })
diff --git a/packages/server/api/test/integration/ce/mcp/mcp-tools.test.ts b/packages/server/api/test/integration/ce/mcp/mcp-tools.test.ts
index fbfac093d95..51cfc36f30d 100644
--- a/packages/server/api/test/integration/ce/mcp/mcp-tools.test.ts
+++ b/packages/server/api/test/integration/ce/mcp/mcp-tools.test.ts
@@ -3,11 +3,15 @@ import { FlowActionType, FlowCreatorType, FlowRunStatus, McpServerType, PackageT
import { FastifyBaseLogger, FastifyInstance } from 'fastify'
import { StatusCodes } from 'http-status-codes'
import { afterAll, beforeAll, describe, expect, it } 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'
@@ -29,6 +33,7 @@ import { apListFlowsTool } from '../../../../src/app/mcp/tools/ap-list-flows'
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 { db } from '../../../helpers/db'
import { createMockPieceMetadata } from '../../../helpers/mocks'
import { createTestContext } from '../../../helpers/test-context'
@@ -160,6 +165,10 @@ function text(result: { content: Array<{ type: 'text', text: string }> }): strin
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+?)\)/)
@@ -2636,4 +2645,97 @@ describe('MCP Tools integration', () => {
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}`)
+ })
+
+ 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_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')
+ })
})
diff --git a/packages/web/src/app/components/project-settings/mcp-server/utils/mcp-tools-metadata.ts b/packages/web/src/app/components/project-settings/mcp-server/utils/mcp-tools-metadata.ts
index f98722d0ded..42448ece26d 100644
--- a/packages/web/src/app/components/project-settings/mcp-server/utils/mcp-tools-metadata.ts
+++ b/packages/web/src/app/components/project-settings/mcp-server/utils/mcp-tools-metadata.ts
@@ -114,6 +114,10 @@ const TOOL_CATEGORIES: ToolCategory[] = [
name: 'ap_create_flow',
description: 'Create a new flow',
},
+ {
+ name: 'ap_create_folder',
+ description: 'Create a folder to group a solution of flows and tables',
+ },
{
name: 'ap_duplicate_flow',
description:
diff --git a/packages/web/src/features/chat/lib/tool-icons.ts b/packages/web/src/features/chat/lib/tool-icons.ts
index d0fbb1be41c..4b03663be80 100644
--- a/packages/web/src/features/chat/lib/tool-icons.ts
+++ b/packages/web/src/features/chat/lib/tool-icons.ts
@@ -5,6 +5,7 @@ import {
Columns3,
Copy,
FlaskConical,
+ FolderPlus,
GitBranch,
Globe,
Image,
@@ -60,6 +61,7 @@ const TOOL_ICONS: Record<string, LucideIcon> = {
ap_build_flow: Workflow,
ap_create_flow: Plus,
+ ap_create_folder: FolderPlus,
ap_add_step: Plus,
ap_update_step: Pencil,
ap_delete_step: Trash2,