n8n_autofix_workflow
Automatically fix workflow validation errors in n8n, including expression format, typeVersion, and webhook path issues. Preview or apply fixes to resolve common automation problems.
Instructions
Automatically fix common workflow validation errors. Preview fixes or apply them. Fixes expression format, typeVersion, error output config, webhook paths.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| id | Yes | Workflow ID to fix | |
| applyFixes | No | Apply fixes to workflow (default: false - preview mode) | |
| fixTypes | No | Types of fixes to apply (default: all) | |
| confidenceThreshold | No | Minimum confidence level for fixes (default: medium) | |
| maxFixes | No | Maximum number of fixes to apply (default: 50) |
Implementation Reference
- The primary handler function that executes the n8n_autofix_workflow tool. It fetches the workflow by ID, performs validation, identifies issues (including expression formats), generates fixes using WorkflowAutoFixer, and optionally applies them via partial workflow updates using handleUpdatePartialWorkflow. Supports preview mode and configurable fix types/confidence thresholds.export async function handleAutofixWorkflow( args: unknown, repository: NodeRepository, context?: InstanceContext ): Promise<McpToolResponse> { try { const client = ensureApiConfigured(context); const input = autofixWorkflowSchema.parse(args); // First, fetch the workflow from n8n const workflowResponse = await handleGetWorkflow({ id: input.id }, context); if (!workflowResponse.success) { return workflowResponse; // Return the error from fetching } const workflow = workflowResponse.data as Workflow; // Create validator instance using the provided repository const validator = new WorkflowValidator(repository, EnhancedConfigValidator); // Run validation to identify issues const validationResult = await validator.validateWorkflow(workflow, { validateNodes: true, validateConnections: true, validateExpressions: true, profile: 'ai-friendly' }); // Check for expression format issues const allFormatIssues: ExpressionFormatIssue[] = []; for (const node of workflow.nodes) { const formatContext = { nodeType: node.type, nodeName: node.name, nodeId: node.id }; const nodeFormatIssues = ExpressionFormatValidator.validateNodeParameters( node.parameters, formatContext ); // Add node information to each format issue const enrichedIssues = nodeFormatIssues.map(issue => ({ ...issue, nodeName: node.name, nodeId: node.id })); allFormatIssues.push(...enrichedIssues); } // Generate fixes using WorkflowAutoFixer const autoFixer = new WorkflowAutoFixer(repository); const fixResult = await autoFixer.generateFixes( workflow, validationResult, allFormatIssues, { applyFixes: input.applyFixes, fixTypes: input.fixTypes, confidenceThreshold: input.confidenceThreshold, maxFixes: input.maxFixes } ); // If no fixes available if (fixResult.fixes.length === 0) { return { success: true, data: { workflowId: workflow.id, workflowName: workflow.name, message: 'No automatic fixes available for this workflow', validationSummary: { errors: validationResult.errors.length, warnings: validationResult.warnings.length } } }; } // If preview mode (applyFixes = false) if (!input.applyFixes) { return { success: true, data: { workflowId: workflow.id, workflowName: workflow.name, preview: true, fixesAvailable: fixResult.fixes.length, fixes: fixResult.fixes, summary: fixResult.summary, stats: fixResult.stats, message: `${fixResult.fixes.length} fixes available. Set applyFixes=true to apply them.` } }; } // Apply fixes using the diff engine if (fixResult.operations.length > 0) { const updateResult = await handleUpdatePartialWorkflow( { id: workflow.id, operations: fixResult.operations, createBackup: true // Ensure backup is created with autofix metadata }, repository, context ); if (!updateResult.success) { return { success: false, error: 'Failed to apply fixes', details: { fixes: fixResult.fixes, updateError: updateResult.error } }; } return { success: true, data: { workflowId: workflow.id, workflowName: workflow.name, fixesApplied: fixResult.fixes.length, fixes: fixResult.fixes, summary: fixResult.summary, stats: fixResult.stats, message: `Successfully applied ${fixResult.fixes.length} fixes to workflow "${workflow.name}"` } }; } return { success: true, data: { workflowId: workflow.id, workflowName: workflow.name, message: 'No fixes needed' } }; } catch (error) { if (error instanceof z.ZodError) { return { success: false, error: 'Invalid input', details: { errors: error.errors } }; } if (error instanceof N8nApiError) { return { success: false, error: getUserFriendlyErrorMessage(error), code: error.code }; } return { success: false, error: error instanceof Error ? error.message : 'Unknown error occurred' }; } }
- src/mcp/tools-n8n-manager.ts:241-275 (schema)The ToolDefinition object defining the name, description, and inputSchema for the n8n_autofix_workflow tool. This schema is part of the n8nManagementTools export used for tool registration.{ name: 'n8n_autofix_workflow', description: `Automatically fix common workflow validation errors. Preview fixes or apply them. Fixes expression format, typeVersion, error output config, webhook paths.`, inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'Workflow ID to fix' }, applyFixes: { type: 'boolean', description: 'Apply fixes to workflow (default: false - preview mode)' }, fixTypes: { type: 'array', description: 'Types of fixes to apply (default: all)', items: { type: 'string', enum: ['expression-format', 'typeversion-correction', 'error-output-config', 'node-type-correction', 'webhook-missing-path', 'typeversion-upgrade', 'version-migration'] } }, confidenceThreshold: { type: 'string', enum: ['high', 'medium', 'low'], description: 'Minimum confidence level for fixes (default: medium)' }, maxFixes: { type: 'number', description: 'Maximum number of fixes to apply (default: 50)' } }, required: ['id'] } },
- src/mcp/tools-n8n-manager.ts:9-525 (registration)The n8nManagementTools array exports all management tool definitions including n8n_autofix_workflow. This array is imported and registered in the MCP server engine.export const n8nManagementTools: ToolDefinition[] = [ // Workflow Management Tools { name: 'n8n_create_workflow', description: `Create workflow. Requires: name, nodes[], connections{}. Created inactive. Returns workflow with ID.`, inputSchema: { type: 'object', properties: { name: { type: 'string', description: 'Workflow name (required)' }, nodes: { type: 'array', description: 'Array of workflow nodes. Each node must have: id, name, type, typeVersion, position, and parameters', items: { type: 'object', required: ['id', 'name', 'type', 'typeVersion', 'position', 'parameters'], properties: { id: { type: 'string' }, name: { type: 'string' }, type: { type: 'string' }, typeVersion: { type: 'number' }, position: { type: 'array', items: { type: 'number' }, minItems: 2, maxItems: 2 }, parameters: { type: 'object' }, credentials: { type: 'object' }, disabled: { type: 'boolean' }, notes: { type: 'string' }, continueOnFail: { type: 'boolean' }, retryOnFail: { type: 'boolean' }, maxTries: { type: 'number' }, waitBetweenTries: { type: 'number' } } } }, connections: { type: 'object', description: 'Workflow connections object. Keys are source node IDs, values define output connections' }, settings: { type: 'object', description: 'Optional workflow settings (execution order, timezone, error handling)', properties: { executionOrder: { type: 'string', enum: ['v0', 'v1'] }, timezone: { type: 'string' }, saveDataErrorExecution: { type: 'string', enum: ['all', 'none'] }, saveDataSuccessExecution: { type: 'string', enum: ['all', 'none'] }, saveManualExecutions: { type: 'boolean' }, saveExecutionProgress: { type: 'boolean' }, executionTimeout: { type: 'number' }, errorWorkflow: { type: 'string' } } } }, required: ['name', 'nodes', 'connections'] } }, { name: 'n8n_get_workflow', description: `Get workflow by ID with different detail levels. Use mode='full' for complete workflow, 'details' for metadata+stats, 'structure' for nodes/connections only, 'minimal' for id/name/active/tags.`, inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'Workflow ID' }, mode: { type: 'string', enum: ['full', 'details', 'structure', 'minimal'], default: 'full', description: 'Detail level: full=complete workflow, details=full+execution stats, structure=nodes/connections topology, minimal=metadata only' } }, required: ['id'] } }, { name: 'n8n_update_full_workflow', description: `Full workflow update. Requires complete nodes[] and connections{}. For incremental use n8n_update_partial_workflow.`, inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'Workflow ID to update' }, name: { type: 'string', description: 'New workflow name' }, nodes: { type: 'array', description: 'Complete array of workflow nodes (required if modifying workflow structure)', items: { type: 'object', additionalProperties: true } }, connections: { type: 'object', description: 'Complete connections object (required if modifying workflow structure)' }, settings: { type: 'object', description: 'Workflow settings to update' } }, required: ['id'] } }, { 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.`, inputSchema: { type: 'object', additionalProperties: true, // Allow any extra properties Claude Desktop might add properties: { id: { type: 'string', description: 'Workflow ID to update' }, operations: { type: 'array', description: 'Array of diff operations to apply. Each operation must have a "type" field and relevant properties for that operation type.', items: { type: 'object', additionalProperties: true } }, validateOnly: { type: 'boolean', description: 'If true, only validate operations without applying them' }, continueOnError: { type: 'boolean', description: 'If true, apply valid operations even if some fail (best-effort mode). Returns applied and failed operation indices. Default: false (atomic)' } }, required: ['id', 'operations'] } }, { name: 'n8n_delete_workflow', description: `Permanently delete a workflow. This action cannot be undone.`, inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'Workflow ID to delete' } }, required: ['id'] } }, { name: 'n8n_list_workflows', description: `List workflows (minimal metadata only). Returns id/name/active/dates/tags. Check hasMore/nextCursor for pagination.`, inputSchema: { type: 'object', properties: { limit: { type: 'number', description: 'Number of workflows to return (1-100, default: 100)' }, cursor: { type: 'string', description: 'Pagination cursor from previous response' }, active: { type: 'boolean', description: 'Filter by active status' }, tags: { type: 'array', items: { type: 'string' }, description: 'Filter by tags (exact match)' }, projectId: { type: 'string', description: 'Filter by project ID (enterprise feature)' }, excludePinnedData: { type: 'boolean', description: 'Exclude pinned data from response (default: true)' } } } }, { name: 'n8n_validate_workflow', description: `Validate workflow by ID. Checks nodes, connections, expressions. Returns errors/warnings/suggestions.`, inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'Workflow ID to validate' }, options: { type: 'object', description: 'Validation options', properties: { validateNodes: { type: 'boolean', description: 'Validate node configurations (default: true)' }, validateConnections: { type: 'boolean', description: 'Validate workflow connections (default: true)' }, validateExpressions: { type: 'boolean', description: 'Validate n8n expressions (default: true)' }, profile: { type: 'string', enum: ['minimal', 'runtime', 'ai-friendly', 'strict'], description: 'Validation profile to use (default: runtime)' } } } }, required: ['id'] } }, { name: 'n8n_autofix_workflow', description: `Automatically fix common workflow validation errors. Preview fixes or apply them. Fixes expression format, typeVersion, error output config, webhook paths.`, inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'Workflow ID to fix' }, applyFixes: { type: 'boolean', description: 'Apply fixes to workflow (default: false - preview mode)' }, fixTypes: { type: 'array', description: 'Types of fixes to apply (default: all)', items: { type: 'string', enum: ['expression-format', 'typeversion-correction', 'error-output-config', 'node-type-correction', 'webhook-missing-path', 'typeversion-upgrade', 'version-migration'] } }, confidenceThreshold: { type: 'string', enum: ['high', 'medium', 'low'], description: 'Minimum confidence level for fixes (default: medium)' }, maxFixes: { type: 'number', description: 'Maximum number of fixes to apply (default: 50)' } }, required: ['id'] } }, // Execution Management Tools { name: 'n8n_test_workflow', description: `Test/trigger workflow execution. Auto-detects trigger type (webhook/form/chat). Supports: webhook (HTTP), form (fields), chat (message). Note: Only workflows with these trigger types can be executed externally.`, inputSchema: { type: 'object', properties: { workflowId: { type: 'string', description: 'Workflow ID to execute (required)' }, triggerType: { type: 'string', enum: ['webhook', 'form', 'chat'], description: 'Trigger type. Auto-detected if not specified. Workflow must have a matching trigger node.' }, // Webhook options httpMethod: { type: 'string', enum: ['GET', 'POST', 'PUT', 'DELETE'], description: 'For webhook: HTTP method (default: from workflow config or POST)' }, webhookPath: { type: 'string', description: 'For webhook: override the webhook path' }, // Chat options message: { type: 'string', description: 'For chat: message to send (required for chat triggers)' }, sessionId: { type: 'string', description: 'For chat: session ID for conversation continuity' }, // Common options data: { type: 'object', description: 'Input data/payload for webhook, form fields, or execution data' }, headers: { type: 'object', description: 'Custom HTTP headers' }, timeout: { type: 'number', description: 'Timeout in ms (default: 120000)' }, waitForResponse: { type: 'boolean', description: 'Wait for workflow completion (default: true)' } }, required: ['workflowId'] } }, { name: 'n8n_executions', description: `Manage workflow executions: get details, list, or delete. Use action='get' with id for execution details, action='list' for listing executions, action='delete' to remove execution record.`, inputSchema: { type: 'object', properties: { action: { type: 'string', enum: ['get', 'list', 'delete'], description: 'Operation: get=get execution details, list=list executions, delete=delete execution' }, // For action='get' and action='delete' id: { type: 'string', description: 'Execution ID (required for action=get or action=delete)' }, // For action='get' - detail level mode: { type: 'string', enum: ['preview', 'summary', 'filtered', 'full', 'error'], description: 'For action=get: preview=structure only, summary=2 items (default), filtered=custom, full=all data, error=optimized error debugging' }, nodeNames: { type: 'array', items: { type: 'string' }, description: 'For action=get with mode=filtered: filter to specific nodes by name' }, itemsLimit: { type: 'number', description: 'For action=get with mode=filtered: items per node (0=structure, 2=default, -1=unlimited)' }, includeInputData: { type: 'boolean', description: 'For action=get: include input data in addition to output (default: false)' }, // Error mode specific parameters errorItemsLimit: { type: 'number', description: 'For action=get with mode=error: sample items from upstream node (default: 2, max: 100)' }, includeStackTrace: { type: 'boolean', description: 'For action=get with mode=error: include full stack trace (default: false, shows truncated)' }, includeExecutionPath: { type: 'boolean', description: 'For action=get with mode=error: include execution path leading to error (default: true)' }, fetchWorkflow: { type: 'boolean', description: 'For action=get with mode=error: fetch workflow for accurate upstream detection (default: true)' }, // For action='list' limit: { type: 'number', description: 'For action=list: number of executions to return (1-100, default: 100)' }, cursor: { type: 'string', description: 'For action=list: pagination cursor from previous response' }, workflowId: { type: 'string', description: 'For action=list: filter by workflow ID' }, projectId: { type: 'string', description: 'For action=list: filter by project ID (enterprise feature)' }, status: { type: 'string', enum: ['success', 'error', 'waiting'], description: 'For action=list: filter by execution status' }, includeData: { type: 'boolean', description: 'For action=list: include execution data (default: false)' } }, required: ['action'] } }, // System Tools { name: 'n8n_health_check', description: `Check n8n instance health and API connectivity. Use mode='diagnostic' for detailed troubleshooting with env vars and tool status.`, inputSchema: { type: 'object', properties: { mode: { type: 'string', enum: ['status', 'diagnostic'], description: 'Mode: "status" (default) for quick health check, "diagnostic" for detailed debug info including env vars and tool status', default: 'status' }, verbose: { type: 'boolean', description: 'Include extra details in diagnostic mode (default: false)' } } } }, { name: 'n8n_workflow_versions', description: `Manage workflow version history, rollback, and cleanup. Six modes: - list: Show version history for a workflow - get: Get details of specific version - rollback: Restore workflow to previous version (creates backup first) - delete: Delete specific version or all versions for a workflow - prune: Manually trigger pruning to keep N most recent versions - truncate: Delete ALL versions for ALL workflows (requires confirmation)`, inputSchema: { type: 'object', properties: { mode: { type: 'string', enum: ['list', 'get', 'rollback', 'delete', 'prune', 'truncate'], description: 'Operation mode' }, workflowId: { type: 'string', description: 'Workflow ID (required for list, rollback, delete, prune)' }, versionId: { type: 'number', description: 'Version ID (required for get mode and single version delete, optional for rollback)' }, limit: { type: 'number', default: 10, description: 'Max versions to return in list mode' }, validateBefore: { type: 'boolean', default: true, description: 'Validate workflow structure before rollback' }, deleteAll: { type: 'boolean', default: false, description: 'Delete all versions for workflow (delete mode only)' }, maxVersions: { type: 'number', default: 10, description: 'Keep N most recent versions (prune mode only)' }, confirmTruncate: { type: 'boolean', default: false, description: 'REQUIRED: Must be true to truncate all versions (truncate mode only)' } }, required: ['mode'] } }, // Template Deployment Tool { name: 'n8n_deploy_template', description: `Deploy a workflow template from n8n.io directly to your n8n instance. Deploys first, then auto-fixes common issues (expression format, typeVersions). Returns workflow ID, required credentials, and fixes applied.`, inputSchema: { type: 'object', properties: { templateId: { type: 'number', description: 'Template ID from n8n.io (required)' }, name: { type: 'string', description: 'Custom workflow name (default: template name)' }, autoUpgradeVersions: { type: 'boolean', default: true, description: 'Automatically upgrade node typeVersions to latest supported (default: true)' }, autoFix: { type: 'boolean', default: true, description: 'Auto-apply fixes after deployment for expression format issues, missing = prefix, etc. (default: true)' }, stripCredentials: { type: 'boolean', default: true, description: 'Remove credential references from nodes - user configures in n8n UI (default: true)' } }, required: ['templateId'] } } ];
- Imports and usage of WorkflowAutoFixer service, the core helper that generates fix operations for workflow issues. This is the key supporting utility for autofix functionality.import { WorkflowAutoFixer, AutoFixConfig } from '../services/workflow-auto-fixer'; import { ExpressionFormatValidator, ExpressionFormatIssue } from '../services/expression-format-validator'; import { WorkflowVersioningService } from '../services/workflow-versioning-service'; import { handleUpdatePartialWorkflow } from './handlers-workflow-diff'; import { telemetry } from '../telemetry'; import { TemplateService } from '../templates/template-service'; import { createCacheKey, createInstanceCache, CacheMutex, cacheMetrics, withRetry, getCacheStatistics } from '../utils/cache-utils'; import { processExecution } from '../services/execution-processor'; import { checkNpmVersion, formatVersionMessage } from '../utils/npm-version-checker'; // ======================================================================== // TypeScript Interfaces for Type Safety // ======================================================================== /** * Health Check Response Data Structure */ interface HealthCheckResponseData { status: string; instanceId?: string; n8nVersion?: string; features?: Record<string, unknown>; apiUrl?: string; mcpVersion: string; supportedN8nVersion?: string; versionCheck: { current: string; latest: string | null; upToDate: boolean; message: string; updateCommand?: string; }; performance: { responseTimeMs: number; cacheHitRate: string; cachedInstances: number; }; nextSteps?: string[]; updateWarning?: string; } /** * Cloud Platform Guide Structure */ interface CloudPlatformGuide { name: string; troubleshooting: string[]; } /** * Applied Fix from Auto-Fix Operation */ interface AppliedFix { node: string; field: string; type: string; before: string; after: string; confidence: string; } /** * Auto-Fix Result Data from handleAutofixWorkflow */ interface AutofixResultData { fixesApplied?: number; fixes?: AppliedFix[]; workflowId?: string; workflowName?: string; message?: string; summary?: string; stats?: Record<string, number>; } /** * Workflow Validation Response Data */ interface WorkflowValidationResponse { valid: boolean; workflowId?: string; workflowName?: string; summary: { totalNodes: number; enabledNodes: number; triggerNodes: number; validConnections: number;
- Tool documentation file providing detailed usage examples, extended schemas, and integration notes for n8n_autofix_workflow.import { ToolDocumentation } from '../types'; export const n8nAutofixWorkflowDoc: ToolDocumentation = { name: 'n8n_autofix_workflow', category: 'workflow_management', essentials: { description: 'Automatically fix common workflow validation errors - expression formats, typeVersions, error outputs, webhook paths, and smart version upgrades', keyParameters: ['id', 'applyFixes'], example: 'n8n_autofix_workflow({id: "wf_abc123", applyFixes: false})', performance: 'Network-dependent (200-1500ms) - fetches, validates, and optionally updates workflow with smart migrations', tips: [ 'Use applyFixes: false to preview changes before applying', 'Set confidenceThreshold to control fix aggressiveness (high/medium/low)', 'Supports expression formats, typeVersion issues, error outputs, node corrections, webhook paths, AND version upgrades', 'High-confidence fixes (≥90%) are safe for auto-application', 'Version upgrades include smart migration with breaking change detection', 'Post-update guidance provides AI-friendly step-by-step instructions for manual changes' ] }, full: { description: `Automatically detects and fixes common workflow validation errors in n8n workflows. This tool: - Fetches the workflow from your n8n instance - Runs comprehensive validation to detect issues - Generates targeted fixes for common problems - Optionally applies the fixes back to the workflow The auto-fixer can resolve: 1. **Expression Format Issues**: Missing '=' prefix in n8n expressions (e.g., {{ $json.field }} → ={{ $json.field }}) 2. **TypeVersion Corrections**: Downgrades nodes with unsupported typeVersions to maximum supported 3. **Error Output Configuration**: Removes conflicting onError settings when error connections are missing 4. **Node Type Corrections**: Intelligently fixes unknown node types using similarity matching: - Handles deprecated package prefixes (n8n-nodes-base. → nodes-base.) - Corrects capitalization mistakes (HttpRequest → httpRequest) - Suggests correct packages (nodes-base.openai → nodes-langchain.openAi) - Uses multi-factor scoring: name similarity, category match, package match, pattern match - Only auto-fixes suggestions with ≥90% confidence - Leverages NodeSimilarityService with 5-minute caching for performance 5. **Webhook Path Generation**: Automatically generates UUIDs for webhook nodes missing path configuration: - Generates a unique UUID for webhook path - Sets both 'path' parameter and 'webhookId' field to the same UUID - Ensures webhook nodes become functional with valid endpoints - High confidence fix as UUID generation is deterministic 6. **Smart Version Upgrades** (NEW): Proactively upgrades nodes to their latest versions: - Detects outdated node versions and recommends upgrades - Applies smart migrations with auto-migratable property changes - Handles breaking changes intelligently (Execute Workflow v1.0→v1.1, Webhook v2.0→v2.1, etc.) - Generates UUIDs for required fields (webhookId), sets sensible defaults - HIGH confidence for non-breaking upgrades, MEDIUM for breaking changes with auto-migration - Example: Execute Workflow v1.0→v1.1 adds inputFieldMapping automatically