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
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(mcp): AI agents can upgrade a piece step to a newer version (#16843)
ziyadevbfe4d1a4ebb7
diff --git a/brain/knowledge/ai-intelligence/mcp-server.md b/brain/knowledge/ai-intelligence/mcp-server.mdindex e4fd6d53f4d..c8620b6c057 100644--- a/brain/knowledge/ai-intelligence/mcp-server.md+++ b/brain/knowledge/ai-intelligence/mcp-server.md@@ -148,3 +148,4 @@ Paths verified 2026-07-17.client gets an unknown-tool error from the protocol, not a permission denial from inside the tool — thecopy "every call fails" is directionally right but one layer off.- **The wording of an MCP tool's `❌ …` reply is part of a contract: `test/integration/ce/mcp/mcp-tools.test.ts` asserts substrings of it verbatim.** Rewording `resolveRouterStep`'s rejection from `not a ROUTER step` to `not a router step (ROUTER or AI_ROUTER)` failed case 62 of that suite, and only in CI, because the CE integration tests need Postgres and are not run locally. Before touching any tool's user-facing text, `grep -n "<old phrase>" packages/server/api/test/integration/ce/mcp/` and either keep the asserted substring or update the assertion in the same commit.+- **`ap_update_step`'s `pieceVersion` is one-way for props the target version lacks.** Moving a step to another version (`"latest"` or an exact `x.y.z`) re-runs `keepKnownInputProps` against the new action, which drops every input key that action doesn't define, and refreshes all dynamic property schemas. A downgrade that drops a prop does not bring the value back on the next upgrade; the prop returns at its default. The version is always stored exact, never as a `~` range: `"latest"` resolves to `~x.y.z`, and flow save strips the prefix (`flowPieceUtil.getExactVersion`).diff --git a/packages/server/api/src/app/mcp/tools/ap-update-step.ts b/packages/server/api/src/app/mcp/tools/ap-update-step.tsindex d0f37eb4abb..53d2190e299 100644--- a/packages/server/api/src/app/mcp/tools/ap-update-step.ts+++ b/packages/server/api/src/app/mcp/tools/ap-update-step.ts@@ -1,5 +1,5 @@import { isNil, Permission } from '@activepieces/core-utils'-import { FlowActionType, FlowOperationRequest, FlowOperationType, flowStructureUtil, McpToolContext, McpToolDefinition, PieceActionSettings, UpdateActionRequest } from '@activepieces/shared'+import { ExactVersionType, FlowActionType, FlowOperationRequest, FlowOperationType, flowPieceUtil, flowStructureUtil, McpToolContext, McpToolDefinition, PieceActionSettings, UpdateActionRequest } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'import { z } from 'zod'import { flowService } from '../../flows/flow/flow.service'@@ -14,6 +14,7 @@ const updateStepInput = z.object({input: z.record(z.string(), z.unknown()).optional(),auth: z.string().optional(),actionName: z.string().optional(),+ pieceVersion: z.union([z.literal('latest'), ExactVersionType]).optional(),loopItems: z.string().optional(),skip: z.boolean().optional(),sourceCode: z.string().optional(),@@ -34,6 +35,7 @@ export const apUpdateStepTool = ({ mcp, userId }: McpToolContext, log: FastifyBainput: z.record(z.string(), z.unknown()).optional().describe(`Input settings for the step (key-value pairs matching the action schema). ${mcpUtils.STEP_REFERENCE_HINT}`),auth: z.string().optional().describe('Connection `externalId` from `ap_list_connections`. Pass the plain id, not a template.'),actionName: z.string().optional().describe('For PIECE steps: the action to perform. Use ap_research_pieces to get valid values.'),+ pieceVersion: z.union([z.literal('latest'), ExactVersionType]).optional().describe('For PIECE steps: move the step to another version of its piece. Pass "latest" or an exact version like "1.2.3". Inputs the new version no longer has are dropped, so pass the adjusted input in the same call.'),loopItems: z.string().optional().describe('For LOOP steps: expression for the items to iterate over'),skip: z.boolean().optional().describe('Whether to skip this step during execution'),sourceCode: z.string().optional().describe('For CODE steps only: the JavaScript/TypeScript source code. Must export a `code` function: `export const code = async (inputs) => { ... }`.'),@@ -43,7 +45,7 @@ export const apUpdateStepTool = ({ mcp, userId }: McpToolContext, log: FastifyBa},annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },execute: async (args) => {- const { flowId, stepName, displayName, input, auth: rawAuth, actionName, loopItems, skip, sourceCode, packageJson, continueOnFailure, retryOnFailure } = updateStepInput.parse(args)+ const { flowId, stepName, displayName, input, auth: rawAuth, actionName, pieceVersion: requestedPieceVersion, loopItems, skip, sourceCode, packageJson, continueOnFailure, retryOnFailure } = updateStepInput.parse(args)const auth = mcpUtils.normalizeAuth(rawAuth)const [flow, project] = await Promise.all([@@ -93,6 +95,26 @@ export const apUpdateStepTool = ({ mcp, userId }: McpToolContext, log: FastifyBareturn { content: [{ type: 'text', text: `❌ actionName can only be set on PIECE steps, but "${stepName}" is type ${step.type}.` }] }}}+ if (requestedPieceVersion !== undefined) {+ if (step.type !== FlowActionType.PIECE) {+ return { content: [{ type: 'text', text: `❌ pieceVersion can only be set on PIECE steps, but "${stepName}" is type ${step.type}.` }], isError: true }+ }+ if (requestedPieceVersion === 'latest') {+ const versionResult = await mcpUtils.resolveLatestPieceVersion({ pieceName: step.settings.pieceName, projectId: mcp.projectId, platformId: project.platformId, log })+ if (versionResult.error) {+ return versionResult.error+ }+ updatedSettings.pieceVersion = flowPieceUtil.getExactVersion(versionResult.pieceVersion)+ }+ else {+ const piece = await pieceMetadataService(log).get({ name: step.settings.pieceName, version: requestedPieceVersion, projectId: mcp.projectId, platformId: project.platformId })+ if (isNil(piece) || piece.version !== requestedPieceVersion) {+ return { content: [{ type: 'text', text: `❌ Version "${requestedPieceVersion}" of piece "${step.settings.pieceName}" not found. Pass "latest" or an exact published version like "1.2.3".` }], isError: true }+ }+ updatedSettings.pieceVersion = requestedPieceVersion+ }+ }+ const pieceVersionChanged = updatedSettings.pieceVersion !== currentSettings.pieceVersionif (rewritten.loopItems !== undefined) {if (step.type === FlowActionType.LOOP_ON_ITEMS) {updatedSettings.items = rewritten.loopItems@@ -127,7 +149,7 @@ export const apUpdateStepTool = ({ mcp, userId }: McpToolContext, log: FastifyBa})}- if (step.type === FlowActionType.PIECE && input !== undefined) {+ if (step.type === FlowActionType.PIECE && (input !== undefined || pieceVersionChanged)) {await mcpUtils.fillDefaultsForMissingOptionalProps({settings: updatedSettings,platformId: project.platformId,@@ -145,7 +167,8 @@ export const apUpdateStepTool = ({ mcp, userId }: McpToolContext, log: FastifyBareturn unknownPropsError}updatedSettings.input = knownInput- updatedSettings.propertySettings = await mcpUtils.resolveDynamicPropertySettings({ pieceName, pieceVersion, componentName: resolvedActionName, componentType: 'action', input: knownInput, propertySettings: currentSettings.propertySettings, changedKeys: Object.keys(callerInput), projectId: mcp.projectId, platformId: project.platformId, log })+ const changedKeys = Object.keys(pieceVersionChanged ? knownInput : callerInput)+ updatedSettings.propertySettings = await mcpUtils.resolveDynamicPropertySettings({ pieceName, pieceVersion, componentName: resolvedActionName, componentType: 'action', input: knownInput, propertySettings: currentSettings.propertySettings, changedKeys, projectId: mcp.projectId, platformId: project.platformId, log })}}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.tsindex d58ea2dfcfd..5680f508f42 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@@ -3181,4 +3181,83 @@ describe('MCP Tools integration', () => {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)+ })})