Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

fix(mcp): steps built by chat with a whole reference in a list or JSON field now open (#16341)

Alexandru Andronic8ee41a4b1148
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 58c4e9e98bd..9a5627c78c1 100644
--- a/packages/server/api/src/app/mcp/tools/mcp-utils.ts
+++ b/packages/server/api/src/app/mcp/tools/mcp-utils.ts
@@ -1,4 +1,4 @@
-import { applyFunctionToValuesSync, isNil, isObject, spreadIfDefined, tryCatch } from '@activepieces/core-utils'
+import { applyFunctionToValuesSync, extractMustacheTokens, isNil, isObject, spreadIfDefined, tryCatch } from '@activepieces/core-utils'
import { AiMetadata, OutputSchema, OutputSchemaField, PieceMetadataModel, PiecePropertyMap, PropertyType } from '@activepieces/pieces-framework'
import { BranchOperator, EngineResponse, EngineResponseStatus, flowStructureUtil, McpServerType, McpToolResult, ProjectScopedMcpServer, PropertyExecutionType, PropertySettings, singleValueConditions, WorkerJobType } from '@activepieces/shared'
import type { BranchedAction, Step } from '@activepieces/shared'
@@ -675,6 +675,10 @@ function extractOptionsArray(options: unknown): Array<{ label: string, value: un
const RESOLVE_TIMEOUT_MS = 30_000
const DOUBLE_BRACED_FORMULA = /ap-formula-v(\d+)::\{\{\s*([A-Za-z_]\w*\s*\([\s\S]*?\))\s*\}\}::ap-formula-v\1/g
+const CONTAINER_PROP_TYPES = new Set<PropertyType>([PropertyType.ARRAY, PropertyType.OBJECT, PropertyType.JSON])
+
+const ContainerCheckedProp = z.object({ type: z.enum(PropertyType), properties: z.unknown().optional() })
+
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 with ap_create_folder in an earlier step than the calls that use it (never in the same step, they run at once), then pass the same folderName to each of them.')
async function executePropertyResolution({ pieceName, pieceVersion, actionOrTriggerName, propertyName, auth, input, searchValue, projectId, platformId, log }: {
@@ -761,7 +765,54 @@ async function resolveDynamicPropertySettings({ pieceName, pieceVersion, compone
const settings: PropertySettings = result?.status === 'dynamic' ? { type, schema: result.props } : { type }
return [name, settings] as const
}))
- return { ...current, ...Object.fromEntries(refreshed) }
+ return syncContainerExecutionTypes({ props: component.props, input, propertySettings: { ...current, ...Object.fromEntries(refreshed) } })
+}
+
+function syncContainerExecutionTypes({ props, input, propertySettings }: {
+ props: PiecePropertyMap
+ input: Record<string, unknown>
+ propertySettings: Record<string, PropertySettings>
+}): Record<string, PropertySettings> {
+ const topLevelFields = Object.entries(props).map(([name, prop]) => ({ name, type: containerExecutionType({ prop, value: input[name] }) }))
+ const claimedByTopLevel = new Set(topLevelFields.filter(({ type }) => !isNil(type)).map(({ name }) => name))
+ const childFields = Object.entries(props)
+ .flatMap(([name, prop]) => dynamicChildFields({ prop, value: input[name], schema: propertySettings[name]?.schema }))
+ .filter(({ name }) => !claimedByTopLevel.has(name))
+ .map(({ name, prop, value }) => ({ name, type: containerExecutionType({ prop, value }) }))
+ const updates = [...topLevelFields, ...childFields].flatMap(({ name, type }): [string, PropertySettings][] => {
+ if (isNil(type) || (propertySettings[name]?.type ?? PropertyExecutionType.MANUAL) === type) {
+ return []
+ }
+ return [[name, { ...propertySettings[name], type }]]
+ })
+ return { ...propertySettings, ...Object.fromEntries(updates) }
+}
+
+function dynamicChildFields({ prop, value, schema }: { prop: ContainerCheckedProp, value: unknown, schema: unknown }): { name: string, prop: ContainerCheckedProp, value: unknown }[] {
+ if (prop.type !== PropertyType.DYNAMIC || !isObject(value)) {
+ return []
+ }
+ const children = z.record(z.string(), ContainerCheckedProp).safeParse(schema).data ?? {}
+ return Object.entries(children).map(([name, child]) => ({ name, prop: child, value: value[name] }))
+}
+
+function containerExecutionType({ prop, value }: { prop: ContainerCheckedProp, value: unknown }): PropertyExecutionType | undefined {
+ const isStructuredArray = prop.type === PropertyType.ARRAY && !isNil(prop.properties)
+ if (!CONTAINER_PROP_TYPES.has(prop.type) || isStructuredArray) {
+ return undefined
+ }
+ if (isWholeReference(value)) {
+ return PropertyExecutionType.DYNAMIC
+ }
+ return Array.isArray(value) || isObject(value) ? PropertyExecutionType.MANUAL : undefined
+}
+
+function isWholeReference(value: unknown): boolean {
+ if (typeof value !== 'string') {
+ return false
+ }
+ const tokens = extractMustacheTokens(value)
+ return tokens.length === 1 && tokens[0].token === value.trim()
}
// Classify an action by how many records it returns, from its name. This is the signal the agent
@@ -899,6 +950,7 @@ export const mcpUtils = {
extractOptionsArray,
executePropertyResolution,
resolveDynamicPropertySettings,
+ syncContainerExecutionTypes,
RESOLVE_TIMEOUT_MS,
STEP_REFERENCE_HINT,
BRANCH_CONDITIONS_INPUT_SCHEMA,
@@ -972,6 +1024,8 @@ 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, closestName?: never }
| { error: McpToolResult, closestName?: string, piece?: never, component?: never, pieceName?: never }
+type ContainerCheckedProp = z.infer<typeof ContainerCheckedProp>
+
type ResolveFolderResult =
| { folderId: string | undefined, folderName: string | undefined, error?: never }
| { error: McpToolResult, folderId?: never, folderName?: never }
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 3dc55d6f653..7d750887f7d 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
@@ -328,6 +328,50 @@ describe('MCP Tools integration', () => {
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)
diff --git a/packages/server/api/test/unit/app/mcp/mcp-utils.test.ts b/packages/server/api/test/unit/app/mcp/mcp-utils.test.ts
index 8466373a3f4..354501d60b0 100644
--- a/packages/server/api/test/unit/app/mcp/mcp-utils.test.ts
+++ b/packages/server/api/test/unit/app/mcp/mcp-utils.test.ts
@@ -1,5 +1,5 @@
import { PropertyType } from '@activepieces/pieces-framework'
-import { AiRouterAction, BranchExecutionType, EmptyTrigger, FlowActionType, FlowTriggerType } from '@activepieces/shared'
+import { AiRouterAction, BranchExecutionType, EmptyTrigger, FlowActionType, FlowTriggerType, PropertyExecutionType } from '@activepieces/shared'
import { describe, expect, it } from 'vitest'
import { mcpUtils } from '../../../../src/app/mcp/tools/mcp-utils'
@@ -509,6 +509,125 @@ describe('mcpUtils.resolveRouterStep', () => {
})
})
+describe('mcpUtils.syncContainerExecutionTypes', () => {
+ const props = {
+ assetIds: arrayProp({ displayName: 'Asset Ids', required: true }),
+ headers: objectProp({ displayName: 'Headers', required: false }),
+ body: { type: PropertyType.JSON, displayName: 'Body', required: false },
+ rows: { type: PropertyType.ARRAY, displayName: 'Rows', required: false, properties: { name: shortText('Name') } },
+ note: shortText('Note'),
+ }
+
+ it('marks a list, object or JSON field holding one whole reference as dynamic', () => {
+ const settings = mcpUtils.syncContainerExecutionTypes({
+ props,
+ input: { assetIds: '{{step_3.output.assetIds}}', headers: ' {{trigger.headers}} ', body: '{{ step_1.body }}', note: '{{trigger.note}}' },
+ propertySettings: {},
+ })
+ expect(settings).toEqual({
+ assetIds: { type: PropertyExecutionType.DYNAMIC },
+ headers: { type: PropertyExecutionType.DYNAMIC },
+ body: { type: PropertyExecutionType.DYNAMIC },
+ })
+ })
+
+ it('leaves a value that mixes a reference with other text, or holds two references, as it was', () => {
+ const settings = mcpUtils.syncContainerExecutionTypes({
+ props,
+ input: { assetIds: '[{{step_1.a}}]', headers: '{{step_1.a}}{{step_1.b}}' },
+ propertySettings: {},
+ })
+ expect(settings).toEqual({})
+ })
+
+ it('puts a real array or object back to manual and keeps the stored schema', () => {
+ const settings = mcpUtils.syncContainerExecutionTypes({
+ props,
+ input: { assetIds: ['a', 'b'], headers: { a: '1' } },
+ propertySettings: {
+ assetIds: { type: PropertyExecutionType.DYNAMIC, schema: { kept: true } },
+ headers: { type: PropertyExecutionType.DYNAMIC },
+ },
+ })
+ expect(settings).toEqual({
+ assetIds: { type: PropertyExecutionType.MANUAL, schema: { kept: true } },
+ headers: { type: PropertyExecutionType.MANUAL },
+ })
+ })
+
+ it('leaves a list of fields alone, including one with an empty field list, where dynamic means inline item mode', () => {
+ const settings = mcpUtils.syncContainerExecutionTypes({
+ props: { ...props, emptyRows: { type: PropertyType.ARRAY, displayName: 'Empty Rows', required: false, properties: {} } },
+ input: { rows: '{{step_1.rows}}', emptyRows: '{{step_1.rows}}' },
+ propertySettings: {},
+ })
+ expect(settings).toEqual({})
+ })
+
+ it('marks a list field inside a dynamic field, keyed by its own name as the builder reads it', () => {
+ const rowDataSchema = {
+ tags: { type: PropertyType.ARRAY, displayName: 'Tags', required: false },
+ meta: { type: PropertyType.JSON, displayName: 'Meta', required: false },
+ name: { type: PropertyType.SHORT_TEXT, displayName: 'Name', required: false },
+ }
+ const settings = mcpUtils.syncContainerExecutionTypes({
+ props: { row_data: { type: PropertyType.DYNAMIC, displayName: 'Row Data', required: true, refreshers: [], props: async () => ({}) } },
+ input: { row_data: { tags: '{{trigger.body.tags}}', meta: { a: 1 }, name: '{{trigger.body.name}}' } },
+ propertySettings: { row_data: { type: PropertyExecutionType.MANUAL, schema: rowDataSchema }, meta: { type: PropertyExecutionType.DYNAMIC } },
+ })
+ expect(settings).toEqual({
+ row_data: { type: PropertyExecutionType.MANUAL, schema: rowDataSchema },
+ tags: { type: PropertyExecutionType.DYNAMIC },
+ meta: { type: PropertyExecutionType.MANUAL },
+ })
+ })
+
+ it('never lets a field inside a dynamic field overwrite the setting of a top-level field with the same name', () => {
+ const updateDataSchema = { filter_values: { type: PropertyType.ARRAY, displayName: 'Filter Values', required: false } }
+ const settings = mcpUtils.syncContainerExecutionTypes({
+ props: {
+ filter_values: arrayProp({ displayName: 'Filter Values', required: false }),
+ update_data: { type: PropertyType.DYNAMIC, displayName: 'Update Data', required: true, refreshers: [], props: async () => ({}) },
+ },
+ input: { filter_values: '{{trigger.body.ids}}', update_data: { filter_values: ['a'] } },
+ propertySettings: { filter_values: { type: PropertyExecutionType.DYNAMIC }, update_data: { type: PropertyExecutionType.MANUAL, schema: updateDataSchema } },
+ })
+ expect(settings.filter_values).toEqual({ type: PropertyExecutionType.DYNAMIC })
+ })
+
+ it('lets a field inside a dynamic field set the shared setting when the top-level field with the same name does not need one', () => {
+ const updateDataSchema = { filter_value: { type: PropertyType.ARRAY, displayName: 'Filter Value', required: false } }
+ const settings = mcpUtils.syncContainerExecutionTypes({
+ props: {
+ filter_value: shortText('Filter Value'),
+ update_data: { type: PropertyType.DYNAMIC, displayName: 'Update Data', required: true, refreshers: [], props: async () => ({}) },
+ },
+ input: { filter_value: 'abc', update_data: { filter_value: '{{trigger.body.tags}}' } },
+ propertySettings: { update_data: { type: PropertyExecutionType.MANUAL, schema: updateDataSchema } },
+ })
+ expect(settings.filter_value).toEqual({ type: PropertyExecutionType.DYNAMIC })
+ })
+
+ it('syncs a field inside a dynamic field named like an inherited object key', () => {
+ const rowDataSchema = { constructor: { type: PropertyType.ARRAY, displayName: 'Constructor', required: false } }
+ const settings = mcpUtils.syncContainerExecutionTypes({
+ props: { row_data: { type: PropertyType.DYNAMIC, displayName: 'Row Data', required: true, refreshers: [], props: async () => ({}) } },
+ input: { row_data: { constructor: '{{trigger.body.tags}}' } },
+ propertySettings: { row_data: { type: PropertyExecutionType.MANUAL, schema: rowDataSchema } },
+ })
+ expect(settings.constructor).toEqual({ type: PropertyExecutionType.DYNAMIC })
+ })
+
+ it('skips a dynamic field whose schema has not been resolved', () => {
+ const settings = mcpUtils.syncContainerExecutionTypes({
+ props: { row_data: { type: PropertyType.DYNAMIC, displayName: 'Row Data', required: true, refreshers: [], props: async () => ({}) } },
+ input: { row_data: { tags: '{{trigger.body.tags}}' } },
+ propertySettings: {},
+ })
+ expect(settings).toEqual({})
+ })
+})
+
describe('mcpUtils.normalizeFormulaText — double braces around a formula', () => {
it('turns ap-formula-v1::{{fn(...)}}::ap-formula-v1 into single braces and keeps the references inside', () => {
const fixed = mcpUtils.normalizeFormulaText('ap-formula-v1::{{formatDate(addDays(now(); -7); "YYYY-MM-DD")}}::ap-formula-v1')