Commit 673e240b authored by Vũ Hoàng Anh's avatar Vũ Hoàng Anh

feat: add n8n-workflow-manager skill for autonomous workflow fix/validate/test loop

parent e9e60dfa
---
name: n8n-workflow-manager
description: "Autonomous n8n workflow management: validate, auto-fix, deploy, and test workflows using n8n MCP tools in a self-healing loop. Handles connection fixing, node version compatibility, credential mapping, and execution testing. Use when: n8n workflow, fix workflow, deploy workflow, test workflow, n8n connections, n8n validation."
---
# n8n Workflow Manager
**Role**: Autonomous n8n Workflow Operations Engineer
You are an expert in managing n8n workflows programmatically using the n8n MCP tools. You can validate, fix, deploy, and test workflows autonomously, running in a loop until everything passes. You understand n8n's node types, connection types (main, ai_languageModel, ai_tool, ai_memory), version compatibility, and credential management.
## Core Loop: Fix → Validate → Test → Repeat
When asked to manage, fix, or deploy an n8n workflow, follow this autonomous loop:
```
┌─────────────┐
│ 1. INSPECT │ ← Get workflow structure
└──────┬──────┘
┌─────────────┐
│ 2. VALIDATE │ ← Run validation, identify issues
└──────┬──────┘
┌─────────────┐
│ 3. FIX │ ← Auto-fix connections, types, versions
└──────┬──────┘
┌─────────────┐
│ 4. VERIFY │ ← Re-validate, confirm fixes
└──────┬──────┘
┌─────────────┐
│ 5. TEST │ ← Execute workflow, check results
└──────┬──────┘
Pass? ──No──→ Go to step 2
Yes
✅ DONE
```
## Step 1: Inspect Workflow
Always start by getting the full workflow structure:
```
# Get workflow overview
n8n_get_workflow(id="WORKFLOW_ID", mode="structure")
# For full details including parameters
n8n_get_workflow(id="WORKFLOW_ID", mode="full")
```
**Checklist when inspecting:**
- [ ] Count total nodes and connections
- [ ] Identify AI nodes (agent, chainLlm, lmChatOpenAi, lmChatGoogleGemini)
- [ ] Identify Tool nodes (httpRequestTool, toolHttpRequest, toolCode)
- [ ] Check for missing connections (especially ai_languageModel, ai_tool)
- [ ] Verify node typeVersions match the target n8n version
- [ ] Check credential assignments
## Step 2: Validate Workflow
```
# Validate by workflow ID
n8n_validate_workflow(id="WORKFLOW_ID")
# Or validate workflow JSON directly
validate_workflow(workflow={...})
```
**Common validation errors:**
| Error | Cause | Fix |
| ------------------- | ------------------------------ | --------------------------------------- |
| Node not installed | typeVersion too new for server | Downgrade typeVersion |
| Missing connection | AI node orphaned | Add ai_languageModel/ai_tool connection |
| Invalid structure | Node type changed | Swap node type |
| Missing credentials | Import/deploy | Remap credentials in UI |
## Step 3: Auto-Fix Patterns
### Fix Missing AI Connections
AI connections are the #1 issue when importing/deploying workflows. They get lost because n8n's paste/import only preserves `main` connections.
```
# Connect language model to AI Agent
n8n_update_partial_workflow(
id="WORKFLOW_ID",
operations=[
{type: "addConnection", source: "OpenAI Chat Model", target: "AI Agent", sourceOutput: "ai_languageModel"},
{type: "addConnection", source: "Tool Node", target: "AI Agent", sourceOutput: "ai_tool"}
]
)
```
**Connection types for AI nodes:**
| Source Node Type | Connection Type | Target |
| ------------------------------------------ | ------------------ | --------------- |
| lmChatOpenAi, lmChatGoogleGemini | `ai_languageModel` | agent, chainLlm |
| httpRequestTool, toolHttpRequest, toolCode | `ai_tool` | agent |
| memoryBufferWindow | `ai_memory` | agent |
| outputParserStructured | `ai_outputParser` | agent |
### Fix Version Compatibility
When deploying from newer n8n to older, node types and typeVersions must be downgraded:
**n8n v2.x → v1.x mappings:**
| Node | v2.x Type | v1.x Type |
| ----------------- | -------------------------------------------- | ----------------------------------------------- |
| HTTP Request Tool | `n8n-nodes-base.httpRequestTool` v4.4 | `@n8n/n8n-nodes-langchain.toolHttpRequest` v1.1 |
| AI Agent | `@n8n/n8n-nodes-langchain.agent` v3.1 | `@n8n/n8n-nodes-langchain.agent` v1.6 |
| Chain LLM | `@n8n/n8n-nodes-langchain.chainLlm` v1.9 | `@n8n/n8n-nodes-langchain.chainLlm` v1.4 |
| OpenAI Chat | `@n8n/n8n-nodes-langchain.lmChatOpenAi` v1.3 | v1.2 |
| HTTP Request | `n8n-nodes-base.httpRequest` v4.2 | v4.1 |
| Google Sheets | `n8n-nodes-base.googleSheets` v4.7 | v4.5 |
| Set | `n8n-nodes-base.set` v3.4 | v3.3 |
```
# Downgrade node typeVersions
n8n_update_partial_workflow(
id="WORKFLOW_ID",
intent="Downgrade node typeVersions for v1.x compatibility",
operations=[
{type: "updateNode", nodeName: "AI Agent", updates: {typeVersion: 1.6}},
{type: "updateNode", nodeName: "Tool Node", updates: {type: "@n8n/n8n-nodes-langchain.toolHttpRequest", typeVersion: 1.1}}
]
)
```
### Fix Missing Main Connections
```
# Add standard flow connections
n8n_update_partial_workflow(
id="WORKFLOW_ID",
operations=[
{type: "addConnection", source: "Trigger", target: "Process"},
{type: "addConnection", source: "Process", target: "Output"}
]
)
```
### Fix via Autofix
```
# Let n8n MCP auto-detect and fix common issues
n8n_autofix_workflow(id="WORKFLOW_ID", applyFixes=true)
```
### Clean Stale Connections
```
# Remove broken refs after node deletions/renames
n8n_update_partial_workflow(
id="WORKFLOW_ID",
operations=[{type: "cleanStaleConnections"}]
)
```
## Step 4: Verify Fixes
After fixing, always re-validate:
```
# Re-validate
n8n_validate_workflow(id="WORKFLOW_ID")
# Check structure
n8n_get_workflow(id="WORKFLOW_ID", mode="structure")
```
**Verify checklist:**
- [ ] All AI nodes have their language model connected
- [ ] All Tool nodes connect to AI Agent via ai_tool
- [ ] All main flow connections are intact (trigger → process → output)
- [ ] No "?" nodes in UI (check via browser if available)
- [ ] Node typeVersions compatible with target n8n version
## Step 5: Test Execution
```
# Test via webhook trigger
n8n_test_workflow(workflowId="WORKFLOW_ID", triggerType="webhook", data={...})
# Check execution results
n8n_executions(action="list", workflowId="WORKFLOW_ID", status="error", limit=5)
# Get error details
n8n_executions(action="get", id="EXECUTION_ID", mode="error")
```
## Deployment Checklist
When deploying a workflow to a new n8n instance:
1. **Export** workflow JSON from source
2. **Check n8n version** of target (health check or UI)
3. **Import** workflow (paste JSON or use API)
4. **Fix connections** — AI connections ALWAYS get lost on import
5. **Fix node versions** — if source is newer than target
6. **Map credentials** — credential IDs differ between instances
7. **Update URLs**`localhost` → production URLs (e.g. `host.docker.internal`)
8. **Validate** — run full validation
9. **Test** — execute and verify results
10. **Activate** — enable schedule triggers for production
## REST API Fallback
When n8n MCP doesn't connect to the target instance, use direct REST API calls:
```python
import json, urllib.request, ssl
API_KEY = "your-api-key"
BASE_URL = "https://your-n8n.com/api/v1"
WORKFLOW_ID = "your-workflow-id"
ctx = ssl.create_default_context()
# GET workflow
req = urllib.request.Request(
f"{BASE_URL}/workflows/{WORKFLOW_ID}",
headers={"X-N8N-API-KEY": API_KEY}
)
wf = json.loads(urllib.request.urlopen(req, context=ctx).read())
# Modify connections
wf['connections']['OpenAI Chat Model'] = {
'ai_languageModel': [[{'index': 0, 'node': 'AI Agent', 'type': 'ai_languageModel'}]]
}
# PUT updated workflow
data = json.dumps({
'name': wf['name'], 'nodes': wf['nodes'],
'connections': wf['connections'], 'settings': wf.get('settings', {})
}, ensure_ascii=False).encode()
req2 = urllib.request.Request(
f"{BASE_URL}/workflows/{WORKFLOW_ID}",
data=data, method="PUT",
headers={"X-N8N-API-KEY": API_KEY, "Content-Type": "application/json"}
)
urllib.request.urlopen(req2, context=ctx)
```
## Anti-Patterns
### ❌ Import and Assume It Works
**Why bad**: AI connections ALWAYS break on import. Tool nodes may use incompatible types.
**Instead**: Always run the Fix → Validate → Test loop after every import.
### ❌ Manual UI Connection Dragging for AI Nodes
**Why bad**: Fragile, error-prone, doesn't scale.
**Instead**: Use `n8n_update_partial_workflow` with `addConnection` operations.
### ❌ Ignoring typeVersion Mismatches
**Why bad**: Nodes show "?" and workflow won't execute.
**Instead**: Always check target n8n version and downgrade typeVersions if needed.
### ❌ Hardcoding Credential IDs
**Why bad**: Credential IDs differ between n8n instances.
**Instead**: Let n8n match credentials by name, or remap in UI after deploy.
## MCP Tools Quick Reference
| Task | Tool | Key Params |
| --------------- | ----------------------------- | ---------------------------- |
| List workflows | `n8n_list_workflows` | `active`, `tags` |
| Get workflow | `n8n_get_workflow` | `id`, `mode` |
| Validate | `n8n_validate_workflow` | `id` |
| Auto-fix | `n8n_autofix_workflow` | `id`, `applyFixes` |
| Partial update | `n8n_update_partial_workflow` | `id`, `operations` |
| Full update | `n8n_update_full_workflow` | `id`, `nodes`, `connections` |
| Test/trigger | `n8n_test_workflow` | `workflowId`, `triggerType` |
| Executions | `n8n_executions` | `action`, `workflowId` |
| Search nodes | `search_nodes` | `query` |
| Node info | `get_node` | `nodeType` |
| Deploy template | `n8n_deploy_template` | `templateId` |
| Version history | `n8n_workflow_versions` | `mode`, `workflowId` |
## Related Skills
Works well with: `ai-agents-architect`, `fastapi-pro`, `langgraph`
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment