import { N8nClient } from '../integrations/n8n-client.js';
/**
* MCP Tools for n8n Workflow Automation Platform
* Enables Claude to manage workflows, install community nodes, and upload blueprints to n8n
*/
let n8nClient = null;
// Initialize n8n client from environment variables
function getN8nClient() {
if (!n8nClient) {
const n8nURL = process.env.N8N_URL;
const apiKey = process.env.N8N_API_KEY;
const username = process.env.N8N_USERNAME;
const password = process.env.N8N_PASSWORD;
if (!n8nURL) {
throw new Error('N8N_URL environment variable is required');
}
if (!apiKey && (!username || !password)) {
throw new Error('Either N8N_API_KEY or N8N_USERNAME/N8N_PASSWORD must be provided');
}
n8nClient = new N8nClient(n8nURL, apiKey, username, password);
}
return n8nClient;
}
export const n8nTools = {
// Tool 1: Check n8n instance health and connectivity
n8n_health_check: {
name: "n8n_health_check",
description: "Check the health and connectivity of the n8n instance. Verifies that n8n is running and accessible.",
inputSchema: {
type: "object",
properties: {}
},
handler: async (args) => {
try {
const client = getN8nClient();
// First check basic health
const healthResult = await client.healthCheck();
// Then try to authenticate
const authResult = await client.authenticate();
// Get instance info if possible
let instanceInfo = null;
if (authResult) {
const infoResult = await client.getInstanceInfo();
instanceInfo = infoResult.success ? infoResult.data : null;
}
return {
success: healthResult.success && healthResult.healthy && authResult,
message: healthResult.healthy && authResult ?
'✅ n8n instance is healthy and accessible' :
'❌ n8n instance has connectivity or authentication issues',
health_status: healthResult,
authentication: authResult,
instance_info: instanceInfo
};
} catch (error) {
return {
success: false,
message: `❌ n8n health check failed: ${error.message}`
};
}
}
},
// Tool 2: List all workflows in n8n
n8n_list_workflows: {
name: "n8n_list_workflows",
description: "Get list of all workflows in the n8n instance. Shows active, inactive, and available workflows for management.",
inputSchema: {
type: "object",
properties: {}
},
handler: async (args) => {
try {
const client = getN8nClient();
await client.authenticate();
const result = await client.getWorkflows();
if (result.success) {
const workflows = result.data || [];
const activeCount = workflows.filter(w => w.active).length;
const inactiveCount = workflows.length - activeCount;
return {
success: true,
message: `Found ${workflows.length} workflows (${activeCount} active, ${inactiveCount} inactive)`,
total_workflows: workflows.length,
active_workflows: activeCount,
inactive_workflows: inactiveCount,
workflows: workflows.map(w => ({
id: w.id,
name: w.name,
active: w.active,
tags: w.tags,
updatedAt: w.updatedAt
}))
};
} else {
return {
success: false,
message: `Failed to list workflows: ${result.error}`
};
}
} catch (error) {
return {
success: false,
message: `❌ List workflows failed: ${error.message}`
};
}
}
},
// Tool 3: Import workflow blueprint from file
n8n_import_workflow: {
name: "n8n_import_workflow",
description: "Import a workflow blueprint from JSON file into n8n. Creates new workflow from exported or downloaded blueprints.",
inputSchema: {
type: "object",
properties: {
workflow_file_path: {
type: "string",
description: "Path to the workflow JSON file to import"
},
activate_immediately: {
type: "boolean",
description: "Whether to activate the workflow after import",
default: false
}
},
required: ["workflow_file_path"]
},
handler: async (args) => {
try {
const client = getN8nClient();
await client.authenticate();
const result = await client.importWorkflowFromFile(args.workflow_file_path);
if (result.success && args.activate_immediately && result.data && result.data.id) {
const activationResult = await client.setWorkflowStatus(result.data.id, true);
return {
success: result.success,
message: `Workflow imported successfully${activationResult.success ? ' and activated' : ' but activation failed'}`,
workflow_id: result.data.id,
workflow_name: result.data.name,
imported_file: result.fileName,
activated: activationResult.success
};
}
return {
success: result.success,
message: result.success ?
`Workflow "${result.data?.name}" imported successfully` :
`Import failed: ${result.error}`,
workflow_id: result.data?.id,
workflow_name: result.data?.name,
imported_file: result.fileName
};
} catch (error) {
return {
success: false,
message: `❌ Workflow import failed: ${error.message}`
};
}
}
},
// Tool 4: Export workflow to file
n8n_export_workflow: {
name: "n8n_export_workflow",
description: "Export a workflow from n8n to JSON file. Useful for backing up workflows or sharing blueprints.",
inputSchema: {
type: "object",
properties: {
workflow_id: {
type: "string",
description: "ID of the workflow to export"
},
output_file_path: {
type: "string",
description: "Optional: Custom path for the exported file"
}
},
required: ["workflow_id"]
},
handler: async (args) => {
try {
const client = getN8nClient();
await client.authenticate();
const result = await client.exportWorkflowToFile(
args.workflow_id,
args.output_file_path
);
return {
success: result.success,
message: result.message,
workflow_name: result.workflowName,
exported_file: result.fileName,
workflow_id: args.workflow_id
};
} catch (error) {
return {
success: false,
message: `❌ Workflow export failed: ${error.message}`
};
}
}
},
// Tool 5: Activate or deactivate workflow
n8n_set_workflow_status: {
name: "n8n_set_workflow_status",
description: "Activate or deactivate a workflow in n8n. Control which workflows are running and processing triggers.",
inputSchema: {
type: "object",
properties: {
workflow_id: {
type: "string",
description: "ID of the workflow to activate/deactivate"
},
active: {
type: "boolean",
description: "True to activate, false to deactivate"
}
},
required: ["workflow_id", "active"]
},
handler: async (args) => {
try {
const client = getN8nClient();
await client.authenticate();
const result = await client.setWorkflowStatus(args.workflow_id, args.active);
return {
success: result.success,
message: result.success ?
`Workflow ${args.active ? 'activated' : 'deactivated'} successfully` :
`Failed to ${args.active ? 'activate' : 'deactivate'} workflow: ${result.error}`,
workflow_id: args.workflow_id,
new_status: args.active ? 'active' : 'inactive'
};
} catch (error) {
return {
success: false,
message: `❌ Workflow status change failed: ${error.message}`
};
}
}
},
// Tool 6: Execute workflow manually
n8n_execute_workflow: {
name: "n8n_execute_workflow",
description: "Manually execute a workflow in n8n with optional input data. Useful for testing workflows and triggering specific automations.",
inputSchema: {
type: "object",
properties: {
workflow_id: {
type: "string",
description: "ID of the workflow to execute"
},
input_data: {
type: "object",
description: "Optional input data for the workflow execution",
default: {}
}
},
required: ["workflow_id"]
},
handler: async (args) => {
try {
const client = getN8nClient();
await client.authenticate();
const result = await client.executeWorkflow(
args.workflow_id,
args.input_data || {}
);
return {
success: result.success,
message: result.success ?
'Workflow executed successfully' :
`Workflow execution failed: ${result.error}`,
workflow_id: args.workflow_id,
execution_data: result.data
};
} catch (error) {
return {
success: false,
message: `❌ Workflow execution failed: ${error.message}`
};
}
}
},
// Tool 7: Install community node package
n8n_install_community_node: {
name: "n8n_install_community_node",
description: "Install a community node package from npm. Expands n8n capabilities with third-party integrations and custom nodes.",
inputSchema: {
type: "object",
properties: {
package_name: {
type: "string",
description: "npm package name of the community node (e.g., 'n8n-nodes-discord')"
},
version: {
type: "string",
description: "Specific version to install (default: latest)",
default: "latest"
}
},
required: ["package_name"]
},
handler: async (args) => {
try {
const client = getN8nClient();
await client.authenticate();
const result = await client.installCommunityNode(
args.package_name,
args.version || 'latest'
);
return {
success: result.success,
message: result.success ?
`Community node "${args.package_name}" installed successfully` :
`Installation failed: ${result.error}`,
package_name: args.package_name,
version: args.version || 'latest',
installation_data: result.data
};
} catch (error) {
return {
success: false,
message: `❌ Community node installation failed: ${error.message}`
};
}
}
},
// Tool 8: List installed community nodes
n8n_list_community_nodes: {
name: "n8n_list_community_nodes",
description: "Get list of all installed community node packages in n8n. Shows available third-party integrations and custom nodes.",
inputSchema: {
type: "object",
properties: {}
},
handler: async (args) => {
try {
const client = getN8nClient();
await client.authenticate();
const result = await client.getCommunityNodes();
if (result.success) {
const packages = result.data || [];
return {
success: true,
message: `Found ${packages.length} installed community node packages`,
total_packages: packages.length,
community_packages: packages.map(pkg => ({
name: pkg.packageName,
version: pkg.installedVersion,
nodes: pkg.installedNodes,
status: pkg.status
}))
};
} else {
return {
success: false,
message: `Failed to list community nodes: ${result.error}`
};
}
} catch (error) {
return {
success: false,
message: `❌ List community nodes failed: ${error.message}`
};
}
}
},
// Tool 9: Uninstall community node package
n8n_uninstall_community_node: {
name: "n8n_uninstall_community_node",
description: "Uninstall a community node package from n8n. Removes third-party integrations and custom nodes.",
inputSchema: {
type: "object",
properties: {
package_name: {
type: "string",
description: "npm package name of the community node to uninstall"
}
},
required: ["package_name"]
},
handler: async (args) => {
try {
const client = getN8nClient();
await client.authenticate();
const result = await client.uninstallCommunityNode(args.package_name);
return {
success: result.success,
message: result.success ?
`Community node "${args.package_name}" uninstalled successfully` :
`Uninstallation failed: ${result.error}`,
package_name: args.package_name
};
} catch (error) {
return {
success: false,
message: `❌ Community node uninstallation failed: ${error.message}`
};
}
}
},
// Tool 10: Bulk import workflows from directory
n8n_bulk_import_workflows: {
name: "n8n_bulk_import_workflows",
description: "Import multiple workflow blueprints from a directory. Efficiently processes multiple JSON workflow files at once.",
inputSchema: {
type: "object",
properties: {
directory_path: {
type: "string",
description: "Path to directory containing workflow JSON files"
},
activate_all: {
type: "boolean",
description: "Whether to activate all imported workflows",
default: false
}
},
required: ["directory_path"]
},
handler: async (args) => {
try {
const client = getN8nClient();
await client.authenticate();
const result = await client.importWorkflowsFromDirectory(args.directory_path);
if (result.success && args.activate_all) {
// Activate all successfully imported workflows
const activationResults = [];
for (const workflowResult of result.results) {
if (workflowResult.success && workflowResult.data?.id) {
const activationResult = await client.setWorkflowStatus(workflowResult.data.id, true);
activationResults.push({
workflow_id: workflowResult.data.id,
activated: activationResult.success
});
}
}
return {
...result,
activation_results: activationResults,
activated_count: activationResults.filter(r => r.activated).length
};
}
return {
success: result.success,
message: result.message,
summary: result.summary,
import_results: result.results
};
} catch (error) {
return {
success: false,
message: `❌ Bulk workflow import failed: ${error.message}`
};
}
}
},
// Tool 11: Get workflow execution history
n8n_get_executions: {
name: "n8n_get_executions",
description: "Get execution history for workflows. Monitor workflow runs, success rates, and troubleshoot failures.",
inputSchema: {
type: "object",
properties: {
workflow_id: {
type: "string",
description: "Optional: Specific workflow ID to get executions for"
},
limit: {
type: "number",
description: "Maximum number of executions to retrieve",
default: 20
}
}
},
handler: async (args) => {
try {
const client = getN8nClient();
await client.authenticate();
const result = await client.getExecutions(
args.workflow_id,
args.limit || 20
);
if (result.success) {
const executions = result.data || [];
const successCount = executions.filter(e => e.finished && !e.stoppedAt).length;
const failedCount = executions.filter(e => e.stoppedAt).length;
return {
success: true,
message: `Retrieved ${executions.length} execution records`,
total_executions: executions.length,
successful_executions: successCount,
failed_executions: failedCount,
workflow_id: args.workflow_id || 'all',
executions: executions.map(e => ({
id: e.id,
workflowId: e.workflowId,
mode: e.mode,
finished: e.finished,
retryOf: e.retryOf,
startedAt: e.startedAt,
stoppedAt: e.stoppedAt
}))
};
} else {
return {
success: false,
message: `Failed to get executions: ${result.error}`
};
}
} catch (error) {
return {
success: false,
message: `❌ Get executions failed: ${error.message}`
};
}
}
}
};
// Export tool definitions for MCP server
export const getN8nToolDefinitions = () => {
return Object.values(n8nTools).map(tool => ({
name: tool.name,
description: tool.description,
inputSchema: tool.inputSchema
}));
};
// Export tool handlers for MCP server execution
export const getN8nToolHandlers = () => {
const handlers = {};
Object.values(n8nTools).forEach(tool => {
handlers[tool.name] = { handler: tool.handler };
});
return handlers;
};