---
name: n8n
description: Meta-skill n8n para criação e gestão de workflows na instância automator.descomplicar.pt. Cobre health check, webhooks, schedule (cron), sync de dados, notify (Slack/email/SMS) e chatbots/AI agents (LangChain/RAG). Triggers — n8n, workflow, automação, webhook, schedule, cron, sync, notify, alerta, slack, chatbot, ai agent, langchain, rag, automator, health check n8n.
---

# /n8n - Meta-skill n8n

Skill unificada para a instância n8n Descomplicar (`https://automator.descomplicar.pt`, MCP `mcp__n8n__*`). Substitui as antigas n8n-chatbot, n8n-health, n8n-notify, n8n-schedule, n8n-sync, n8n-webhook.

## Contexto NotebookLM (sempre antes de executar)

| Notebook | ID |
|----------|-----|
| n8n Deep Research | `f2c809b8-1cb5-4dd0-aa7e-be2cfb6704d1` |

```
mcp__notebooklm__notebook_query({ notebook_id: "f2c809b8-1cb5-4dd0-aa7e-be2cfb6704d1", query: "<adaptar ao pedido>" })
```

## Workflow obrigatório (qualquer criação)

```
1. mcp__n8n__n8n_health_check()
2. mcp__n8n__search_templates({ task: "<webhook|scheduling|data_sync|notification|ai_automation>" })
3. Se template adequado -> mcp__n8n__n8n_deploy_template()
4. Caso contrário, criar do zero seguindo a secção apropriada abaixo
```

---

## 1. Health (diagnóstico)

```
/n8n health           # status rápido
/n8n health verbose   # diagnóstico completo
```

```js
mcp__n8n__n8n_health_check({ mode: "status" })
mcp__n8n__n8n_health_check({ mode: "diagnostic", verbose: true })
```

Output esperado: status (OK/ERRO), URL, versão MCP, response time, workflows activos.

Erros comuns: Connection refused (n8n offline), 401 (API key inválida — regenerar), timeout (rede). Diagnóstico manual:
```bash
curl -I https://automator.descomplicar.pt
curl -H "X-N8N-API-KEY: $KEY" https://automator.descomplicar.pt/api/v1/workflows
tail ~/.claude/logs/mcp-n8n.log
```

---

## 2. Webhook

Receber dados de sistemas externos.

```
/n8n webhook create <descrição>
/n8n webhook list
/n8n webhook test <workflow_id>
```

```js
mcp__n8n__get_node({ nodeType: "nodes-base.webhook", detail: "standard", includeExamples: true })
mcp__n8n__validate_node({ nodeType: "nodes-base.webhook", config: { httpMethod: "POST", path: "meu-webhook", responseMode: "onReceived" }, mode: "minimal" })
mcp__n8n__n8n_create_workflow({ name: "Webhook - X", nodes: [...], connections: {...}, active: true })
```

Parâmetros: `httpMethod` (GET/POST/PUT/DELETE, default POST), `path` (obrigatório), `authentication` (none/basicAuth/headerAuth), `responseMode` (onReceived/lastNode).

URLs: produção `https://automator.descomplicar.pt/webhook/<path>` | teste `https://automator.descomplicar.pt/webhook-test/<path>`.

Nodes processamento: `nodes-base.set`, `nodes-base.if`, `nodes-base.code`, `nodes-base.httpRequest`.

Teste:
```js
mcp__n8n__n8n_test_workflow({ workflowId: "wf-xxx", inputData: { body: {test:"data"}, headers: {"Content-Type":"application/json"} } })
```
```bash
curl -X POST https://automator.descomplicar.pt/webhook/meu-webhook -H "Content-Type: application/json" -d '{"test":"data"}'
```

Troubleshooting: 404 (workflow não activo), 401 (auth), dados não chegam (responseMode).

---

## 3. Schedule (cron)

Workflows com execução agendada.

```
/n8n schedule create <descrição>
/n8n schedule list
/n8n schedule disable <id>
```

Cron comuns: `0 9 * * *` (diário 9h), `0 9 * * 1-5` (Seg-Sex 9h), `0 */2 * * *` (cada 2h), `*/15 * * * *` (15min), `0 0 1 * *` (dia 1), `0 3 * * 0` (domingos 3h).

```js
mcp__n8n__validate_node({
  nodeType: "nodes-base.scheduleTrigger",
  config: { rule: { interval: [{ field: "cronExpression", expression: "0 9 * * 1-5" }] }, options: { timezone: "Europe/Lisbon" } },
  mode: "minimal"
})
```

Gestão:
```js
mcp__n8n__n8n_update_partial_workflow({ id: "wf-xxx", operations: [{ type: "deactivateWorkflow" }] })
mcp__n8n__n8n_update_partial_workflow({ id: "wf-xxx", operations: [{ type: "activateWorkflow" }] })
mcp__n8n__n8n_executions({ workflowId: "wf-xxx", limit: 10, status: "all" })
```

Exemplos: relatório diário (Schedule -> Postgres -> Set -> Email), backup semanal (Schedule -> SSH -> IF -> Slack), limpeza logs.

Troubleshooting: não executa (workflow inactivo), hora errada (timezone), duplicado (múltiplos triggers).

---

## 4. Sync (sincronização de dados)

```
/n8n sync create <origem> <destino>
/n8n sync list
/n8n sync status <workflow_id>
```

Padrões: One-Way (origem -> transform -> destino), Two-Way (com resolução conflitos), Hub-and-Spoke.

Nodes:
- APIs: `nodes-base.httpRequest`, `nodes-base.webhook`
- BD: `nodes-base.postgres`, `nodes-base.mySql`, `nodes-base.mongoDb`
- Ficheiros: `nodes-base.googleSheets`, `nodes-base.spreadsheetFile`, `nodes-base.ftp`

Estratégias: Full Sync, Incremental (updated_at), Delta (hashes).

Upsert:
```js
{ nodeType: "nodes-base.postgres", config: { operation: "upsert", table: "clientes", columns: "email,nome,empresa", conflictColumns: "email" } }
```

Erros: retry (`{ options: { retry: { maxRetries: 3, retryInterval: 1000 } } }`), Dead Letter Queue (Error Trigger -> BD -> Slack).

Exemplo CRM->Sheets: Schedule -> HTTP GET leads -> IF -> Set -> Google Sheets append -> Slack.

Troubleshooting: duplicados (upsert), timeout (batches menores), rate limit (delays).

---

## 5. Notify (alertas)

```
/n8n notify create <descrição>
/n8n notify slack <mensagem>
/n8n notify email <para> <assunto>
```

Canais: Slack (`nodes-base.slack`), Email (`nodes-base.emailSend`), Telegram, Discord, SMS Twilio.

Slack:
```js
mcp__n8n__validate_node({
  nodeType: "nodes-base.slack",
  config: { resource: "message", operation: "post", channel: "#alertas", text: "..." },
  mode: "minimal"
})
```

Mensagem formatada (Blocks): header + section com `mrkdwn` e `{{ $json.message }}`.

Email:
```js
mcp__n8n__validate_node({
  nodeType: "nodes-base.emailSend",
  config: { fromEmail: "alertas@descomplicar.pt", toEmail: "emanuel@descomplicar.pt", subject: "Alerta: {{ $json.title }}", text: "{{ $json.message }}" },
  mode: "minimal"
})
```

Padrões: Webhook->Slack, Monitor->Multi-canal (Schedule -> HTTP -> IF -> Slack+Email), Error Handler (Error Trigger -> Slack).

Níveis: Info (Slack), Warning (Slack+Email), Critical (Slack+Email+SMS) — implementar com IF aninhado por `severity`.

Troubleshooting: Slack não envia (token/canal), email em spam (SPF/DKIM), rate limited (agrupar).

---

## 6. Chatbot / AI Agents (LangChain)

```
/n8n chatbot create <descrição>
/n8n chatbot agent <tipo>
/n8n chatbot rag <knowledge_base>
```

### Nodes LangChain

Core: `@n8n/n8n-nodes-langchain.agent`, `chainLlm`, `chainRetrievalQa`.
Modelos: `lmChatOpenAi`, `lmChatAnthropic`, `lmChatOllama`.
Memória: `memoryBufferWindow`, `memoryPostgresChat`, `memoryRedisChat`.
Tools: `toolCalculator`, `toolCode`, `toolHttpRequest`, `toolWorkflow`.
Vector Stores: `vectorStoreSupabase`, `vectorStorePinecone`, `vectorStorePgVector`.

### Chatbot básico

```
Webhook -> LLM Chat -> Memory Buffer -> Agent -> Resposta
```

### RAG

```
Documentos -> Embeddings -> Vector Store -> Query -> Retriever -> LLM
```

```js
mcp__n8n__validate_node({
  nodeType: "@n8n/n8n-nodes-langchain.vectorStoreSupabase",
  config: { mode: "insert", tableName: "documents", queryName: "match_documents" },
  mode: "minimal"
})
```

### AI Agent com tools

```js
mcp__n8n__validate_node({
  nodeType: "@n8n/n8n-nodes-langchain.agent",
  config: { agentType: "conversationalAgent", systemMessage: "Tu és um assistente prestável...", options: { returnIntermediateSteps: true } },
  mode: "minimal"
})
```

### Exemplos práticos

- Suporte: Webhook -> Memory Postgres -> Vector Store -> Chain Retrieval QA -> Webhook Response.
- Agent CRM: Webhook -> Agent (tools: pesquisar/criar lead/actualizar tarefa) -> Slack.
- Resumo PDFs: Webhook -> PDF Extract -> Text Splitter -> LLM Chain -> Email.

### Credenciais

OpenAI/Anthropic (API Key), Supabase (URL+Key), Pinecone (API Key).

### Boas práticas

System prompt claro | temperatura 0.1-0.3 | memória limitada | retry on error | logs de conversas.

### Troubleshooting

Inconsistente (baixar temperatura), contexto perdido (memória), RAG vazio (embeddings), timeout (limite), token limit (resumir).

---

## Templates

```js
mcp__n8n__search_templates({ searchMode: "by_task", task: "ai_automation" })
mcp__n8n__search_templates({ searchMode: "keyword", query: "chatbot langchain openai" })
```

---

**Versão:** 2.0.0 (consolidação 6->1, 07-04-2026) | **Autor:** Descomplicar®

## Healing Log

```jsonl
{"date":"","issue":"","fix":"","source":"user|auto"}
```
