{
  "name": "MazyOS · AI Agent + Postgres Chat Memory + Structured Output + MCP + Transbordo Chatwoot",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "chatwoot-agente-ia",
        "options": {}
      },
      "id": "node-webhook-chatwoot",
      "name": "Webhook Chatwoot",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [200, 340],
      "webhookId": "chatwoot-agente-ia"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "cond-incoming",
              "leftValue": "={{ $json.body?.message_type }}",
              "rightValue": "incoming",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            },
            {
              "id": "cond-ia-ativa",
              "leftValue": "={{ ($json.body?.conversation?.custom_attributes?.ia_pausada ?? false) }}",
              "rightValue": false,
              "operator": {
                "type": "boolean",
                "operation": "equals"
              }
            },
            {
              "id": "cond-sem-etiqueta-humano",
              "leftValue": "={{ ($json.body?.conversation?.labels ?? []).includes('atendimento-humano') }}",
              "rightValue": false,
              "operator": {
                "type": "boolean",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "node-checar-ia-pausada",
      "name": "IA Ativa na Conversa?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [440, 340]
    },
    {
      "parameters": {
        "model": "deepseek-flash",
        "options": {
          "temperature": 0.3
        }
      },
      "id": "node-llm-modelo",
      "name": "Modelo Chat (DeepSeek / OpenRouter)",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.2,
      "position": [680, 560],
      "credentials": {
        "openAiApi": {
          "id": "${N8N_LLM_CREDENTIAL_ID}",
          "name": "API IA (${LLM_BASE_URL})"
        }
      }
    },
    {
      "parameters": {
        "sessionIdType": "customKey",
        "sessionKey": "={{ 'cw:' + ($json.body.conversation.id) }}",
        "tableName": "n8n_chat_histories",
        "contextWindowLength": 15
      },
      "id": "node-postgres-memory",
      "name": "Postgres Chat Memory",
      "type": "@n8n/n8n-nodes-langchain.memoryPostgresChat",
      "typeVersion": 1.3,
      "position": [860, 560],
      "credentials": {
        "postgres": {
          "id": "${N8N_POSTGRES_CREDENTIAL_ID}",
          "name": "Postgres VPS"
        }
      }
    },
    {
      "parameters": {
        "sseEndpoint": "${MCP_SERVER_SSE_URL}",
        "authentication": "bearerAuth"
      },
      "id": "node-mcp-client-tool",
      "name": "MCP Client Tool",
      "type": "@n8n/n8n-nodes-langchain.mcpClientTool",
      "typeVersion": 1,
      "position": [1040, 560],
      "credentials": {
        "httpBearerAuth": {
          "id": "${N8N_MCP_CREDENTIAL_ID}",
          "name": "Bearer MCP (${MCP_AUTH_TOKEN})"
        }
      }
    },
    {
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n  \"type\": \"object\",\n  \"properties\": {\n    \"resposta\": { \"type\": \"string\", \"description\": \"Resposta final para o cliente em um único bloco de texto\" },\n    \"transbordo_humano\": { \"type\": \"boolean\", \"description\": \"true quando o cliente pede atendente humano, reclamação ou caso fora do escopo\" },\n    \"etiqueta_sugerida\": { \"type\": \"string\", \"enum\": [\"qualificacao\", \"agendamento\", \"atendimento-humano\", \"suporte\"] },\n    \"resumo_interno\": { \"type\": \"string\" }\n  },\n  \"required\": [\"resposta\", \"transbordo_humano\", \"etiqueta_sugerida\", \"resumo_interno\"]\n}"
      },
      "id": "node-structured-output",
      "name": "Structured Output Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "typeVersion": 1.2,
      "position": [1220, 560]
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "={{ $json.body.content }}",
        "hasOutputParser": true,
        "options": {
          "systemMessage": "Você é o agente oficial de atendimento da empresa. Consulte as ferramentas MCP para agenda ou catálogo antes de prometer horário ou preço. Nunca invente valores. Se o cliente pedir para falar com um atendente, marque transbordo_humano = true."
        }
      },
      "id": "node-ai-agent-principal",
      "name": "AI Agent + MCP",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 1.7,
      "position": [880, 260]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "cond-transbordo",
              "leftValue": "={{ $json.output.transbordo_humano }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "node-if-transbordo",
      "name": "Precisa de Humano?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [1220, 260]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=${CHATWOOT_BASE_URL}/api/v1/accounts/{{ $('Webhook Chatwoot').item.json.body.account.id }}/conversations/{{ $('Webhook Chatwoot').item.json.body.conversation.id }}/labels",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "api_access_token",
              "value": "${CHATWOOT_API_TOKEN}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"labels\": [\"atendimento-humano\"]\n}",
        "options": {}
      },
      "id": "node-etiqueta-humano",
      "name": "Etiquetar Transbordo no Chatwoot",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [1480, 140]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=${CHATWOOT_BASE_URL}/api/v1/accounts/{{ $('Webhook Chatwoot').item.json.body.account.id }}/conversations/{{ $('Webhook Chatwoot').item.json.body.conversation.id }}/messages",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "api_access_token",
              "value": "${CHATWOOT_API_TOKEN}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"content\": \"[Transbordo IA] {{ $('AI Agent + MCP').item.json.output.resumo_interno }}\",\n  \"message_type\": \"outgoing\",\n  \"private\": true\n}",
        "options": {}
      },
      "id": "node-nota-transbordo",
      "name": "Enviar Nota Privada de Contexto",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [1720, 140]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=${CHATWOOT_BASE_URL}/api/v1/accounts/{{ $('Webhook Chatwoot').item.json.body.account.id }}/conversations/{{ $('Webhook Chatwoot').item.json.body.conversation.id }}/messages",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "api_access_token",
              "value": "${CHATWOOT_API_TOKEN}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"content\": \"{{ $('AI Agent + MCP').item.json.output.resposta }}\",\n  \"message_type\": \"outgoing\",\n  \"private\": false\n}",
        "options": {}
      },
      "id": "node-responder-cliente-cw",
      "name": "Enviar Resposta no Chatwoot",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [1480, 380]
    }
  ],
  "connections": {
    "Webhook Chatwoot": {
      "main": [[{ "node": "IA Ativa na Conversa?", "type": "main", "index": 0 }]]
    },
    "IA Ativa na Conversa?": {
      "main": [[{ "node": "AI Agent + MCP", "type": "main", "index": 0 }]]
    },
    "Modelo Chat (DeepSeek / OpenRouter)": {
      "ai_languageModel": [[{ "node": "AI Agent + MCP", "type": "ai_languageModel", "index": 0 }]]
    },
    "Postgres Chat Memory": {
      "ai_memory": [[{ "node": "AI Agent + MCP", "type": "ai_memory", "index": 0 }]]
    },
    "MCP Client Tool": {
      "ai_tool": [[{ "node": "AI Agent + MCP", "type": "ai_tool", "index": 0 }]]
    },
    "Structured Output Parser": {
      "ai_outputParser": [[{ "node": "AI Agent + MCP", "type": "ai_outputParser", "index": 0 }]]
    },
    "AI Agent + MCP": {
      "main": [[{ "node": "Precisa de Humano?", "type": "main", "index": 0 }]]
    },
    "Precisa de Humano?": {
      "main": [
        [{ "node": "Etiquetar Transbordo no Chatwoot", "type": "main", "index": 0 }],
        [{ "node": "Enviar Resposta no Chatwoot", "type": "main", "index": 0 }]
      ]
    },
    "Etiquetar Transbordo no Chatwoot": {
      "main": [[{ "node": "Enviar Nota Privada de Contexto", "type": "main", "index": 0 }]]
    },
    "Enviar Nota Privada de Contexto": {
      "main": [[{ "node": "Enviar Resposta no Chatwoot", "type": "main", "index": 0 }]]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "meta": {
    "templateCredsSetupCompleted": false
  }
}
