{
  "name": "Weekly Search Console digest for every client site in Slack (GSC Magic)",
  "nodes": [
    {
      "id": "6a319e8b-25b1-42ca-ae89-87b98be44e92",
      "name": "Every Monday at 08:00",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        0
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "weeks",
              "triggerAtDay": [
                1
              ],
              "triggerAtHour": 8
            }
          ]
        }
      }
    },
    {
      "id": "a418b32c-226c-47e3-ae72-b899abc6548e",
      "name": "Settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        308,
        0
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "e3612b3a-6946-4520-ad26-465ca5c16f12",
              "name": "onlySites",
              "value": "",
              "type": "string"
            },
            {
              "id": "7a5701a4-9027-4072-a6a0-27c2de91f6bf",
              "name": "slackChannel",
              "value": "#seo-weekly",
              "type": "string"
            },
            {
              "id": "f7eafe79-f7be-4905-a244-a2a80e29be8e",
              "name": "alertChangePct",
              "value": 20,
              "type": "number"
            },
            {
              "id": "74fa2e83-e48e-40b7-ac12-25e5cea4fcdf",
              "name": "minClicksToJudge",
              "value": 20,
              "type": "number"
            },
            {
              "id": "cf2411ae-260c-495e-ae1d-eeaa6813cef5",
              "name": "pagesPerClient",
              "value": 3,
              "type": "number"
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "25df72a2-cadc-414c-ad52-c3c59e97c909",
      "name": "GSC Magic: list properties",
      "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: 'gsc_list_sites', arguments: {} } }) }}",
        "options": {
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 300
            }
          },
          "timeout": 180000
        }
      }
    },
    {
      "id": "9a8cbf7c-665e-4dd3-a264-4ac4ecb50272",
      "name": "Pick client sites",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        924,
        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 res = unwrap($input.first().json);\nif (!res.ok) throw new Error('Could not list Search Console properties: ' + res.error);\n\nconst hostOf = (s) => String(s).trim().toLowerCase()\n  .replace(/^sc-domain:/, '').replace(/^https?:\\/\\//, '').replace(/^www\\./, '').replace(/\\/.*$/, '');\nconst wanted = String(cfg.onlySites || '').split(',').map(hostOf).filter(Boolean);\n\nconst properties = (Array.isArray(res.data) ? res.data : [])\n  .filter((p) => p.permissionLevel !== 'siteUnverifiedUser');\nconst picked = wanted.length ? properties.filter((p) => wanted.includes(hostOf(p.siteUrl))) : properties;\n\nif (!picked.length) {\n  throw new Error(wanted.length\n    ? 'None of the properties matches onlySites (' + cfg.onlySites + '). Check the spelling or leave it empty.'\n    : 'The token cannot read any Search Console property. Connect Google in the GSC Magic dashboard first.');\n}\nreturn picked.map((p) => ({ json: { site: p.siteUrl } }));\n"
      }
    },
    {
      "id": "d8b33aa3-43fc-402e-aa8e-a620f5e4eb14",
      "name": "GSC Magic: week-over-week movers",
      "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: 'report_traffic_drops', arguments: { site: $json.site, range: 'last_7_days', dimension: 'page', limit: $('Settings').first().json.pagesPerClient } } }) }}",
        "options": {
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 300
            }
          },
          "timeout": 180000
        }
      }
    },
    {
      "id": "30a98723-8187-4ff2-af2a-07392b4dbb6c",
      "name": "Label each client",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1540,
        0
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "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 site = $('Pick client sites').item.json.site;\nconst res = unwrap($json);\nif (!res.ok) return { json: { site, status: 'failed', error: res.error } };\n\nconst d = res.data;\nconst now = d.totals_current || { clicks: 0, impressions: 0 };\nconst prev = d.totals_previous || { clicks: 0, impressions: 0 };\nconst changePct = prev.clicks > 0 ? Math.round(((now.clicks - prev.clicks) / prev.clicks) * 100) : null;\n\nlet status = 'steady';\nif (prev.clicks < cfg.minClicksToJudge && now.clicks < cfg.minClicksToJudge) status = 'low';\nelse if (changePct === null) status = now.clicks > 0 ? 'up' : 'steady';\nelse if (changePct <= -cfg.alertChangePct) status = 'down';\nelse if (changePct >= cfg.alertChangePct) status = 'up';\n\nconst path = (u) => String(u).replace(/^https?:\\/\\/[^/]+/i, '') || '/';\nconst pages = (rows) => (rows || []).filter((r) => r.clicks_delta !== 0)\n  .map((r) => ({ page: path(r.key), url: r.key, delta: r.clicks_delta }));\n\nreturn { json: {\n  site, status, changePct,\n  clicksNow: now.clicks, clicksPrev: prev.clicks,\n  impressionsNow: now.impressions, impressionsPrev: prev.impressions,\n  current: d.current, previous: d.previous,\n  losers: pages(d.losers), gainers: pages(d.gainers),\n} };\n"
      }
    },
    {
      "id": "ef9e6775-66c8-4495-a741-5baec208ac43",
      "name": "Build the digest",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1848,
        0
      ],
      "parameters": {
        "jsCode": "const clients = $input.all().map((i) => i.json);\nconst order = { failed: 0, down: 1, up: 2, steady: 3, low: 4 };\nclients.sort((a, b) => order[a.status] - order[b.status] || (a.changePct ?? 0) - (b.changePct ?? 0));\n\nconst icon = { failed: ':warning:', down: ':red_circle:', up: ':large_green_circle:', steady: ':white_circle:', low: ':grey_question:' };\nconst fmt = (n) => Number(n || 0).toLocaleString('en-US');\nconst pct = (p) => (p === null || p === undefined ? 'new' : (p > 0 ? '+' : '') + p + '%');\nconst name = (site) => String(site).replace(/^sc-domain:/, '').replace(/^https?:\\/\\//, '').replace(/\\/$/, '');\nconst day = (s) => new Date(s + 'T00:00:00Z').toLocaleDateString('en-GB', { day: 'numeric', month: 'short', timeZone: 'UTC' });\n\nconst withPeriod = clients.find((c) => c.current && c.previous);\nconst period = withPeriod\n  ? day(withPeriod.current.startDate) + ' to ' + day(withPeriod.current.endDate) + ' vs ' + day(withPeriod.previous.startDate) + ' to ' + day(withPeriod.previous.endDate)\n  : 'last 7 days vs the 7 days before';\n\nconst count = (s) => clients.filter((c) => c.status === s).length;\nconst lines = [\n  '*Search Console weekly digest* (' + period + ')',\n  [count('down') && icon.down + ' ' + count('down') + ' down', count('up') && icon.up + ' ' + count('up') + ' up',\n   count('steady') && icon.steady + ' ' + count('steady') + ' steady', count('low') && icon.low + ' ' + count('low') + ' low traffic',\n   count('failed') && icon.failed + ' ' + count('failed') + ' failed'].filter(Boolean).join('   '),\n  '',\n];\n\nfor (const c of clients) {\n  if (c.status === 'failed') {\n    lines.push(icon.failed + ' *' + name(c.site) + '*: could not read data. ' + c.error);\n    continue;\n  }\n  lines.push(icon[c.status] + ' *' + name(c.site) + '*  clicks ' + fmt(c.clicksPrev) + ' > ' + fmt(c.clicksNow) + ' (' + pct(c.changePct) + ')'\n    + ', impressions ' + fmt(c.impressionsPrev) + ' > ' + fmt(c.impressionsNow));\n  if (c.status === 'down' || c.status === 'up') {\n    const lost = c.losers.filter((p) => p.delta < 0).map((p) => '<' + p.url + '|' + p.page + '> ' + p.delta).join(', ');\n    const won = c.gainers.filter((p) => p.delta > 0).map((p) => '<' + p.url + '|' + p.page + '> +' + p.delta).join(', ');\n    if (lost) lines.push('      lost: ' + lost);\n    if (won) lines.push('      gained: ' + won);\n  }\n}\nlines.push('', '_Clicks from Google Search, finalized data. Small sites swing a lot from week to week._');\nreturn [{ json: { text: lines.join('\\n'), clients: clients.length } }];\n"
      }
    },
    {
      "id": "211ece81-5899-4772-a671-9078440819eb",
      "name": "Post digest to Slack",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.3,
      "position": [
        2156,
        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,
        -333
      ],
      "parameters": {
        "content": "## Step 1: Configure\n- **onlySites**: comma-separated domains or properties to include, e.g. `acme.com, sc-domain:shop.io`. Empty = every property the token can read.\n- **slackChannel**: channel name, e.g. `#seo-weekly`.\n- **alertChangePct**: a change of this many percent or more marks a client as down or up.\n- **minClicksToJudge**: below this many clicks in the previous week the client is marked low traffic instead of down or up, because small numbers swing a lot.\n- **pagesPerClient**: how many losing and gaining pages to show per client.",
        "width": 488,
        "height": 523,
        "color": 7
      }
    },
    {
      "id": "fb5559c3-e3cc-47fb-a9c5-f544f0f3f1c5",
      "name": "Step 2",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        576,
        -333
      ],
      "parameters": {
        "content": "## Step 2: Pick the client sites\nLists every Search Console property the token can read and keeps the ones in `onlySites` (all of them when it is empty).",
        "width": 488,
        "height": 523,
        "color": 7
      }
    },
    {
      "id": "03d449e4-39bb-4010-a3fd-5eb19176b77b",
      "name": "Step 3",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1192,
        -333
      ],
      "parameters": {
        "content": "## Step 3: Compare the weeks\nOne GSC Magic call per site: the last 7 finalized days against the 7 before. Each client is labeled down, up, steady, low traffic or failed.",
        "width": 488,
        "height": 523,
        "color": 7
      }
    },
    {
      "id": "677633d8-0cf9-4db1-ac8a-5ab4250cdfac",
      "name": "Step 4",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1808,
        -333
      ],
      "parameters": {
        "content": "## Step 4: Post the digest\nSorts the clients, problems first, and posts one Slack message with the pages behind each change.",
        "width": 488,
        "height": 523,
        "color": 7
      }
    },
    {
      "id": "5cbdb61a-126b-4d19-a213-bdb8b6b9121a",
      "name": "Overview",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -740,
        -333
      ],
      "parameters": {
        "content": "## Weekly Search Console digest for every client site\nEvery Monday this workflow checks each Search Console property your GSC Magic token can read and posts **one** Slack message: which clients lost or gained clicks week over week, and the pages behind the change. Clients that need attention are listed first.\n\n**Who it is for:** SEO agencies and freelancers who look after several sites and want Monday's triage done before the first coffee.\n\n**How it works**\n1. Lists your Search Console properties and keeps the ones in `onlySites` (or all of them).\n2. For each site, compares the last 7 days of finalized data with the 7 days before.\n3. Labels each client: down, up, steady, too little traffic to judge, or failed.\n4. Posts one digest to Slack.\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. Fill in the **Settings** node.\n5. Add a Slack credential to **Post digest to Slack** and invite the bot to the channel.\n6. Click **Execute workflow**, check the message, then activate.\n\nSchedule times use the workflow time zone (Workflow settings > Timezone), which defaults to the instance time zone.\n\n**Calls per run:** 1 + one per site. The Free plan has 1 site and 10 calls a day; a multi-client digest needs Pro (10 sites) or Agency (25 sites).\n\n### Errors and limits\n- A wrong or revoked token, or no readable property, stops the run in **Pick client sites** with a clear message (set an n8n error workflow to be told).\n- A failure for one site (plan limit, Google error) does not stop the others: the site is listed as *failed* with the reason.\n- Search Console data arrives 2 to 3 days late. GSC Magic ends both weeks on the latest finalized day, so the weeks compare like for like.",
        "width": 640,
        "height": 867
      }
    }
  ],
  "connections": {
    "Every Monday at 08:00": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Settings": {
      "main": [
        [
          {
            "node": "GSC Magic: list properties",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GSC Magic: list properties": {
      "main": [
        [
          {
            "node": "Pick client sites",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pick client sites": {
      "main": [
        [
          {
            "node": "GSC Magic: week-over-week movers",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GSC Magic: week-over-week movers": {
      "main": [
        [
          {
            "node": "Label each client",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Label each client": {
      "main": [
        [
          {
            "node": "Build the digest",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build the digest": {
      "main": [
        [
          {
            "node": "Post digest to Slack",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "active": false
}
