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(connections): replace connections of piece tools in agent steps (#16873)
Abdul61bc1bfefddb
diff --git a/packages/core/execution/src/lib/agents/tools.ts b/packages/core/execution/src/lib/agents/tools.tsindex 5e8e737bdc5..ad19d79830c 100644--- a/packages/core/execution/src/lib/agents/tools.ts+++ b/packages/core/execution/src/lib/agents/tools.ts@@ -1,97 +1,21 @@-import { AgentToolType, FieldControlMode, KnowledgeBaseSourceType, McpAuthType, McpProtocol } from '@activepieces/core-piece-types'-import { z } from 'zod'--export { AgentToolType, FieldControlMode, KnowledgeBaseSourceType, McpAuthType, McpProtocol, TASK_COMPLETION_TOOL_NAME } from '@activepieces/core-piece-types'--export const PredefinedInputField = z.object({- mode: z.enum(FieldControlMode),- value: z.unknown(),-})-export type PredefinedInputField = z.infer<typeof PredefinedInputField>--export const PredefinedInputsStructure = z.object({- auth: z.string().optional(),- fields: z.record(z.string(), PredefinedInputField),-})-export type PredefinedInputsStructure = z.infer<typeof PredefinedInputsStructure>--const AgentToolBase = {- toolName: z.string().min(1),-}--export const McpAuthNone = z.object({- type: z.literal(McpAuthType.NONE),-})--export const McpAuthAccessToken = z.object({- type: z.literal(McpAuthType.ACCESS_TOKEN),- accessToken: z.string(),-})--export const McpAuthApiKey = z.object({- type: z.literal(McpAuthType.API_KEY),- apiKey: z.string(),- apiKeyHeader: z.string(),-})--export const McpAuthHeaders = z.object({- type: z.literal(McpAuthType.HEADERS),- headers: z.record(z.string(), z.string()),-})--export const McpAuthConfig = z.discriminatedUnion('type', [- McpAuthNone,+export {+ AgentFlowTool,+ AgentKnowledgeBaseTool,+ AgentMcpTool,+ AgentPieceTool,+ AgentPieceToolMetadata,+ AgentTool,+ AgentToolType,+ FieldControlMode,+ KnowledgeBaseSourceType,McpAuthAccessToken,McpAuthApiKey,+ McpAuthConfig,McpAuthHeaders,-])-export type McpAuthConfig = z.infer<typeof McpAuthConfig>--export const AgentPieceToolMetadata = z.object({- pieceName: z.string(),- pieceVersion: z.string(),- actionName: z.string(),- predefinedInput: PredefinedInputsStructure.optional(),-})-export type AgentPieceToolMetadata = z.infer<typeof AgentPieceToolMetadata>--export const AgentPieceTool = z.object({- type: z.literal(AgentToolType.PIECE),- ...AgentToolBase,- pieceMetadata: AgentPieceToolMetadata,-})-export type AgentPieceTool = z.infer<typeof AgentPieceTool>--export const AgentFlowTool = z.object({- type: z.literal(AgentToolType.FLOW),- ...AgentToolBase,- externalFlowId: z.string(),- flowDisplayName: z.string().optional(),-})-export type AgentFlowTool = z.infer<typeof AgentFlowTool>--export const AgentMcpTool = z.object({- type: z.literal(AgentToolType.MCP),- ...AgentToolBase,- serverUrl: z.string().url(),- protocol: z.nativeEnum(McpProtocol),- auth: McpAuthConfig,-})-export type AgentMcpTool = z.infer<typeof AgentMcpTool>--export const AgentKnowledgeBaseTool = z.object({- type: z.literal(AgentToolType.KNOWLEDGE_BASE),- ...AgentToolBase,- sourceType: z.nativeEnum(KnowledgeBaseSourceType),- sourceId: z.string(),- sourceName: z.string(),-})-export type AgentKnowledgeBaseTool = z.infer<typeof AgentKnowledgeBaseTool>--export const AgentTool = z.discriminatedUnion('type', [- AgentPieceTool,- AgentFlowTool,- AgentMcpTool,- AgentKnowledgeBaseTool,-])-export type AgentTool = z.infer<typeof AgentTool>+ McpAuthNone,+ McpAuthType,+ McpProtocol,+ PredefinedInputField,+ PredefinedInputsStructure,+ TASK_COMPLETION_TOOL_NAME,+} from '@activepieces/core-piece-types'diff --git a/packages/core/execution/src/lib/flows/util/flow-structure-util.ts b/packages/core/execution/src/lib/flows/util/flow-structure-util.tsindex 1cd6c84239a..009376250cb 100644--- a/packages/core/execution/src/lib/flows/util/flow-structure-util.ts+++ b/packages/core/execution/src/lib/flows/util/flow-structure-util.ts@@ -1,5 +1,5 @@-import { AgentPieceProps } from '@activepieces/core-piece-types'-import { isNil, unique } from '@activepieces/core-utils'+import { AgentPieceProps, AgentPieceTool, AgentTool, AgentToolType } from '@activepieces/core-piece-types'+import { connectionTemplate, isNil, isObject, unique } from '@activepieces/core-utils'import { ActivepiecesError, ErrorCode } from '@activepieces/core-utils'import { BranchCondition, BranchedAction, BranchExecutionType, CodeAction, emptyCondition, FlowAction, FlowActionType, PieceAction } from '../actions/action'import { FlowVersion } from '../flow-version'@@ -280,19 +280,83 @@ function isAgentPiece(action: Step) {}function extractConnectionIds(flowVersion: FlowVersion): string[] {- const triggerAuthIds = flowVersion.trigger.settings?.input?.auth- ? extractConnectionIdsFromAuth(flowVersion.trigger.settings.input.auth)- : []+ const stepAuthIds = getAllSteps(flowVersion.trigger).flatMap((step) =>+ step.settings?.input?.auth ? extractConnectionIdsFromAuth(step.settings.input.auth) : [],+ )+ return unique([...stepAuthIds, ...extractAgentToolsConnectionIds(flowVersion)])+}++function getAgentToolConnectionId(tool: unknown): string | undefined {+ const pieceTool = AgentPieceTool.safeParse(tool)+ if (!pieceTool.success) {+ return undefined+ }+ return connectionTemplate.unwrapExternalId(pieceTool.data.pieceMetadata.predefinedInput?.auth) ?? undefined+}++function extractAgentToolsConnectionIds(flowVersion: FlowVersion): string[] {+ const connectionIds = getAllSteps(flowVersion.trigger).flatMap((step) => getAgentToolsInlinedInStep(step).map(getAgentToolConnectionId))+ return unique(connectionIds.filter((connectionId): connectionId is string => !isNil(connectionId) && connectionId !== ''))+}++function getAgentToolsInlinedInStep(step: Step): unknown[] {+ if (!isAgentPiece(step)) {+ return []+ }+ const agentTools = step.settings.input[AgentPieceProps.AGENT_TOOLS]+ return Array.isArray(agentTools) ? agentTools : []+}++function replaceConnection({ flowVersion, sourceExternalId, targetExternalId }: ReplaceConnectionParams): FlowVersion {+ return transferFlow(flowVersion, (step) => {+ const input = step.settings?.input+ if (!isObject(input)) {+ return step+ }+ const replacesAuth = input['auth'] === `{{connections['${sourceExternalId}']}}`+ const agentTools = getAgentToolsInlinedInStep(step)+ const replacesAgentTools = agentTools.some((tool) => getAgentToolConnectionId(tool) === sourceExternalId)+ if (!replacesAuth && !replacesAgentTools) {+ return step+ }+ return {+ ...step,+ settings: {+ ...step.settings,+ input: {+ ...input,+ ...(replacesAuth && { auth: `{{connections['${targetExternalId}']}}` }),+ ...(replacesAgentTools && { [AgentPieceProps.AGENT_TOOLS]: agentTools.map((tool) => replaceInlinedAgentToolConnection({ tool, sourceExternalId, targetExternalId })) }),+ },+ },+ }+ })+}- const stepAuthIds = flowStructureUtil- .getAllSteps(flowVersion.trigger)- .flatMap(step =>- step.settings?.input?.auth- ? extractConnectionIdsFromAuth(step.settings.input.auth)- : [],- )+function replaceInlinedAgentToolConnection({ tool, sourceExternalId, targetExternalId }: { tool: unknown } & ReplaceToolConnectionParams): unknown {+ const pieceTool = AgentPieceTool.safeParse(tool)+ if (!pieceTool.success) {+ return tool+ }+ const replacedTool = replaceAgentToolConnection({ tool: pieceTool.data, sourceExternalId, targetExternalId })+ return replacedTool === pieceTool.data ? tool : replacedTool+}- return Array.from(new Set([...triggerAuthIds, ...stepAuthIds]))+function replaceAgentToolConnection({ tool, sourceExternalId, targetExternalId }: { tool: AgentTool } & ReplaceToolConnectionParams): AgentTool {+ if (tool.type !== AgentToolType.PIECE) {+ return tool+ }+ const predefinedInput = tool.pieceMetadata.predefinedInput+ if (isNil(predefinedInput) || connectionTemplate.unwrapExternalId(predefinedInput.auth) !== sourceExternalId) {+ return tool+ }+ return {+ ...tool,+ pieceMetadata: {+ ...tool.pieceMetadata,+ predefinedInput: { ...predefinedInput, auth: targetExternalId },+ },+ }}export const flowStructureUtil = {@@ -320,4 +384,16 @@ export const flowStructureUtil = {isAgentPiece,isBranchedAction,extractAgentIds,-}\ No newline at end of file+ getAgentToolConnectionId,+ extractAgentToolsConnectionIds,+ replaceAgentToolConnection,+ replaceConnection,+}++type ReplaceConnectionParams = {+ flowVersion: FlowVersion+ sourceExternalId: string+ targetExternalId: string+}++type ReplaceToolConnectionParams = Omit<ReplaceConnectionParams, 'flowVersion'>diff --git a/packages/core/execution/test/flow/replace-connection.test.ts b/packages/core/execution/test/flow/replace-connection.test.tsnew file mode 100644index 00000000000..d91427eaeb5--- /dev/null+++ b/packages/core/execution/test/flow/replace-connection.test.ts@@ -0,0 +1,167 @@+import { AgentMcpTool, AgentPieceTool, AgentToolType, FlowAction, FlowActionType, flowStructureUtil, McpAuthType, McpProtocol, FlowTriggerType, FlowVersion, FlowVersionState, PieceAction } from '../../src'++function pieceStep({ name, auth, nextAction }: { name: string, auth?: string, nextAction?: FlowAction }): PieceAction {+ return {+ name,+ type: FlowActionType.PIECE,+ valid: true,+ displayName: name,+ lastUpdatedDate: '2026-10-20T00:00:00.000Z',+ settings: {+ pieceName: '@activepieces/piece-slack',+ pieceVersion: '0.0.1',+ actionName: 'send_message',+ input: { auth, channel: 'general' },+ propertySettings: {},+ },+ nextAction,+ }+}++function flowWith(head: FlowAction): FlowVersion {+ return {+ id: 'version',+ created: '2026-10-20T00:00:00.000Z',+ updated: '2026-10-20T00:00:00.000Z',+ flowId: 'flow',+ displayName: 'Flow',+ updatedBy: null,+ valid: true,+ schemaVersion: null,+ agentIds: [],+ state: FlowVersionState.DRAFT,+ connectionIds: [],+ backupFiles: null,+ notes: [],+ trigger: {+ name: 'trigger',+ type: FlowTriggerType.EMPTY,+ valid: true,+ displayName: 'Trigger',+ lastUpdatedDate: '2026-10-20T00:00:00.000Z',+ settings: {},+ nextAction: head,+ },+ }+}++function authOf(flowVersion: FlowVersion, stepName: string): unknown {+ return flowStructureUtil.getStepOrThrow(stepName, flowVersion.trigger).settings.input.auth+}++describe('flowStructureUtil.replaceConnection', () => {+ it('points every step that uses the source connection at the target connection and leaves the rest alone', () => {+ const flowVersion = flowWith(pieceStep({+ name: 'step_1',+ auth: "{{connections['old']}}",+ nextAction: pieceStep({+ name: 'step_2',+ auth: "{{connections['other']}}",+ nextAction: pieceStep({ name: 'step_3', auth: "{{connections['old']}}" }),+ }),+ }))++ const result = flowStructureUtil.replaceConnection({ flowVersion: flowVersion, sourceExternalId: 'old', targetExternalId: 'new' })++ expect(authOf(result, 'step_1')).toBe("{{connections['new']}}")+ expect(authOf(result, 'step_2')).toBe("{{connections['other']}}")+ expect(authOf(result, 'step_3')).toBe("{{connections['new']}}")+ expect(flowStructureUtil.getStepOrThrow('step_1', result.trigger).settings.input.channel).toBe('general')+ expect(flowStructureUtil.extractConnectionIds(result)).toEqual(['new', 'other'])+ })++ it('does not change a step whose auth points at a connection that only starts with the source name', () => {+ const flowVersion = flowWith(pieceStep({ name: 'step_1', auth: "{{connections['old-2']}}" }))++ const result = flowStructureUtil.replaceConnection({ flowVersion: flowVersion, sourceExternalId: 'old', targetExternalId: 'new' })++ expect(authOf(result, 'step_1')).toBe("{{connections['old-2']}}")+ })++ it('points agent tools that use the source connection at the target connection, in plain or wrapped form', () => {+ const agentStep: PieceAction = {+ ...pieceStep({ name: 'step_1' }),+ settings: {+ pieceName: '@activepieces/piece-ai',+ pieceVersion: '0.6.0',+ actionName: 'run_agent',+ input: {+ agentTools: [+ slackTool({ toolName: 'send', auth: 'old' }),+ slackTool({ toolName: 'reply', auth: "{{connections['old']}}" }),+ slackTool({ toolName: 'read', auth: 'other' }),+ mcpTool,+ ],+ },+ propertySettings: {},+ },+ }+ const flowVersion = flowWith(agentStep)+ expect(flowStructureUtil.extractAgentToolsConnectionIds(flowVersion)).toEqual(['old', 'other'])+ expect(flowStructureUtil.extractConnectionIds(flowVersion)).toEqual(['old', 'other'])++ const result = flowStructureUtil.replaceConnection({ flowVersion, sourceExternalId: 'old', targetExternalId: 'new' })++ expect(flowStructureUtil.getStepOrThrow('step_1', result.trigger).settings.input.agentTools).toEqual([+ slackTool({ toolName: 'send', auth: 'new' }),+ slackTool({ toolName: 'reply', auth: 'new' }),+ slackTool({ toolName: 'read', auth: 'other' }),+ mcpTool,+ ])+ })++ it('ignores agentTools on a step that is not the AI piece', () => {+ const step = pieceStep({ name: 'step_1' })+ const otherPieceStep: PieceAction = {+ ...step,+ settings: { ...step.settings, input: { agentTools: [slackTool({ toolName: 'send', auth: 'old' })] } },+ }+ const flowVersion = flowWith(otherPieceStep)+ expect(flowStructureUtil.extractAgentToolsConnectionIds(flowVersion)).toEqual([])++ const result = flowStructureUtil.replaceConnection({ flowVersion, sourceExternalId: 'old', targetExternalId: 'new' })++ expect(flowStructureUtil.getStepOrThrow('step_1', result.trigger).settings.input.agentTools).toEqual([slackTool({ toolName: 'send', auth: 'old' })])+ })+})++describe('flowStructureUtil.replaceAgentToolConnection', () => {+ it('points a piece tool that uses the source connection, in plain or wrapped form, at the target connection', () => {+ const tools = [+ slackTool({ toolName: 'send', auth: 'old' }),+ slackTool({ toolName: 'reply', auth: "{{connections['old']}}" }),+ slackTool({ toolName: 'read', auth: 'other' }),+ mcpTool,+ ]++ const result = tools.map((tool) => flowStructureUtil.replaceAgentToolConnection({ tool, sourceExternalId: 'old', targetExternalId: 'new' }))++ expect(result).toEqual([+ slackTool({ toolName: 'send', auth: 'new' }),+ slackTool({ toolName: 'reply', auth: 'new' }),+ slackTool({ toolName: 'read', auth: 'other' }),+ mcpTool,+ ])+ })+})++function slackTool({ toolName, auth }: { toolName: string, auth: string }): AgentPieceTool {+ return {+ type: AgentToolType.PIECE,+ toolName,+ pieceMetadata: {+ pieceName: '@activepieces/piece-slack',+ pieceVersion: '0.0.1',+ actionName: 'send_message',+ predefinedInput: { auth, fields: {} },+ },+ }+}++const mcpTool: AgentMcpTool = {+ type: AgentToolType.MCP,+ toolName: 'mcp',+ serverUrl: 'https://example.com',+ protocol: McpProtocol.STREAMABLE_HTTP,+ auth: { type: McpAuthType.NONE },+}