feat: add n8n_deploy_template tool for one-click template deployment (v2.27.0) (#453)

* feat: add n8n_deploy_template tool for one-click template deployment (v2.27.0)

Add new MCP tool that deploys n8n.io workflow templates directly to user's
n8n instance in a single operation.

Features:
- Fetch template from local database
- Extract and report required credentials
- Optionally strip credentials (default: true)
- Optionally auto-upgrade node typeVersions (default: true)
- Optionally validate before deployment (default: true)
- Return workflow ID, URL, and setup guidance

Parameters:
- templateId (required): Template ID from n8n.io
- name (optional): Custom workflow name
- autoUpgradeVersions (default: true)
- validate (default: true)
- stripCredentials (default: true)

Conceived by Romuald Członkowski - https://www.aiadvisors.pl/en

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: address code review findings for n8n_deploy_template

- Fix health check tool count (12 → 13) to include new tool
- Add templateId validation (must be positive integer)
- Use deep copy of workflow to prevent template mutation
- Expand unit tests with negative/zero/decimal validation cases

Conceived by Romuald Członkowski - https://www.aiadvisors.pl/en

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* docs: update README with n8n_deploy_template tool

- Update management tools count from 12 to 13
- Add n8n_deploy_template to the tools list

Conceived by Romuald Członkowski - https://www.aiadvisors.pl/en

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: prevent workflow validator from mutating node types

The validator was incorrectly mutating node types from full form
(n8n-nodes-base.*) to short form (nodes-base.*) during validation.
This caused deployed workflows to show "?" icons in n8n UI because
the API requires full form node types.

Also updated SplitInBatches detection to check both node type forms
since workflows may contain either format.

Conceived by Romuald Członkowski - www.aiadvisors.pl/en

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* test: update tool counts in handlers-n8n-manager test

Update expected managementTools count from 12 to 13 and
totalAvailable from 19 to 20 to account for the new
n8n_deploy_template tool.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: pin MCP SDK and Zod versions to prevent Zod v4 resolution

Fixes #440, #444, #446, #447, #450

Root cause: package.json declared `"@modelcontextprotocol/sdk": "^1.20.1"`
which allowed npm to resolve to SDK 1.23.0. That version accepts
`"zod": "^3.25 || ^4.0"`, causing npm to deduplicate to Zod v4.
SDK 1.23.0's `isZ4Schema()` function crashes when called with undefined,
which happens for plain JSON Schema objects.

Changes:
- Pin SDK to exact version 1.20.1 (removes ^ prefix)
- Pin Zod to exact version 3.24.1 (removes ^ prefix)
- Add CI workflow to verify fresh installs get compatible versions

The new CI workflow:
- Packs and installs package fresh (without lockfile)
- Verifies SDK is exactly 1.20.1
- Verifies Zod is NOT v4 (blocks 4.x.x)
- Runs weekly to catch upstream dependency changes

Conceived by Romuald Członkowski - https://www.aiadvisors.pl/en

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* chore: improve dependency-check workflow based on code review

- Add workflow_dispatch for manual triggering/debugging
- Add explicit "not found" handling for version detection failures
- Use regex pattern for Zod v4 check to catch pre-release versions
- Add Zod error pattern detection in functionality test
- Capture stderr output for comprehensive error checking

Conceived by Romuald Członkowski - https://www.aiadvisors.pl/en

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Romuald Członkowski
2025-11-29 00:48:26 +01:00
committed by GitHub
parent c7e7bda505
commit e7dd04b471
14 changed files with 891 additions and 26 deletions

View File

@@ -34,6 +34,7 @@ import { ExpressionFormatValidator, ExpressionFormatIssue } from '../services/ex
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,
@@ -1788,7 +1789,7 @@ export async function handleDiagnostic(request: any, context?: InstanceContext):
// Check which tools are available
const documentationTools = 7; // Base documentation tools (after v2.26.0 consolidation)
const managementTools = apiConfigured ? 12 : 0; // Management tools requiring API (after v2.26.0 consolidation)
const managementTools = apiConfigured ? 13 : 0; // Management tools requiring API (includes n8n_deploy_template)
const totalTools = documentationTools + managementTools;
// Check npm version
@@ -2189,3 +2190,220 @@ export async function handleWorkflowVersions(
};
}
}
// ========================================================================
// Template Deployment Handler
// ========================================================================
const deployTemplateSchema = z.object({
templateId: z.number().positive().int(),
name: z.string().optional(),
autoUpgradeVersions: z.boolean().default(true),
validate: z.boolean().default(true),
stripCredentials: z.boolean().default(true)
});
interface RequiredCredential {
nodeType: string;
nodeName: string;
credentialType: string;
}
/**
* Deploy a workflow template from n8n.io directly to the user's n8n instance.
*
* This handler:
* 1. Fetches the template from the local template database
* 2. Extracts credential requirements for user guidance
* 3. Optionally strips credentials (for user to configure in n8n UI)
* 4. Optionally upgrades node typeVersions to latest supported
* 5. Optionally validates the workflow structure
* 6. Creates the workflow in the n8n instance
*/
export async function handleDeployTemplate(
args: unknown,
templateService: TemplateService,
repository: NodeRepository,
context?: InstanceContext
): Promise<McpToolResponse> {
try {
const client = ensureApiConfigured(context);
const input = deployTemplateSchema.parse(args);
// Fetch template
const template = await templateService.getTemplate(input.templateId, 'full');
if (!template) {
return {
success: false,
error: `Template ${input.templateId} not found`,
details: {
hint: 'Use search_templates to find available templates',
templateUrl: `https://n8n.io/workflows/${input.templateId}`
}
};
}
// Extract workflow from template (deep copy to avoid mutation)
const workflow = JSON.parse(JSON.stringify(template.workflow));
if (!workflow || !workflow.nodes) {
return {
success: false,
error: 'Template has invalid workflow structure',
details: { templateId: input.templateId }
};
}
// Set workflow name
const workflowName = input.name || template.name;
// Collect required credentials before stripping
const requiredCredentials: RequiredCredential[] = [];
for (const node of workflow.nodes) {
if (node.credentials && typeof node.credentials === 'object') {
for (const [credType] of Object.entries(node.credentials)) {
requiredCredentials.push({
nodeType: node.type,
nodeName: node.name,
credentialType: credType
});
}
}
}
// Strip credentials if requested
if (input.stripCredentials) {
workflow.nodes = workflow.nodes.map((node: any) => {
const { credentials, ...rest } = node;
return rest;
});
}
// Auto-upgrade typeVersions if requested
if (input.autoUpgradeVersions) {
const autoFixer = new WorkflowAutoFixer(repository);
// Run validation to get issues to fix
const validator = new WorkflowValidator(repository, EnhancedConfigValidator);
const validationResult = await validator.validateWorkflow(workflow, {
validateNodes: true,
validateConnections: false,
validateExpressions: false,
profile: 'runtime'
});
// Generate fixes focused on typeVersion upgrades
const fixResult = await autoFixer.generateFixes(
workflow,
validationResult,
[],
{ fixTypes: ['typeversion-upgrade', 'typeversion-correction'] }
);
// Apply fixes to workflow
if (fixResult.operations.length > 0) {
for (const op of fixResult.operations) {
if (op.type === 'updateNode' && op.updates) {
const node = workflow.nodes.find((n: any) =>
n.id === op.nodeId || n.name === op.nodeName
);
if (node) {
for (const [path, value] of Object.entries(op.updates)) {
if (path === 'typeVersion') {
node.typeVersion = value;
}
}
}
}
}
}
}
// Validate workflow if requested
if (input.validate) {
const validator = new WorkflowValidator(repository, EnhancedConfigValidator);
const validationResult = await validator.validateWorkflow(workflow, {
validateNodes: true,
validateConnections: true,
validateExpressions: true,
profile: 'runtime'
});
if (validationResult.errors.length > 0) {
return {
success: false,
error: 'Workflow validation failed',
details: {
errors: validationResult.errors.map(e => ({
node: e.nodeName,
message: e.message
})),
warnings: validationResult.warnings.length,
hint: 'Use validate=false to skip validation, or fix the template issues'
}
};
}
}
// Identify trigger type
const triggerNode = workflow.nodes.find((n: any) =>
n.type?.includes('Trigger') ||
n.type?.includes('webhook') ||
n.type === 'n8n-nodes-base.webhook'
);
const triggerType = triggerNode?.type?.split('.').pop() || 'manual';
// Create workflow via API (always creates inactive)
const createdWorkflow = await client.createWorkflow({
name: workflowName,
nodes: workflow.nodes,
connections: workflow.connections,
settings: workflow.settings || { executionOrder: 'v1' }
});
// Get base URL for workflow link
const apiConfig = context ? getN8nApiConfigFromContext(context) : getN8nApiConfig();
const baseUrl = apiConfig?.baseUrl?.replace('/api/v1', '') || '';
return {
success: true,
data: {
workflowId: createdWorkflow.id,
name: createdWorkflow.name,
active: false,
nodeCount: workflow.nodes.length,
triggerType,
requiredCredentials: requiredCredentials.length > 0 ? requiredCredentials : undefined,
url: baseUrl ? `${baseUrl}/workflow/${createdWorkflow.id}` : undefined,
templateId: input.templateId,
templateUrl: template.url || `https://n8n.io/workflows/${input.templateId}`
},
message: `Workflow "${createdWorkflow.name}" deployed successfully from template ${input.templateId}. ${
requiredCredentials.length > 0
? `Configure ${requiredCredentials.length} credential(s) in n8n to activate.`
: ''
}`
};
} 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,
details: error.details as Record<string, unknown> | undefined
};
}
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error occurred'
};
}
}

View File

@@ -856,6 +856,12 @@ export class N8NDocumentationMCPServer {
? { valid: true, errors: [] }
: { valid: false, errors: [{ field: 'action', message: 'action is required' }] };
break;
case 'n8n_deploy_template':
// Requires templateId parameter
validationResult = args.templateId !== undefined
? { valid: true, errors: [] }
: { valid: false, errors: [{ field: 'templateId', message: 'templateId is required' }] };
break;
default:
// For tools not yet migrated to schema validation, use basic validation
return this.validateToolParamsBasic(toolName, args, legacyRequiredParams || []);
@@ -1203,6 +1209,13 @@ export class N8NDocumentationMCPServer {
this.validateToolParams(name, args, ['mode']);
return n8nHandlers.handleWorkflowVersions(args, this.repository!, this.instanceContext);
case 'n8n_deploy_template':
this.validateToolParams(name, args, ['templateId']);
await this.ensureInitialized();
if (!this.templateService) throw new Error('Template service not initialized');
if (!this.repository) throw new Error('Repository not initialized');
return n8nHandlers.handleDeployTemplate(args, this.templateService, this.repository, this.instanceContext);
default:
throw new Error(`Unknown tool: ${name}`);
}

View File

@@ -21,7 +21,8 @@ import {
n8nAutofixWorkflowDoc,
n8nTriggerWebhookWorkflowDoc,
n8nExecutionsDoc,
n8nWorkflowVersionsDoc
n8nWorkflowVersionsDoc,
n8nDeployTemplateDoc
} from './workflow_management';
// Combine all tool documentations into a single object
@@ -58,7 +59,8 @@ export const toolsDocumentation: Record<string, ToolDocumentation> = {
n8n_autofix_workflow: n8nAutofixWorkflowDoc,
n8n_trigger_webhook_workflow: n8nTriggerWebhookWorkflowDoc,
n8n_executions: n8nExecutionsDoc,
n8n_workflow_versions: n8nWorkflowVersionsDoc
n8n_workflow_versions: n8nWorkflowVersionsDoc,
n8n_deploy_template: n8nDeployTemplateDoc
};
// Re-export types

View File

@@ -9,3 +9,4 @@ export { n8nAutofixWorkflowDoc } from './n8n-autofix-workflow';
export { n8nTriggerWebhookWorkflowDoc } from './n8n-trigger-webhook-workflow';
export { n8nExecutionsDoc } from './n8n-executions';
export { n8nWorkflowVersionsDoc } from './n8n-workflow-versions';
export { n8nDeployTemplateDoc } from './n8n-deploy-template';

View File

@@ -0,0 +1,69 @@
import { ToolDocumentation } from '../types';
export const n8nDeployTemplateDoc: ToolDocumentation = {
name: 'n8n_deploy_template',
category: 'workflow_management',
essentials: {
description: 'Deploy a workflow template from n8n.io directly to your n8n instance. Fetches template, optionally upgrades node versions and validates, then creates workflow.',
keyParameters: ['templateId', 'name', 'autoUpgradeVersions', 'validate', 'stripCredentials'],
example: 'n8n_deploy_template({templateId: 2776, name: "My Deployed Template"})',
performance: 'Network-dependent',
tips: [
'Workflow created inactive - configure credentials in n8n UI first',
'Returns list of required credentials',
'Use search_templates to find template IDs',
'Templates are upgraded to latest node versions by default'
]
},
full: {
description: 'Deploys a workflow template from n8n.io directly to your n8n instance. This tool combines fetching a template and creating a workflow in a single operation. Templates are stored locally and fetched from the database. The workflow is always created in an inactive state, allowing you to configure credentials before activation.',
parameters: {
templateId: { type: 'number', required: true, description: 'Template ID from n8n.io (find via search_templates)' },
name: { type: 'string', description: 'Custom workflow name (default: template name)' },
autoUpgradeVersions: { type: 'boolean', description: 'Upgrade node typeVersions to latest supported (default: true)' },
validate: { type: 'boolean', description: 'Validate workflow before deployment (default: true)' },
stripCredentials: { type: 'boolean', description: 'Remove credential references - user configures in n8n UI (default: true)' }
},
returns: 'Object with workflowId, name, nodeCount, triggerType, requiredCredentials array, url, templateId, templateUrl',
examples: [
`// Deploy template with default settings
n8n_deploy_template({templateId: 2776})`,
`// Deploy with custom name
n8n_deploy_template({
templateId: 2776,
name: "My Google Drive to Airtable Sync"
})`,
`// Deploy without validation (faster, use for trusted templates)
n8n_deploy_template({
templateId: 2776,
validate: false
})`,
`// Keep original node versions (useful for compatibility)
n8n_deploy_template({
templateId: 2776,
autoUpgradeVersions: false
})`
],
useCases: [
'Quickly deploy pre-built workflow templates',
'Set up common automation patterns',
'Bootstrap new projects with proven workflows',
'Deploy templates found via search_templates'
],
performance: 'Network-dependent - Typically 200-500ms (template fetch + workflow creation)',
bestPractices: [
'Use search_templates to find templates by use case',
'Review required credentials in the response',
'Configure credentials in n8n UI before activating',
'Test workflow before connecting to production systems'
],
pitfalls: [
'**REQUIRES N8N_API_URL and N8N_API_KEY environment variables** - tool unavailable without n8n API access',
'Workflows created in INACTIVE state - must configure credentials and activate in n8n',
'Templates may reference services you do not have (Slack, Google, etc.)',
'Template database must be populated - run npm run fetch:templates if templates not found',
'Validation may fail for templates with outdated node configurations'
],
relatedTools: ['search_templates', 'get_template', 'n8n_create_workflow', 'n8n_validate_workflow']
}
};

View File

@@ -126,7 +126,7 @@ When working with Code nodes, always start by calling the relevant guide:
- searchMode='by_task': Curated task-based templates
- searchMode='by_metadata': Filter by complexity/services
**n8n API Tools** (12 tools, requires N8N_API_URL configuration)
**n8n API Tools** (13 tools, requires N8N_API_URL configuration)
- n8n_create_workflow - Create new workflows
- n8n_get_workflow - Get workflow with mode='full'/'details'/'structure'/'minimal'
- n8n_update_full_workflow - Full workflow replacement
@@ -139,6 +139,7 @@ When working with Code nodes, always start by calling the relevant guide:
- n8n_executions - Unified execution management (action='get'/'list'/'delete')
- n8n_health_check - Check n8n API connectivity
- n8n_workflow_versions - Version history and rollback
- n8n_deploy_template - Deploy templates directly to n8n instance
## Performance Characteristics
- Instant (<10ms): search_nodes, get_node (minimal/standard)

View File

@@ -445,5 +445,40 @@ export const n8nManagementTools: ToolDefinition[] = [
},
required: ['mode']
}
},
// Template Deployment Tool
{
name: 'n8n_deploy_template',
description: `Deploy a workflow template from n8n.io directly to your n8n instance. Fetches template, optionally upgrades node versions and validates, then creates workflow. Returns workflow ID and required credentials list.`,
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)'
},
validate: {
type: 'boolean',
default: true,
description: 'Validate workflow before deployment (default: true)'
},
stripCredentials: {
type: 'boolean',
default: true,
description: 'Remove credential references from nodes - user configures in n8n UI (default: true)'
}
},
required: ['templateId']
}
}
];