mirror of
https://github.com/czlonkowski/n8n-mcp.git
synced 2026-03-22 18:33:08 +00:00
Add transferWorkflow diff operation to move workflows between n8n projects:
- TransferWorkflowOperation type with destinationProjectId field
- WorkflowDiffEngine validates and tracks transfer intent
- Handler calls PUT /workflows/{id}/transfer after update
- N8nApiClient.transferWorkflow() method
- Zod schema validates destinationProjectId is non-empty
- Tool description and documentation updated
- inferIntentFromOperations case for transfer
Also fixes two pre-existing bugs found during review:
- continueOnError path now properly extracts/propagates activation flags
- Debug log in updateConnectionReferences shows correct old name
Based on work by @djakielski in PR #645.
Conceived by Romuald Członkowski - https://www.aiadvisors.pl/en
This commit is contained in:
committed by
GitHub
parent
14962a39b6
commit
47a1cb135d
@@ -68,6 +68,8 @@ const workflowDiffSchema = z.object({
|
||||
settings: z.any().optional(),
|
||||
name: z.string().optional(),
|
||||
tag: z.string().optional(),
|
||||
// Transfer operation
|
||||
destinationProjectId: z.string().min(1).optional(),
|
||||
// Aliases: LLMs often use "id" instead of "nodeId" — accept both
|
||||
id: z.string().optional(),
|
||||
}).transform((op) => {
|
||||
@@ -370,6 +372,26 @@ export async function handleUpdatePartialWorkflow(
|
||||
}
|
||||
}
|
||||
|
||||
// Handle project transfer if requested (before activation so workflow is in target project first)
|
||||
let transferMessage = '';
|
||||
if (diffResult.transferToProjectId) {
|
||||
try {
|
||||
await client.transferWorkflow(input.id, diffResult.transferToProjectId);
|
||||
transferMessage = ` Workflow transferred to project ${diffResult.transferToProjectId}.`;
|
||||
} catch (transferError) {
|
||||
logger.error('Failed to transfer workflow to project', transferError);
|
||||
return {
|
||||
success: false,
|
||||
saved: true,
|
||||
error: 'Workflow updated successfully but project transfer failed',
|
||||
details: {
|
||||
workflowUpdated: true,
|
||||
transferError: transferError instanceof Error ? transferError.message : 'Unknown error'
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Handle activation/deactivation if requested
|
||||
let finalWorkflow = updatedWorkflow;
|
||||
let activationMessage = '';
|
||||
@@ -454,7 +476,7 @@ export async function handleUpdatePartialWorkflow(
|
||||
nodeCount: finalWorkflow.nodes?.length || 0,
|
||||
operationsApplied: diffResult.operationsApplied
|
||||
},
|
||||
message: `Workflow "${finalWorkflow.name}" updated successfully. Applied ${diffResult.operationsApplied} operations.${activationMessage} Use n8n_get_workflow with mode 'structure' to verify current state.`,
|
||||
message: `Workflow "${finalWorkflow.name}" updated successfully. Applied ${diffResult.operationsApplied} operations.${transferMessage}${activationMessage} Use n8n_get_workflow with mode 'structure' to verify current state.`,
|
||||
details: {
|
||||
applied: diffResult.applied,
|
||||
failed: diffResult.failed,
|
||||
@@ -559,6 +581,8 @@ function inferIntentFromOperations(operations: any[]): string {
|
||||
return 'Activate workflow';
|
||||
case 'deactivateWorkflow':
|
||||
return 'Deactivate workflow';
|
||||
case 'transferWorkflow':
|
||||
return `Transfer workflow to project ${op.destinationProjectId || ''}`.trim();
|
||||
default:
|
||||
return `Workflow ${op.type}`;
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ export const n8nUpdatePartialWorkflowDoc: ToolDocumentation = {
|
||||
name: 'n8n_update_partial_workflow',
|
||||
category: 'workflow_management',
|
||||
essentials: {
|
||||
description: 'Update workflow incrementally with diff operations. Types: addNode, removeNode, updateNode, moveNode, enable/disableNode, addConnection, removeConnection, rewireConnection, cleanStaleConnections, replaceConnections, updateSettings, updateName, add/removeTag, activateWorkflow, deactivateWorkflow. Supports smart parameters (branch, case) for multi-output nodes. Full support for AI connections (ai_languageModel, ai_tool, ai_memory, ai_embedding, ai_vectorStore, ai_document, ai_textSplitter, ai_outputParser).',
|
||||
description: 'Update workflow incrementally with diff operations. Types: addNode, removeNode, updateNode, moveNode, enable/disableNode, addConnection, removeConnection, rewireConnection, cleanStaleConnections, replaceConnections, updateSettings, updateName, add/removeTag, activateWorkflow, deactivateWorkflow, transferWorkflow. Supports smart parameters (branch, case) for multi-output nodes. Full support for AI connections (ai_languageModel, ai_tool, ai_memory, ai_embedding, ai_vectorStore, ai_document, ai_textSplitter, ai_outputParser).',
|
||||
keyParameters: ['id', 'operations', 'continueOnError'],
|
||||
example: 'n8n_update_partial_workflow({id: "wf_123", operations: [{type: "rewireConnection", source: "IF", from: "Old", to: "New", branch: "true"}]})',
|
||||
performance: 'Fast (50-200ms)',
|
||||
@@ -22,7 +22,8 @@ export const n8nUpdatePartialWorkflowDoc: ToolDocumentation = {
|
||||
'Batch AI component connections for atomic updates',
|
||||
'Auto-sanitization: ALL nodes auto-fixed during updates (operator structures, missing metadata)',
|
||||
'Node renames automatically update all connection references - no manual connection operations needed',
|
||||
'Activate/deactivate workflows: Use activateWorkflow/deactivateWorkflow operations (requires activatable triggers like webhook/schedule)'
|
||||
'Activate/deactivate workflows: Use activateWorkflow/deactivateWorkflow operations (requires activatable triggers like webhook/schedule)',
|
||||
'Transfer workflows between projects: Use transferWorkflow with destinationProjectId (enterprise feature)'
|
||||
]
|
||||
},
|
||||
full: {
|
||||
@@ -55,6 +56,9 @@ export const n8nUpdatePartialWorkflowDoc: ToolDocumentation = {
|
||||
- **activateWorkflow**: Activate the workflow to enable automatic execution via triggers
|
||||
- **deactivateWorkflow**: Deactivate the workflow to prevent automatic execution
|
||||
|
||||
### Project Management Operations (1 type):
|
||||
- **transferWorkflow**: Transfer the workflow to a different project. Requires \`destinationProjectId\`. Enterprise/cloud feature.
|
||||
|
||||
## Smart Parameters for Multi-Output Nodes
|
||||
|
||||
For **IF nodes**, use semantic 'branch' parameter instead of technical sourceIndex:
|
||||
@@ -345,7 +349,10 @@ n8n_update_partial_workflow({
|
||||
'// Migrate from deprecated continueOnFail to onError\nn8n_update_partial_workflow({id: "rm2", operations: [{type: "updateNode", nodeName: "HTTP Request", updates: {continueOnFail: null, onError: "continueErrorOutput"}}]})',
|
||||
'// Remove nested property\nn8n_update_partial_workflow({id: "rm3", operations: [{type: "updateNode", nodeName: "API Request", updates: {"parameters.authentication": null}}]})',
|
||||
'// Remove multiple properties\nn8n_update_partial_workflow({id: "rm4", operations: [{type: "updateNode", nodeName: "Data Processor", updates: {continueOnFail: null, alwaysOutputData: null, "parameters.legacy_option": null}}]})',
|
||||
'// Remove entire array property\nn8n_update_partial_workflow({id: "rm5", operations: [{type: "updateNode", nodeName: "HTTP Request", updates: {"parameters.headers": null}}]})'
|
||||
'// Remove entire array property\nn8n_update_partial_workflow({id: "rm5", operations: [{type: "updateNode", nodeName: "HTTP Request", updates: {"parameters.headers": null}}]})',
|
||||
'\n// ============ PROJECT TRANSFER EXAMPLES ============',
|
||||
'// Transfer workflow to a different project\nn8n_update_partial_workflow({id: "tf1", operations: [{type: "transferWorkflow", destinationProjectId: "project-abc-123"}]})',
|
||||
'// Transfer and activate in one call\nn8n_update_partial_workflow({id: "tf2", operations: [{type: "transferWorkflow", destinationProjectId: "project-abc-123"}, {type: "activateWorkflow"}]})'
|
||||
],
|
||||
useCases: [
|
||||
'Rewire connections when replacing nodes',
|
||||
@@ -363,7 +370,8 @@ n8n_update_partial_workflow({
|
||||
'Add fallback language models to AI Agents',
|
||||
'Configure Vector Store retrieval systems',
|
||||
'Swap language models in existing AI workflows',
|
||||
'Batch-update AI tool connections'
|
||||
'Batch-update AI tool connections',
|
||||
'Transfer workflows between team projects (enterprise)'
|
||||
],
|
||||
performance: 'Very fast - typically 50-200ms. Much faster than full updates as only changes are processed.',
|
||||
bestPractices: [
|
||||
|
||||
@@ -143,7 +143,7 @@ export const n8nManagementTools: ToolDefinition[] = [
|
||||
},
|
||||
{
|
||||
name: 'n8n_update_partial_workflow',
|
||||
description: `Update workflow incrementally with diff operations. Types: addNode, removeNode, updateNode, moveNode, enable/disableNode, addConnection, removeConnection, updateSettings, updateName, add/removeTag. See tools_documentation("n8n_update_partial_workflow", "full") for details.`,
|
||||
description: `Update workflow incrementally with diff operations. Types: addNode, removeNode, updateNode, moveNode, enable/disableNode, addConnection, removeConnection, updateSettings, updateName, add/removeTag, activate/deactivateWorkflow, transferWorkflow. See tools_documentation("n8n_update_partial_workflow", "full") for details.`,
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
additionalProperties: true, // Allow any extra properties Claude Desktop might add
|
||||
|
||||
@@ -252,6 +252,14 @@ export class N8nApiClient {
|
||||
}
|
||||
}
|
||||
|
||||
async transferWorkflow(id: string, destinationProjectId: string): Promise<void> {
|
||||
try {
|
||||
await this.client.put(`/workflows/${id}/transfer`, { destinationProjectId });
|
||||
} catch (error) {
|
||||
throw handleN8nApiError(error);
|
||||
}
|
||||
}
|
||||
|
||||
async activateWorkflow(id: string): Promise<Workflow> {
|
||||
try {
|
||||
const response = await this.client.post(`/workflows/${id}/activate`, {});
|
||||
|
||||
@@ -28,7 +28,8 @@ import {
|
||||
ActivateWorkflowOperation,
|
||||
DeactivateWorkflowOperation,
|
||||
CleanStaleConnectionsOperation,
|
||||
ReplaceConnectionsOperation
|
||||
ReplaceConnectionsOperation,
|
||||
TransferWorkflowOperation
|
||||
} from '../types/workflow-diff';
|
||||
import { Workflow, WorkflowNode, WorkflowConnection } from '../types/n8n-api';
|
||||
import { Logger } from '../utils/logger';
|
||||
@@ -54,6 +55,8 @@ export class WorkflowDiffEngine {
|
||||
// Track tag operations for dedicated API calls
|
||||
private tagsToAdd: string[] = [];
|
||||
private tagsToRemove: string[] = [];
|
||||
// Track transfer operation for dedicated API call
|
||||
private transferToProjectId: string | undefined;
|
||||
|
||||
/**
|
||||
* Apply diff operations to a workflow
|
||||
@@ -70,6 +73,7 @@ export class WorkflowDiffEngine {
|
||||
this.removedNodeNames.clear();
|
||||
this.tagsToAdd = [];
|
||||
this.tagsToRemove = [];
|
||||
this.transferToProjectId = undefined;
|
||||
|
||||
// Clone workflow to avoid modifying original
|
||||
const workflowCopy = JSON.parse(JSON.stringify(workflow));
|
||||
@@ -141,6 +145,12 @@ export class WorkflowDiffEngine {
|
||||
};
|
||||
}
|
||||
|
||||
// Extract and clean up activation flags (same as atomic mode)
|
||||
const shouldActivate = (workflowCopy as any)._shouldActivate === true;
|
||||
const shouldDeactivate = (workflowCopy as any)._shouldDeactivate === true;
|
||||
delete (workflowCopy as any)._shouldActivate;
|
||||
delete (workflowCopy as any)._shouldDeactivate;
|
||||
|
||||
const success = appliedIndices.length > 0;
|
||||
return {
|
||||
success,
|
||||
@@ -151,8 +161,11 @@ export class WorkflowDiffEngine {
|
||||
warnings: this.warnings.length > 0 ? this.warnings : undefined,
|
||||
applied: appliedIndices,
|
||||
failed: failedIndices,
|
||||
shouldActivate: shouldActivate || undefined,
|
||||
shouldDeactivate: shouldDeactivate || undefined,
|
||||
tagsToAdd: this.tagsToAdd.length > 0 ? this.tagsToAdd : undefined,
|
||||
tagsToRemove: this.tagsToRemove.length > 0 ? this.tagsToRemove : undefined
|
||||
tagsToRemove: this.tagsToRemove.length > 0 ? this.tagsToRemove : undefined,
|
||||
transferToProjectId: this.transferToProjectId || undefined
|
||||
};
|
||||
} else {
|
||||
// Atomic mode: all operations must succeed
|
||||
@@ -256,7 +269,8 @@ export class WorkflowDiffEngine {
|
||||
shouldActivate: shouldActivate || undefined,
|
||||
shouldDeactivate: shouldDeactivate || undefined,
|
||||
tagsToAdd: this.tagsToAdd.length > 0 ? this.tagsToAdd : undefined,
|
||||
tagsToRemove: this.tagsToRemove.length > 0 ? this.tagsToRemove : undefined
|
||||
tagsToRemove: this.tagsToRemove.length > 0 ? this.tagsToRemove : undefined,
|
||||
transferToProjectId: this.transferToProjectId || undefined
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -298,6 +312,8 @@ export class WorkflowDiffEngine {
|
||||
case 'addTag':
|
||||
case 'removeTag':
|
||||
return null; // These are always valid
|
||||
case 'transferWorkflow':
|
||||
return this.validateTransferWorkflow(workflow, operation as TransferWorkflowOperation);
|
||||
case 'activateWorkflow':
|
||||
return this.validateActivateWorkflow(workflow, operation);
|
||||
case 'deactivateWorkflow':
|
||||
@@ -367,6 +383,9 @@ export class WorkflowDiffEngine {
|
||||
case 'replaceConnections':
|
||||
this.applyReplaceConnections(workflow, operation);
|
||||
break;
|
||||
case 'transferWorkflow':
|
||||
this.applyTransferWorkflow(workflow, operation as TransferWorkflowOperation);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -975,6 +994,18 @@ export class WorkflowDiffEngine {
|
||||
(workflow as any)._shouldDeactivate = true;
|
||||
}
|
||||
|
||||
// Transfer operation — uses dedicated API call (PUT /workflows/{id}/transfer)
|
||||
private validateTransferWorkflow(_workflow: Workflow, operation: TransferWorkflowOperation): string | null {
|
||||
if (!operation.destinationProjectId) {
|
||||
return 'transferWorkflow requires a non-empty destinationProjectId string';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private applyTransferWorkflow(_workflow: Workflow, operation: TransferWorkflowOperation): void {
|
||||
this.transferToProjectId = operation.destinationProjectId;
|
||||
}
|
||||
|
||||
// Connection cleanup operation validators
|
||||
private validateCleanStaleConnections(workflow: Workflow, operation: CleanStaleConnectionsOperation): string | null {
|
||||
// This operation is always valid - it just cleans up what it finds
|
||||
@@ -1128,9 +1159,10 @@ export class WorkflowDiffEngine {
|
||||
const connection = connectionsAtIndex[connIndex];
|
||||
// Check if target node was renamed
|
||||
if (renames.has(connection.node)) {
|
||||
const oldTargetName = connection.node;
|
||||
const newTargetName = renames.get(connection.node)!;
|
||||
connection.node = newTargetName;
|
||||
logger.debug(`Updated connection: ${sourceName}[${outputType}][${outputIndex}][${connIndex}].node: "${connection.node}" → "${newTargetName}"`);
|
||||
logger.debug(`Updated connection: ${sourceName}[${outputType}][${outputIndex}][${connIndex}].node: "${oldTargetName}" → "${newTargetName}"`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,6 +124,11 @@ export interface DeactivateWorkflowOperation extends DiffOperation {
|
||||
// No additional properties needed - just deactivates the workflow
|
||||
}
|
||||
|
||||
export interface TransferWorkflowOperation extends DiffOperation {
|
||||
type: 'transferWorkflow';
|
||||
destinationProjectId: string;
|
||||
}
|
||||
|
||||
// Connection Cleanup Operations
|
||||
export interface CleanStaleConnectionsOperation extends DiffOperation {
|
||||
type: 'cleanStaleConnections';
|
||||
@@ -161,7 +166,8 @@ export type WorkflowDiffOperation =
|
||||
| ActivateWorkflowOperation
|
||||
| DeactivateWorkflowOperation
|
||||
| CleanStaleConnectionsOperation
|
||||
| ReplaceConnectionsOperation;
|
||||
| ReplaceConnectionsOperation
|
||||
| TransferWorkflowOperation;
|
||||
|
||||
// Main diff request structure
|
||||
export interface WorkflowDiffRequest {
|
||||
@@ -192,6 +198,7 @@ export interface WorkflowDiffResult {
|
||||
shouldDeactivate?: boolean; // Flag to deactivate workflow after update (for deactivateWorkflow operation)
|
||||
tagsToAdd?: string[];
|
||||
tagsToRemove?: string[];
|
||||
transferToProjectId?: string; // For transferWorkflow operation - uses dedicated API call
|
||||
}
|
||||
|
||||
// Helper type for node reference (supports both ID and name)
|
||||
|
||||
Reference in New Issue
Block a user