---
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 Ops — fix nhanh, check kỹ, test đến khi ngon

You manage n8n workflows by **combining two tools flexibly**:
- **n8n MCP** — API-level: read/write workflow JSON, validate, fix connections, update nodes
- **Playwright MCP** — Visual: open n8n UI, see errors, check node status, click test

Don't follow a rigid script. **Observe → Diagnose → Fix → Verify** — loop until clean.

## Philosophy

1. **Check lỗi trước, fix sau** — đừng đoán, hãy xem thực tế
2. **Kết hợp linh hoạt** — dùng n8n MCP khi cần sửa data, Playwright khi cần nhìn UI
3. **Loop đến khi pass** — mỗi vòng fix 1 loại lỗi, verify, rồi tìm lỗi tiếp
4. **Không hard-code** — mỗi workflow khác nhau, đọc rồi mới quyết

## Workflow: Observe → Fix → Verify Loop

```
 ┌──────────────────────────────┐
 │  OBSERVE                     │
 │  • n8n MCP: get workflow     │
 │  • Playwright: open UI, look │
 │  • What's broken?            │
 └──────────┬───────────────────┘
            ▼
 ┌──────────────────────────────┐
 │  DIAGNOSE                    │
 │  • "?" nodes = wrong type    │
 │  • Missing lines = lost conn │
 │  • Red errors = bad config   │
 │  • Credential warnings       │
 └──────────┬───────────────────┘
            ▼
 ┌──────────────────────────────┐
 │  FIX                         │
 │  • n8n MCP: update nodes     │
 │  • n8n MCP: add connections  │
 │  • n8n MCP: autofix          │
 │  • Playwright: click assign  │
 └──────────┬───────────────────┘
            ▼
 ┌──────────────────────────────┐
 │  VERIFY                      │
 │  • n8n MCP: validate         │
 │  • Playwright: reload, check │
 │  • Still broken? → go back   │
 │  • Clean? → TEST             │
 └──────────┬───────────────────┘
            ▼
 ┌──────────────────────────────┐
 │  TEST                        │
 │  • Execute workflow          │
 │  • Check execution result    │
 │  • Errors? → OBSERVE again   │
 │  • Pass? → ✅ DONE           │
 └──────────────────────────────┘
```

## How to Observe

### Via n8n MCP (data-level)
```
# Quick overview
n8n_get_workflow(id="ID", mode="structure")

# Full details with params
n8n_get_workflow(id="ID", mode="full")

# Run validation
n8n_validate_workflow(id="ID")

# Check recent executions
n8n_executions(action="list", workflowId="ID", status="error", limit=5)
```

### Via Playwright (visual)
```
# Open workflow in browser
browser_navigate(url="https://your-n8n.com/workflow/ID")

# Take snapshot to see node states
browser_snapshot()

# Look for:
# - "?" icons = node type not installed
# - Dashed lines = AI connections (ok)
# - Missing lines = broken connections
# - Red badges = errors
# - Yellow triangles = warnings

# Screenshot for documentation
browser_take_screenshot(type="png")
```

### Combining Both
1. **Playwright first** — open workflow UI, take snapshot, identify visual issues
2. **n8n MCP second** — get structure, understand what's actually in the JSON
3. **Compare** — what does UI show vs what's in data? Gaps = problems to fix

## How to Fix

### Fix connections (n8n MCP)
```
# Add single connection
n8n_update_partial_workflow(id="ID", operations=[
  {type: "addConnection", source: "Node A", target: "Node B"}
])

# Add AI connections (most common issue on import!)
n8n_update_partial_workflow(id="ID", operations=[
  {type: "addConnection", source: "LLM Node", target: "Agent", sourceOutput: "ai_languageModel"},
  {type: "addConnection", source: "Tool Node", target: "Agent", sourceOutput: "ai_tool"}
])

# Clean broken connections
n8n_update_partial_workflow(id="ID", operations=[
  {type: "cleanStaleConnections"}
])
```

### Fix node types/versions (n8n MCP)
```
# Downgrade typeVersion for older n8n
n8n_update_partial_workflow(id="ID", operations=[
  {type: "updateNode", nodeName: "Node Name", updates: {typeVersion: 1.6}}
])

# Swap node type entirely
n8n_update_partial_workflow(id="ID", operations=[
  {type: "updateNode", nodeName: "Tool Node", updates: {
    type: "@n8n/n8n-nodes-langchain.toolHttpRequest",
    typeVersion: 1.1
  }}
])
```

### Fix via autofix (n8n MCP)
```
# Auto-detect and fix common issues
n8n_autofix_workflow(id="ID", applyFixes=true)
```

### Fix credentials (Playwright)
```
# Credentials can't be set via API — use UI
browser_navigate(url="https://n8n.com/workflow/ID")
browser_snapshot()  # Find the node with credential warning
browser_click(ref="node-ref")  # Open node
browser_snapshot()  # See credential dropdown
browser_select_option(ref="credential-dropdown", values=["My Credential"])
```

## How to Verify

### Quick verify (n8n MCP)
```
n8n_validate_workflow(id="ID")
# Check: errors=0, warnings=0
```

### Visual verify (Playwright)
```
# Reload page
browser_navigate(url="https://n8n.com/workflow/ID")
browser_snapshot()
# Check: no "?" nodes, all connections visible, no red badges
browser_take_screenshot(type="png", filename="workflow_verified.png")
```

## How to Test

### Execute workflow (n8n MCP)
```
# Via webhook trigger
n8n_test_workflow(workflowId="ID", triggerType="webhook", data={...})

# Check execution
n8n_executions(action="list", workflowId="ID", limit=1)

# Get error details if failed
n8n_executions(action="get", id="EXEC_ID", mode="error")
```

### Visual test (Playwright)
```
# Click execute in UI
browser_navigate(url="https://n8n.com/workflow/ID")
browser_snapshot()
# Find and click "Execute workflow" button
browser_click(ref="execute-button")
# Wait and check result
browser_wait_for(text="Execution successful", time=30)
browser_take_screenshot(type="png", filename="execution_result.png")
```

## Common Issues & Solutions

| Symptom                 | Diagnosis                             | Fix                                                     |
| ----------------------- | ------------------------------------- | ------------------------------------------------------- |
| Node shows "?"          | typeVersion too new for server        | `updateNode` to lower typeVersion                       |
| Node shows "?"          | Node type doesn't exist               | Swap type (e.g. `httpRequestTool` → `toolHttpRequest`)  |
| AI Agent has no model   | `ai_languageModel` connection missing | `addConnection` with `sourceOutput: "ai_languageModel"` |
| Tools not connected     | `ai_tool` connections missing         | `addConnection` with `sourceOutput: "ai_tool"`          |
| All connections gone    | Import/paste lost them                | Rebuild from source workflow JSON                       |
| Credential warning      | ID mismatch between instances         | Assign in UI via Playwright                             |
| Execution fails at HTTP | URL points to localhost               | `updateNode` to change `parameters.url`                 |

## REST API Fallback

When n8n MCP points to wrong instance, use Python script directly:

```python
import json, urllib.request, ssl

API_KEY = "your-key"
URL = f"https://your-n8n.com/api/v1/workflows/WORKFLOW_ID"
ctx = ssl.create_default_context()

# GET
req = urllib.request.Request(URL, headers={"X-N8N-API-KEY": API_KEY})
wf = json.loads(urllib.request.urlopen(req, context=ctx).read())

# Modify wf['connections'], wf['nodes'] as needed...

# PUT
data = json.dumps(wf, ensure_ascii=False).encode()
req2 = urllib.request.Request(URL, data=data, method="PUT",
    headers={"X-N8N-API-KEY": API_KEY, "Content-Type": "application/json"})
urllib.request.urlopen(req2, context=ctx)
```

## Key Principles

- **Không hard-code giải pháp** — mỗi workflow khác nhau, đọc trước rồi mới fix
- **Playwright cho mắt, n8n MCP cho tay** — nhìn UI để hiểu, dùng API để sửa
- **Loop không giới hạn** — fix 1 lỗi, verify, phát hiện lỗi mới, fix tiếp
- **Document mọi thứ** — screenshot trước/sau khi fix để bro review
- **Hỏi khi không chắc** — đặc biệt với credentials và URLs production
