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
fix(chat): ask before deleting tables, records, fields or flows (#15881)
Hazem Adelf783bf3bb4f1
diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/agent-worker-tools.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/agent-worker-tools.tsindex a88d6f43c8b..0120dc0b03e 100644--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/agent-worker-tools.ts+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/agent-worker-tools.ts@@ -3,7 +3,7 @@ import { createCrossProjectTools } from './tools/cross-project-tools'import { createDisplayTools } from './tools/display-tools'import { createEmailTools } from './tools/email-tools'import { createEventEmitter } from './tools/event-emitter'-import { wrapTestFlowGate } from './tools/flow-gate-tools'+import { wrapDeleteGate, wrapTestFlowGate } from './tools/flow-gate-tools'import { createAgentSurfaceTools, createBuildPlanTools, createLocalTools, createPhaseTools, createStructuredOutputTool, createThinkingTools } from './tools/session-tools'import { extractResultText, extractUserFacingError, isSuccessResult, normalizePieceName, TOOL_EXECUTION_TIMEOUT_MS, truncateLargeResult, withToolTimeout, wrapToolsWithTaint } from './tools/tool-primitives'import { createImageTools, createProviderSearchTools, createScrapeTools, createSearchTools, createWebTools, falImageGenerator, providerImageGenerator } from './tools/web-media-tools'@@ -26,6 +26,7 @@ export const agentWorkerTools = {providerImageGenerator,createEmailTools,wrapTestFlowGate,+ wrapDeleteGate,createThinkingTools,createPhaseTools,createBuildPlanTools,diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.tsindex dabef7c7f83..379a5b9ce3d 100644--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts@@ -697,20 +697,21 @@ function buildToolSet({ ctx, eventEmitter, log, phaseState, taintState, mcpToolSeventEmitter,getProjectId: () => projectState.projectId,})+ const timedMcpTools = agentMcpClient.withToolTimeouts({+ mcpToolSet,+ brokenConnectors,+ taintState,+ getSelectedAuth: ({ pieceName }) => selectedConnectionByPiece.get(pieceName),+ saveLargeResult: async ({ json, fileName }) => {+ const { data: saved } = await tryCatch(() => ctx.apiClient.saveAgentFile({+ platformId, conversationId, data: Buffer.from(json, 'utf8'), mediaType: 'application/json',+ ...spreadIfDefined('projectId', projectState.projectId ?? undefined), fileName,+ }))+ return saved?.fileId ?? null+ },+ })const mcpTools = agentWorkerTools.wrapTestFlowGate({- mcpTools: agentMcpClient.withToolTimeouts({- mcpToolSet,- brokenConnectors,- taintState,- getSelectedAuth: ({ pieceName }) => selectedConnectionByPiece.get(pieceName),- saveLargeResult: async ({ json, fileName }) => {- const { data: saved } = await tryCatch(() => ctx.apiClient.saveAgentFile({- platformId, conversationId, data: Buffer.from(json, 'utf8'), mediaType: 'application/json',- ...spreadIfDefined('projectId', projectState.projectId ?? undefined), fileName,- }))- return saved?.fileId ?? null- },- }),+ mcpTools: agentWorkerTools.wrapDeleteGate({ mcpTools: timedMcpTools, waitForApproval, storePendingGate, eventEmitter }),checkFlowWrites: async (flowId) => {const response = await ctx.apiClient.executeAgentTool({ toolName: '__flow_write_check', toolInput: { flowId }, platformId, userId, source, conversationId })return response.resultdiff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/flow-gate-tools.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/flow-gate-tools.tsindex cf6f71fc56a..9b89f2d4b74 100644--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/flow-gate-tools.ts+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/flow-gate-tools.ts@@ -64,3 +64,57 @@ export function wrapTestFlowGate({ mcpTools, checkFlowWrites, waitForApproval, sreturn { ...mcpTools, ap_test_flow: wrapped }}+export function wrapDeleteGate({ mcpTools, waitForApproval, storePendingGate, eventEmitter }: {+ mcpTools: Record<string, unknown>+ waitForApproval: (params: { gateId: string, timeoutMs?: number }) => Promise<GateDecision>+ storePendingGate: (params: { gateId: string, toolName: string, displayName: string, toolInput: Record<string, unknown> }) => Promise<void>+ eventEmitter: AgentEventEmitter+}): Record<string, unknown> {+ const gated = Object.entries(DELETE_GATES).flatMap(([toolName, { labelOf, deletes }]) => {+ const deleteTool = mcpTools[toolName]+ if (!isObject(deleteTool) || !toolHasExecute(deleteTool)) {+ return []+ }+ const originalExecute = deleteTool.execute.bind(deleteTool)+ return [[toolName, Object.assign({}, deleteTool, {+ execute: async (args: unknown, options?: ToolExecutionOptions<undefined>) => {+ const gateId = options?.toolCallId+ const toolInput = isObject(args) ? args : {}+ if (!gateId || !deletes(toolInput)) {+ return originalExecute(args, options)+ }+ const label = labelOf(toolInput)+ eventEmitter.emitActionPreview({ toolCallId: gateId, pieceName: '', actionName: toolName, actionDisplayName: label, input: toolInput, isBatch: false })+ await tryCatch(() => storePendingGate({ gateId, toolName, displayName: label, toolInput }))+ const decision = await waitForApproval({ gateId })+ if (decision.outcome === 'approved') {+ return originalExecute(args, options)+ }+ const text = decision.outcome === 'timeout' ? gateNoResponseMessage('delete approval') : 'The user declined this delete. Do not retry it; ask what they want instead.'+ return { content: [{ type: 'text', text }] }+ },+ })]]+ })+ return { ...mcpTools, ...Object.fromEntries(gated) }+}++function textField({ toolInput, key }: { toolInput: Record<string, unknown>, key: string }): string {+ const value = toolInput[key]+ return typeof value === 'string' ? value : 'unknown'+}++const DELETE_GATES: Record<string, { labelOf: (toolInput: Record<string, unknown>) => string, deletes: (toolInput: Record<string, unknown>) => boolean }> = {+ ap_delete_records: {+ labelOf: (toolInput) => {+ const count = Array.isArray(toolInput['recordIds']) ? toolInput['recordIds'].length : 0+ return `Delete ${count} ${count === 1 ? 'record' : 'records'} from table ${textField({ toolInput, key: 'tableId' })}`+ },+ deletes: () => true,+ },+ ap_delete_table: { labelOf: (toolInput) => `Delete table ${textField({ toolInput, key: 'tableId' })}`, deletes: () => true },+ ap_delete_flow: { labelOf: (toolInput) => `Delete flow ${textField({ toolInput, key: 'flowId' })}`, deletes: () => true },+ ap_manage_fields: {+ labelOf: (toolInput) => `Delete field ${textField({ toolInput, key: 'fieldId' })} from table ${textField({ toolInput, key: 'tableId' })}`,+ deletes: (toolInput) => toolInput['operation'] === 'DELETE',+ },+}diff --git a/packages/server/worker/test/lib/execute/jobs/ee/agent/delete-gate.test.ts b/packages/server/worker/test/lib/execute/jobs/ee/agent/delete-gate.test.tsnew file mode 100644index 00000000000..b58979757c5--- /dev/null+++ b/packages/server/worker/test/lib/execute/jobs/ee/agent/delete-gate.test.ts@@ -0,0 +1,82 @@+import { isObject } from '@activepieces/core-utils'+import { SendAgentEventRequest } from '@activepieces/shared'+import { describe, expect, it, vi } from 'vitest'+import { agentWorkerTools, GateDecision } from '../../../../../../src/lib/execute/jobs/ee/agent/agent-worker-tools'+import { toolHasExecute } from '../../../../../../src/lib/execute/jobs/ee/agent/tools/tool-primitives'++describe('wrapDeleteGate', () => {+ it('asks the user before every delete, and deletes only after they approve', async () => {+ const { tools, deleteRecords, waitForApproval, sentEvents } = setup({ decision: 'approved' })++ await tools.ap_delete_records.execute({ tableId: 't1', recordIds: ['r1', 'r2'], displayName: 'Delete a harmless temp row' }, { toolCallId: 'call-1' })++ expect(JSON.stringify(sentEvents)).toContain('Delete 2 records from table t1')+ expect(JSON.stringify(sentEvents.map((event) => event.type))).toContain('ACTION_PREVIEW')+ expect(waitForApproval).toHaveBeenCalledWith({ gateId: 'call-1' })+ expect(deleteRecords).toHaveBeenCalledTimes(1)+ })++ it('does not delete when the user declines', async () => {+ const { tools, deleteRecords } = setup({ decision: 'declined' })++ const result = await tools.ap_delete_records.execute({ tableId: 't1' }, { toolCallId: 'call-1' })++ expect(deleteRecords).not.toHaveBeenCalled()+ expect(JSON.stringify(result)).toContain('declined')+ })++ it('asks before deleting a table field, but not before renaming one', async () => {+ const { tools, manageFields, waitForApproval } = setup({ decision: 'approved' })++ await tools.ap_manage_fields.execute({ tableId: 't1', operation: 'UPDATE', fieldId: 'f1', name: 'Title' }, { toolCallId: 'call-2' })+ expect(waitForApproval).not.toHaveBeenCalled()++ await tools.ap_manage_fields.execute({ tableId: 't1', operation: 'DELETE', fieldId: 'f1' }, { toolCallId: 'call-3' })+ expect(waitForApproval).toHaveBeenCalledWith({ gateId: 'call-3' })+ expect(manageFields).toHaveBeenCalledTimes(2)+ })++ it('leaves other writes alone', async () => {+ const { tools, insertRecords, waitForApproval } = setup({ decision: 'approved' })++ await tools.ap_insert_records.execute({ tableId: 't1' }, { toolCallId: 'call-4' })++ expect(waitForApproval).not.toHaveBeenCalled()+ expect(insertRecords).toHaveBeenCalledTimes(1)+ })+})++function setup({ decision }: { decision: GateDecision['outcome'] }): {+ tools: Record<string, { execute: (args: unknown, options: { toolCallId: string }) => Promise<unknown> }>+ deleteRecords: ReturnType<typeof vi.fn>+ insertRecords: ReturnType<typeof vi.fn>+ manageFields: ReturnType<typeof vi.fn>+ waitForApproval: ReturnType<typeof vi.fn>+ sentEvents: SendAgentEventRequest['event'][]+} {+ const deleteRecords = vi.fn(async () => TOOL_RESULT)+ const insertRecords = vi.fn(async () => TOOL_RESULT)+ const manageFields = vi.fn(async () => TOOL_RESULT)+ const waitForApproval = vi.fn(async (): Promise<GateDecision> => ({ outcome: decision }))+ const sentEvents: SendAgentEventRequest['event'][] = []+ const eventEmitter = agentWorkerTools.createEventEmitter({+ sendEvent: async ({ event }) => {+ sentEvents.push(event)+ },+ userId: 'user-1',+ conversationId: 'conv-1',+ })+ const wrapped = agentWorkerTools.wrapDeleteGate({+ mcpTools: { ap_delete_records: { execute: deleteRecords }, ap_insert_records: { execute: insertRecords }, ap_manage_fields: { execute: manageFields } },+ waitForApproval,+ storePendingGate: async () => undefined,+ eventEmitter,+ })+ return { tools: toolsOf(wrapped), deleteRecords, insertRecords, manageFields, waitForApproval, sentEvents }+}++function toolsOf(wrapped: Record<string, unknown>): Record<string, { execute: (args: unknown, options: { toolCallId: string }) => Promise<unknown> }> {+ return Object.fromEntries(Object.entries(wrapped).flatMap(([name, value]) => isObject(value) && toolHasExecute(value) ? [[name, value]] : []))+}++const TOOL_RESULT = { content: [{ type: 'text', text: 'done' }] }diff --git a/packages/web/src/features/chat/lib/use-chat.ts b/packages/web/src/features/chat/lib/use-chat.tsindex 434289656f5..fe1c1676a1e 100644--- a/packages/web/src/features/chat/lib/use-chat.ts+++ b/packages/web/src/features/chat/lib/use-chat.ts@@ -89,6 +89,13 @@ function restoreReceiptsIntoStore({const MAX_FILE_SIZE = 10 * 1024 * 1024;const AGENT_POLL_INTERVAL_MS = 5_000;+const TOOL_GATES_WITHOUT_A_PIECE = new Set([+ 'ap_test_flow',+ 'ap_delete_records',+ 'ap_delete_table',+ 'ap_delete_flow',+ 'ap_manage_fields',+]);function buildToolCallMetaFromGate(gate: PendingGate,@@ -126,13 +133,13 @@ function buildToolCallMetaFromGate(? (gateInput.items as Record<string, unknown>[]).slice(0, 3): undefined,};- } else if (gate.toolName === 'ap_test_flow') {+ } else if (TOOL_GATES_WITHOUT_A_PIECE.has(gate.toolName)) {actionPreview = {toolCallId: gate.gateId,pieceName: '',- actionName: 'ap_test_flow',+ actionName: gate.toolName,actionDisplayName: gate.displayName,- input: {},+ input: gate.toolName === 'ap_test_flow' ? {} : gateInput,isBatch: false,};}