{
  "name": "Weekly report of visits from ChatGPT, Perplexity, Gemini and other AI assistants (GA4 + GSC Magic)",
  "nodes": [
    {
      "id": "38afc948-4a7f-4692-a8ce-afd6abbb561f",
      "name": "Every Monday at 08:30",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        0
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "weeks",
              "triggerAtDay": [
                1
              ],
              "triggerAtHour": 8,
              "triggerAtMinute": 30
            }
          ]
        }
      }
    },
    {
      "id": "e49c182e-2162-459e-a2df-b18f99c2e64e",
      "name": "Settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        308,
        0
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "b459d664-24f3-4822-a150-0cd2cf70e50b",
              "name": "ga4PropertyId",
              "value": "123456789",
              "type": "string"
            },
            {
              "id": "5f0a732b-164c-4e89-ac74-462c4f219403",
              "name": "siteName",
              "value": "example.com",
              "type": "string"
            },
            {
              "id": "7a5701a4-9027-4072-a6a0-27c2de91f6bf",
              "name": "slackChannel",
              "value": "#seo-weekly",
              "type": "string"
            },
            {
              "id": "8367508e-666a-449a-a235-4f3d29732735",
              "name": "aiSourcesRegex",
              "value": "chatgpt\\.com|chat\\.openai\\.com|perplexity\\.ai|perplexity|gemini\\.google\\.com|bard\\.google\\.com|claude\\.ai|copilot\\.microsoft\\.com|copilot\\.com|you\\.com|poe\\.com|phind\\.com|deepseek\\.com|chat\\.deepseek\\.com|grok\\.com|meta\\.ai|chat\\.mistral\\.ai|edgeservices\\.bing\\.com",
              "type": "string"
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "c29227f8-da6e-4fde-a732-223e23fe2c3f",
      "name": "GSC Magic: AI sessions this week",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        616,
        0
      ],
      "onError": "continueRegularOutput",
      "parameters": {
        "method": "POST",
        "url": "https://mcp.gscmagic.com/mcp",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBearerAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Accept",
              "value": "application/json, text/event-stream"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'ga_run_report', arguments: { property: $('Settings').first().json.ga4PropertyId, dimensions: ['sessionSource'], metrics: ['sessions', 'engagedSessions', 'keyEvents'], start_date: '7daysAgo', end_date: 'yesterday', dimension_filters: [{ field: 'sessionSource', match_type: 'FULL_REGEXP', value: $('Settings').first().json.aiSourcesRegex }], order_by: [{ field: 'sessions', desc: true }], limit: 50 } } }) }}",
        "options": {
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 300
            }
          },
          "timeout": 180000
        }
      }
    },
    {
      "id": "aa0ab30e-f92f-412f-a280-692a79ede879",
      "name": "GSC Magic: AI sessions week before",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        924,
        0
      ],
      "onError": "continueRegularOutput",
      "parameters": {
        "method": "POST",
        "url": "https://mcp.gscmagic.com/mcp",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBearerAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Accept",
              "value": "application/json, text/event-stream"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'ga_run_report', arguments: { property: $('Settings').first().json.ga4PropertyId, dimensions: ['sessionSource'], metrics: ['sessions', 'engagedSessions', 'keyEvents'], start_date: '14daysAgo', end_date: '8daysAgo', dimension_filters: [{ field: 'sessionSource', match_type: 'FULL_REGEXP', value: $('Settings').first().json.aiSourcesRegex }], order_by: [{ field: 'sessions', desc: true }], limit: 50 } } }) }}",
        "options": {
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 300
            }
          },
          "timeout": 180000
        }
      }
    },
    {
      "id": "fc16bf70-b44c-496b-a9bf-c372edd5a6c2",
      "name": "GSC Magic: AI landing pages",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1232,
        0
      ],
      "onError": "continueRegularOutput",
      "parameters": {
        "method": "POST",
        "url": "https://mcp.gscmagic.com/mcp",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBearerAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Accept",
              "value": "application/json, text/event-stream"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'ga_run_report', arguments: { property: $('Settings').first().json.ga4PropertyId, dimensions: ['sessionSource', 'landingPage'], metrics: ['sessions', 'engagedSessions', 'keyEvents'], start_date: '7daysAgo', end_date: 'yesterday', dimension_filters: [{ field: 'sessionSource', match_type: 'FULL_REGEXP', value: $('Settings').first().json.aiSourcesRegex }], order_by: [{ field: 'sessions', desc: true }], limit: 100 } } }) }}",
        "options": {
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 300
            }
          },
          "timeout": 180000
        }
      }
    },
    {
      "id": "9a821459-8450-4401-a806-c5064be80b01",
      "name": "Build the report",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1540,
        0
      ],
      "parameters": {
        "jsCode": "// Turns a GSC Magic response (MCP JSON-RPC) into { ok, data, error, image }.\nfunction unwrap(res) {\n  const result = res && res.result;\n  if (result && Array.isArray(result.content)) {\n    const text = result.content.filter((b) => b.type === 'text').map((b) => b.text).join('\\n');\n    if (result.isError) return { ok: false, error: text || 'GSC Magic reported an error' };\n    let data;\n    try { data = JSON.parse(text); } catch (e) { data = { text }; }\n    const image = result.content.find((b) => b.type === 'image' && b.data);\n    return { ok: true, data, image };\n  }\n  const err = res && res.error;\n  const message = typeof err === 'string' ? err : (err && (err.message || err.description)) || 'No response from GSC Magic';\n  if (/401|unauthori[sz]ed|Authorization failed/i.test(message)) {\n    return { ok: false, error: 'GSC Magic rejected the access token (wrong, expired or revoked). Create a new one in the GSC Magic dashboard: Connect > Access tokens.' };\n  }\n  return { ok: false, error: String(message) };\n}\n\nconst cfg = $('Settings').first().json;\nconst now = unwrap($('GSC Magic: AI sessions this week').first().json);\nconst prev = unwrap($('GSC Magic: AI sessions week before').first().json);\nconst land = unwrap($('GSC Magic: AI landing pages').first().json);\nconst failed = [now, prev, land].find((r) => !r.ok);\nif (failed) return [{ json: { text: ':warning: *AI assistant traffic* for ' + cfg.siteName + ': GA4 report failed. ' + failed.error } }];\n\nconst ASSISTANTS = [\n  ['ChatGPT', /chatgpt|openai/], ['Perplexity', /perplexity/], ['Gemini', /gemini|bard/], ['Claude', /claude/],\n  ['Copilot', /copilot|edgeservices\\.bing/], ['DeepSeek', /deepseek/], ['Grok', /grok/], ['Meta AI', /meta\\.ai/],\n  ['Mistral', /mistral/], ['You.com', /you\\.com/], ['Poe', /poe\\.com/], ['Phind', /phind/],\n];\nconst nameOf = (source) => (ASSISTANTS.find(([, re]) => re.test(source)) || [source])[0];\nconst group = (rows) => {\n  const out = {};\n  for (const r of rows || []) {\n    const k = nameOf(String(r.sessionSource));\n    out[k] = out[k] || { sessions: 0, engaged: 0, keyEvents: 0 };\n    out[k].sessions += Number(r.sessions) || 0;\n    out[k].engaged += Number(r.engagedSessions) || 0;\n    out[k].keyEvents += Number(r.keyEvents) || 0;\n  }\n  return out;\n};\nconst cur = group(now.data.rows);\nconst old = group(prev.data.rows);\nconst total = (g) => Object.values(g).reduce((s, x) => s + x.sessions, 0);\nconst tNow = total(cur), tOld = total(old);\nconst change = (a, b) => (b ? (a >= b ? '+' : '') + Math.round(((a - b) / b) * 100) + '%' : (a ? 'new' : '0%'));\n\nconst lines = ['*AI assistant traffic* for ' + cfg.siteName + ' (last 7 days vs the 7 before)'];\nif (!tNow && !tOld) {\n  lines.push('No sessions from AI assistants in the last two weeks.');\n} else {\n  const engagedNow = Object.values(cur).reduce((s, x) => s + x.engaged, 0);\n  const keyNow = Object.values(cur).reduce((s, x) => s + x.keyEvents, 0);\n  lines.push('*' + tNow + ' sessions* (' + change(tNow, tOld) + '), engagement rate ' + (tNow ? Math.round((engagedNow / tNow) * 100) : 0) + '%, key events ' + keyNow, '');\n  const names = [...new Set([...Object.keys(cur), ...Object.keys(old)])]\n    .sort((a, b) => ((cur[b] || {}).sessions || 0) - ((cur[a] || {}).sessions || 0));\n  for (const n of names) {\n    const a = (cur[n] || {}).sessions || 0, b = (old[n] || {}).sessions || 0;\n    lines.push('- ' + n + ': ' + a + ' (' + change(a, b) + ')' + (cur[n] && cur[n].keyEvents ? ', ' + cur[n].keyEvents + (cur[n].keyEvents === 1 ? ' key event' : ' key events') : ''));\n  }\n  const byPage = {};\n  for (const r of land.data.rows || []) {\n    const p = String(r.landingPage || '(not set)');\n    byPage[p] = byPage[p] || { sessions: 0, from: new Set() };\n    byPage[p].sessions += Number(r.sessions) || 0;\n    byPage[p].from.add(nameOf(String(r.sessionSource)));\n  }\n  const top = Object.entries(byPage).sort((a, b) => b[1].sessions - a[1].sessions).slice(0, 5);\n  if (top.length) {\n    lines.push('', '*Top landing pages*');\n    for (const [p, v] of top) lines.push('- ' + p + ': ' + v.sessions + ' (' + [...v.from].join(', ') + ')');\n  }\n}\nlines.push('', '_Counts only visits where the assistant passed a referrer. App traffic without a referrer shows up as direct._');\nreturn [{ json: { text: lines.join('\\n') } }];\n"
      }
    },
    {
      "id": "40a4e11c-a30d-4415-aed9-c6ea99867952",
      "name": "Post to Slack",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.3,
      "position": [
        1848,
        0
      ],
      "parameters": {
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "name",
          "value": "={{ $('Settings').first().json.slackChannel }}"
        },
        "text": "={{ $json.text }}",
        "otherOptions": {
          "includeLinkToWorkflow": false
        }
      }
    },
    {
      "id": "7edbd534-615a-42a5-a0ba-c9ef02e5a7e2",
      "name": "Step 1",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -186
      ],
      "parameters": {
        "content": "## Step 1: Configure\n- **ga4PropertyId**: the numeric GA4 property id.\n- **siteName**: shown in the message title.\n- **aiSourcesRegex**: GA4 `sessionSource` values that count as AI assistants (full match). Add a source with `|newsource\\.com`.",
        "width": 488,
        "height": 376,
        "color": 7
      }
    },
    {
      "id": "d1e08a7b-6cd0-454c-ae8f-c217c16b85f8",
      "name": "Step 2",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        576,
        -186
      ],
      "parameters": {
        "content": "## Step 2: Pull AI assistant sessions from GA4\nThree GA4 reports through GSC Magic: sessions from AI assistants this week, the week before, and their landing pages.",
        "width": 796,
        "height": 376,
        "color": 7
      }
    },
    {
      "id": "fefebb23-e99c-486d-accd-2f501f6db5b1",
      "name": "Step 3",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1500,
        -186
      ],
      "parameters": {
        "content": "## Step 3: Report in Slack\nGroups sources into assistants, compares the weeks and posts sessions, engagement, key events and top pages.",
        "width": 488,
        "height": 376,
        "color": 7
      }
    },
    {
      "id": "5432f21a-2798-4243-ae44-729ba3511981",
      "name": "Overview",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -740,
        -186
      ],
      "parameters": {
        "content": "## Weekly AI assistant traffic report\nSearch Console does not show clicks from ChatGPT, Perplexity, Claude, Gemini or Copilot. Google Analytics 4 does, if you know which sources to look for. Every Monday this workflow pulls those sessions from GA4, compares them with the week before and posts which assistants send visitors and which pages they land on.\n\n**Who it is for:** GEO / AEO agencies and site owners who need a number for \"are AI assistants sending us traffic?\".\n\n**How it works**\n1. Three GA4 reports through GSC Magic: AI sessions this week, the week before, and landing pages this week.\n2. Groups sources into assistants (chatgpt.com and chat.openai.com count as ChatGPT, and so on).\n3. Posts totals, change, engagement rate, key events and the top landing pages to Slack.\n\n**Requirements:** a GA4 property connected to the Google account behind GSC Magic (GSC Magic asks for Analytics read access when you connect Google).\n\n**Connect GSC Magic** (about 2 minutes)\n1. In the [GSC Magic dashboard](https://app.gscmagic.com) open **Connect > Access tokens** and create a token. Copy the `gsm_...` value (shown once).\n2. Open the first node whose name starts with **GSC Magic:**, and under **Credential for Bearer Auth** create a new credential. Paste the token into **Bearer Token**. In every other **GSC Magic:** node, select that same credential.\n3. Never paste the token into a URL, a prompt or a Code node.\n\n**Then**\n4. Put your GA4 property id in **Settings** (GA4 > Admin > Property details, a number like 123456789).\n5. Add a Slack credential to **Post to Slack**, execute once, activate.\n\nSchedule times use the workflow time zone (Workflow settings > Timezone), which defaults to the instance time zone.\n\n**Calls per run:** 3. Works on the Free plan (10 calls a day).\n\n### Errors and limits\n- If any of the three reports fails (wrong property id, no Analytics access, plan limit), Slack gets one message with the reason instead of a partial report.\n- Weeks are GA4 relative dates (`7daysAgo` to `yesterday`) in the property's time zone.\n- Mobile apps of some assistants open links without a referrer, so the real number is higher than what GA4 can attribute.",
        "width": 640,
        "height": 919
      }
    }
  ],
  "connections": {
    "Every Monday at 08:30": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Settings": {
      "main": [
        [
          {
            "node": "GSC Magic: AI sessions this week",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GSC Magic: AI sessions this week": {
      "main": [
        [
          {
            "node": "GSC Magic: AI sessions week before",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GSC Magic: AI sessions week before": {
      "main": [
        [
          {
            "node": "GSC Magic: AI landing pages",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GSC Magic: AI landing pages": {
      "main": [
        [
          {
            "node": "Build the report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build the report": {
      "main": [
        [
          {
            "node": "Post to Slack",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "active": false
}
