{
  "id": "ZarifToolGuard01",
  "name": "Tool call guard: catch failed tool calls behind a green run",
  "active": false,
  "nodes": [
    {
      "id": "note-how-to",
      "name": "How to use this workflow",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -260,
        -420
      ],
      "parameters": {
        "content": "## Tool call guard (Zarif Automates, v1)\n\nCatches tool calls that failed even though the n8n run looks green: an empty result, an error field, a non-2xx status, or missing fields.\n\n**Try it:** click Execute workflow. The sample run ends red at **Fail the run** on purpose.\n\n**Use it:** delete **Sample tool calls**, call this workflow from your agent workflow with an Execute Workflow node, and edit REQUIRED_FIELDS in **Check tool result**.\n\nNodes named PLACEHOLDER do nothing yet. Replace them.\n\nGuide: https://www.zarifautomates.com/blog/n8n-tool-call-guard-workflow",
        "height": 340,
        "width": 520,
        "color": 4
      }
    },
    {
      "id": "manual",
      "name": "Run with sample tool calls",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        0
      ],
      "parameters": {}
    },
    {
      "id": "samples",
      "name": "Sample tool calls",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Made-up tool calls for a test run. Nothing here calls a real tool.\n// Delete this node once the guard receives real tool calls.\nreturn [\n  { tool: 'lookup_order', statusCode: 200, attempt: 1, result: { order_id: 'A-1001', status: 'shipped' } },\n  { tool: 'lookup_order', statusCode: 200, attempt: 1, result: {} },\n  { tool: 'create_ticket', statusCode: 200, attempt: 1, result: { success: false, error: { message: 'subject is required' } } },\n  { tool: 'lookup_order', statusCode: 404, attempt: 1, result: { message: 'Not Found' } },\n  { tool: 'lookup_order', statusCode: 200, attempt: 1, result: { id: 'A-1003', state: 'shipped' } },\n  { tool: 'search_docs', statusCode: 503, attempt: 1, result: '' },\n  { tool: 'search_docs', statusCode: 503, attempt: 2, result: '' },\n  {\n    output: 'I created the ticket for you.',\n    intermediateSteps: [\n      { action: { tool: 'lookup_order', toolInput: { order_id: 'A-1004' } }, observation: '{\"order_id\":\"A-1004\",\"status\":\"processing\"}' },\n      { action: { tool: 'create_ticket', toolInput: { subject: 'Late order A-1004' } }, observation: '{\"error\":\"rate limit exceeded\",\"statusCode\":429}' },\n    ],\n  },\n].map((json) => ({ json }));"
      }
    },
    {
      "id": "called",
      "name": "When called by another workflow",
      "type": "n8n-nodes-base.executeWorkflowTrigger",
      "typeVersion": 1.1,
      "position": [
        220,
        200
      ],
      "parameters": {
        "inputSource": "passthrough"
      }
    },
    {
      "id": "split",
      "name": "Split out tool calls",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        460,
        100
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// One output item per tool call. Accepts two input shapes:\n// 1. AI Agent output with \"Return Intermediate Steps\" on:\n//    { output, intermediateSteps: [{ action: { tool, toolInput }, observation }] }\n// 2. A single tool result you send yourself:\n//    { tool, statusCode, attempt, result }\n// JSON text is parsed: an object, a list, or a JSON-encoded string, so an\n// observation of \"\" (two quote characters) counts as an empty result.\nfunction parseMaybeJson(value) {\n  if (typeof value !== 'string') return value;\n  const text = value.trim();\n  if (!text.startsWith('{') && !text.startsWith('[') && !text.startsWith('\"')) return value;\n  try {\n    return JSON.parse(text);\n  } catch {\n    return value;\n  }\n}\n\nconst calls = [];\n$input.all().forEach((item, index) => {\n  const row = item.json;\n  const attempt = Number.isInteger(row.attempt) ? row.attempt : 1;\n  if (Array.isArray(row.intermediateSteps)) {\n    row.intermediateSteps.forEach((step, stepIndex) => {\n      const result = parseMaybeJson(step.observation);\n      const statusCode = result && typeof result === 'object' && Number.isInteger(result.statusCode) ? result.statusCode : null;\n      calls.push({\n        json: { tool: step.action?.tool ?? 'unknown', source: 'agent-step', step: stepIndex + 1, attempt, statusCode, result },\n        pairedItem: { item: index },\n      });\n    });\n    return;\n  }\n  calls.push({\n    json: {\n      tool: row.tool ?? 'unknown',\n      source: 'tool-result',\n      step: null,\n      attempt,\n      statusCode: Number.isInteger(row.statusCode) ? row.statusCode : null,\n      result: parseMaybeJson(row.result),\n    },\n    pairedItem: { item: index },\n  });\n});\nreturn calls;"
      }
    },
    {
      "id": "check",
      "name": "Check tool result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        680,
        100
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// EDIT: the fields each tool must return. A tool not listed skips the schema check.\nconst REQUIRED_FIELDS = {\n  lookup_order: ['order_id', 'status'],\n  create_ticket: ['ticket_id'],\n};\n// EDIT: how many times one tool call may run before it alerts instead of retrying.\nconst MAX_ATTEMPTS = 2;\n// Status codes that are often temporary. Any other failure alerts straight away.\nconst RETRYABLE_STATUS = [408, 429, 500, 502, 503, 504];\n\nfunction isEmpty(value) {\n  if (value === null || value === undefined) return true;\n  if (typeof value === 'string') return value.trim() === '';\n  if (Array.isArray(value)) return value.length === 0;\n  if (typeof value === 'object') return Object.keys(value).length === 0;\n  return false;\n}\n\nfunction errorFields(value) {\n  if (typeof value === 'string') return /^\\s*error\\b/i.test(value) ? ['text starts with error'] : [];\n  if (!value || typeof value !== 'object' || Array.isArray(value)) return [];\n  const found = [];\n  if (value.error) found.push('error');\n  if (Array.isArray(value.errors) ? value.errors.length > 0 : Boolean(value.errors)) found.push('errors');\n  if (value.success === false) found.push('success is false');\n  if (value.ok === false) found.push('ok is false');\n  return found;\n}\n\nreturn $input.all().map((item, index) => {\n  const call = item.json;\n  const signals = [];\n  const status = call.statusCode;\n  if (Number.isInteger(status) && (status < 200 || status > 299)) signals.push('non_2xx_status: ' + status);\n  const fields = errorFields(call.result);\n  if (fields.length > 0) signals.push('error_field: ' + fields.join(', '));\n  if (isEmpty(call.result)) signals.push('empty_result');\n  const required = REQUIRED_FIELDS[call.tool];\n  if (required && signals.length === 0) {\n    const body = call.result;\n    const isObject = body !== null && typeof body === 'object' && !Array.isArray(body);\n    const missing = isObject ? required.filter((key) => body[key] === undefined || body[key] === null) : required;\n    if (missing.length > 0) signals.push('schema_mismatch: missing ' + missing.join(', '));\n  }\n  const attempt = Number.isInteger(call.attempt) ? call.attempt : 1;\n  const passed = signals.length === 0;\n  const retry = !passed && Number.isInteger(status) && RETRYABLE_STATUS.includes(status) && attempt < MAX_ATTEMPTS;\n  return {\n    json: {\n      ...call,\n      guard: {\n        passed,\n        retry,\n        route: passed ? 'pass' : retry ? 'retry' : 'alert',\n        signals,\n        attempt,\n        maxAttempts: MAX_ATTEMPTS,\n        nextAttempt: retry ? attempt + 1 : null,\n      },\n    },\n    pairedItem: { item: index },\n  };\n});"
      }
    },
    {
      "id": "passed",
      "name": "Tool call passed?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        900,
        100
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "Tool call passed?-condition",
              "leftValue": "={{ $json.guard.passed }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "continue",
      "name": "Passed: continue here",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        1140,
        0
      ],
      "parameters": {},
      "notes": "Connect whatever should happen with a good tool result here.",
      "notesInFlow": true
    },
    {
      "id": "retry",
      "name": "Worth a retry?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1140,
        200
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "Worth a retry?-condition",
              "leftValue": "={{ $json.guard.retry }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "wait",
      "name": "Wait before retry",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        1380,
        120
      ],
      "parameters": {
        "resume": "timeInterval",
        "amount": 5,
        "unit": "seconds"
      }
    },
    {
      "id": "retry-placeholder",
      "name": "PLACEHOLDER: call the tool again",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        1600,
        120
      ],
      "parameters": {},
      "notes": "PLACEHOLDER. Replace with the node that repeats this tool call, then send its result back into this workflow with attempt set to guard.nextAttempt.",
      "notesInFlow": true
    },
    {
      "id": "alert",
      "name": "Build alert message",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1380,
        320
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// One alert for every tool call that failed for good in this run.\nconst failures = $input.all().map((item) => ({\n  tool: item.json.tool,\n  step: item.json.step,\n  attempt: item.json.guard.attempt,\n  signals: item.json.guard.signals,\n}));\nconst lines = failures.map((f) => '- ' + f.tool + (f.step ? ' (agent step ' + f.step + ')' : '') + ', attempt ' + f.attempt + ': ' + f.signals.join('; '));\nconst text = failures.length + ' tool call(s) failed behind a successful-looking run:\\n' + lines.join('\\n');\nreturn [{ json: { failedToolCalls: failures.length, failures, text } }];"
      }
    },
    {
      "id": "fail",
      "name": "Fail the run",
      "type": "n8n-nodes-base.stopAndError",
      "typeVersion": 1,
      "position": [
        1600,
        320
      ],
      "parameters": {
        "errorMessage": "={{ $json.text }}"
      }
    },
    {
      "id": "error-trigger",
      "name": "When a run fails",
      "type": "n8n-nodes-base.errorTrigger",
      "typeVersion": 1,
      "position": [
        0,
        560
      ],
      "parameters": {}
    },
    {
      "id": "describe",
      "name": "Describe the failed run",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        560
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// The Error Trigger receives the failed run. Turn it into one message.\nreturn $input.all().map((item, index) => {\n  const run = item.json.execution ?? {};\n  const workflow = item.json.workflow ?? {};\n  const text = 'n8n run failed: ' + (workflow.name ?? 'unknown workflow') +\n    ' stopped at ' + (run.lastNodeExecuted ?? 'an unknown node') +\n    '. ' + (run.error?.message ?? 'No error message.') +\n    (run.url ? ' ' + run.url : '');\n  return { json: { text, workflowName: workflow.name ?? null, executionUrl: run.url ?? null }, pairedItem: { item: index } };\n});"
      }
    },
    {
      "id": "notify-placeholder",
      "name": "PLACEHOLDER: send the alert",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        460,
        560
      ],
      "parameters": {},
      "notes": "PLACEHOLDER. Replace with your Slack, email, Telegram or HTTP Request node. Send the text field.",
      "notesInFlow": true
    }
  ],
  "connections": {
    "Run with sample tool calls": {
      "main": [
        [
          {
            "node": "Sample tool calls",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sample tool calls": {
      "main": [
        [
          {
            "node": "Split out tool calls",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When called by another workflow": {
      "main": [
        [
          {
            "node": "Split out tool calls",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split out tool calls": {
      "main": [
        [
          {
            "node": "Check tool result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check tool result": {
      "main": [
        [
          {
            "node": "Tool call passed?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Tool call passed?": {
      "main": [
        [
          {
            "node": "Passed: continue here",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Worth a retry?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Worth a retry?": {
      "main": [
        [
          {
            "node": "Wait before retry",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build alert message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait before retry": {
      "main": [
        [
          {
            "node": "PLACEHOLDER: call the tool again",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build alert message": {
      "main": [
        [
          {
            "node": "Fail the run",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When a run fails": {
      "main": [
        [
          {
            "node": "Describe the failed run",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Describe the failed run": {
      "main": [
        [
          {
            "node": "PLACEHOLDER: send the alert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {},
  "tags": []
}
