@xevrion/gsc-mcp 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +219 -2
- package/dist/analysis.js +405 -0
- package/dist/auth.js +388 -0
- package/dist/dates.js +64 -0
- package/dist/demo.js +330 -0
- package/dist/format.js +55 -0
- package/dist/gsc.js +342 -0
- package/dist/http.js +60 -0
- package/dist/index.js +184 -0
- package/dist/install.js +128 -0
- package/dist/prompts.js +16 -0
- package/dist/server.js +26 -0
- package/dist/tools.js +971 -0
- package/dist/updates.js +17 -0
- package/package.json +54 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 xevrion
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,220 @@
|
|
|
1
|
-
#
|
|
1
|
+
# gsc-mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Google Search Console for Claude, Cursor, and every other AI app. Free, open source, runs on your machine.**
|
|
4
|
+
|
|
5
|
+
Ask your AI "why did my traffic drop?" and get an actual answer: the day it broke, whether it lines up with a Google update, and which pages lost clicks because they ranked worse, got clicked less, or because fewer people searched.
|
|
6
|
+
|
|
7
|
+
[](https://www.npmjs.com/package/@xevrion/gsc-mcp)
|
|
8
|
+
[](https://github.com/xevrion/gsc-mcp/actions/workflows/ci.yml)
|
|
9
|
+
[](LICENSE)
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npx -y @xevrion/gsc-mcp setup
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
That's the whole install. It signs you in with Google, finds the AI apps on your computer (Claude Code, Claude Desktop, Cursor, Windsurf, VS Code, Gemini CLI, Codex) and adds itself to each one.
|
|
16
|
+
|
|
17
|
+
**Just want to look first?** `npx -y @xevrion/gsc-mcp demo` adds it with a realistic made-up site, no Google account needed. Every tool works on it.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## What you can ask
|
|
22
|
+
|
|
23
|
+
> How is my site doing on Google this month?
|
|
24
|
+
>
|
|
25
|
+
> Why did my traffic drop in September?
|
|
26
|
+
>
|
|
27
|
+
> Which keywords am I close to page one for, and what should I change?
|
|
28
|
+
>
|
|
29
|
+
> Are any of my pages competing with each other?
|
|
30
|
+
>
|
|
31
|
+
> Which pages in my sitemap is Google ignoring, and why?
|
|
32
|
+
>
|
|
33
|
+
> Did the November core update hurt me?
|
|
34
|
+
>
|
|
35
|
+
> Is my blog section growing or shrinking?
|
|
36
|
+
|
|
37
|
+
Here's a real answer from the demo site:
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
diagnose_traffic_drop · sc-domain:brewguide.coffee · 2026-08-28 to 2026-11-25
|
|
41
|
+
Clicks 23,783 vs 26,506 (-10.3%, -2,723).
|
|
42
|
+
|
|
43
|
+
Trend break: around 2026-08-08, daily clicks went from ~302 to ~265.
|
|
44
|
+
Matches a Google update: August 2026 spam update (2026-08-18 to 2026-08-21).
|
|
45
|
+
|
|
46
|
+
| cause | clicks Δ |
|
|
47
|
+
| CTR drops at similar rank | -2,752 |
|
|
48
|
+
| Ranking drops | -16 |
|
|
49
|
+
| Lower search demand | +45 |
|
|
50
|
+
|
|
51
|
+
| page | clicks Δ | cause | detail |
|
|
52
|
+
| /blog/french-press-ratio | -2,752 | ctr | CTR 17.0% → 12.3% at a similar position |
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
A drop in CTR at the same ranking usually means a new AI Overview or a weaker title. The tool tells you which one you're dealing with, so you fix the right thing.
|
|
56
|
+
|
|
57
|
+
## Why this one
|
|
58
|
+
|
|
59
|
+
Lots of Search Console MCP servers exist. Most of them pass Google's raw JSON to the model and stop there. This one does the analysis too, and it was built after going through the issue trackers of the popular ones to see what people kept running into.
|
|
60
|
+
|
|
61
|
+
- **Setup a non-developer can finish.** One command does everything, including adding itself to your apps. It opens each Google page for you and picks up the downloaded key on its own. If something isn't connected, your AI can start the sign-in from the chat.
|
|
62
|
+
- **Answers, not data dumps.** 21 tools, and most of them answer a question directly: drop diagnosis, quick wins, weak titles, cannibalization, content decay, indexing audits, update impact.
|
|
63
|
+
- **Benchmarks from your own site.** "Expected CTR" comes from your own data, not an industry table. A site that normally gets 0.6× typical CTR won't have every page flagged, and a strong brand won't hide its weak pages.
|
|
64
|
+
- **Cheap on tokens.** Output is compact tables with shared URL prefixes folded into the header, about 2.6× smaller than the raw JSON most servers return (8.6k vs 22k characters for the same 100 rows). All 21 tools together cost about 5k tokens of context, and `GSC_TOOLS` trims them further. Results always say when they were cut off.
|
|
65
|
+
- **Fast.** Starts in about 0.4 s. Requests run in parallel, and repeated queries come from a 10-minute cache, so a full SEO report mostly reuses data it already fetched.
|
|
66
|
+
- **Right about your property.** `example.com`, `https://www.example.com/blog/post` and `sc-domain:example.com` all resolve to the right property, every time. It never picks `myexample.com`, and it asks when it can't tell.
|
|
67
|
+
- **The 2026 API.** Hourly data, Google's branded query classification, `webMultimodal` (Lens and Circle to Search), and multi-value country and device filters.
|
|
68
|
+
- **Safe by default.** It's read-only unless you opt in. There's no telemetry, it never talks to a server of ours, and tokens are stored with 0600 permissions.
|
|
69
|
+
- **Tested.** 163 tests, plus runs against real Search Console accounts. They cover pagination boundaries (exactly 25,000 rows), timezone edges, retries, multi-account routing and installer edge cases. CI runs on Linux, macOS and Windows.
|
|
70
|
+
|
|
71
|
+
## Tools
|
|
72
|
+
|
|
73
|
+
| Tool | What it answers |
|
|
74
|
+
| --- | --- |
|
|
75
|
+
| `site_overview` | How is the site doing: totals against the previous period and last year, top queries and pages with changes, devices, countries, data freshness, share of clicks from hidden queries |
|
|
76
|
+
| `diagnose_traffic_drop` | Why traffic changed: the trend-break day, matching Google updates, and each loss split into lost / ranking / CTR / demand |
|
|
77
|
+
| `update_impact` | How every confirmed Google update in the last 16 months affected the site |
|
|
78
|
+
| `find_anomalies` | Days that broke from the normal weekly pattern (outages, spikes, tracking gaps) |
|
|
79
|
+
| `compare_periods` | Biggest winners and losers by query, page, country, device |
|
|
80
|
+
| `find_opportunities` | Striking-distance keywords ranked by extra clicks they could get |
|
|
81
|
+
| `find_low_ctr` | Pages that rank fine but don't get clicked (title and description fixes) |
|
|
82
|
+
| `find_cannibalization` | Queries split across several of your pages, with daily evidence of Google swapping between them |
|
|
83
|
+
| `find_content_decay` | Pages in steady decline over months, with the likely cause |
|
|
84
|
+
| `analyze_queries` | Search intent breakdown, long AI-style questions, and topic clusters |
|
|
85
|
+
| `brand_split` | Branded vs non-branded traffic |
|
|
86
|
+
| `section_report` | Performance by folder (/blog/, /products/, ...) |
|
|
87
|
+
| `page_report` | Everything about one URL: queries, trend, devices, index status |
|
|
88
|
+
| `all_sites_overview` | Every property side by side |
|
|
89
|
+
| `search_analytics` | Raw data with any dimensions and filters, auto-paginated past 25k rows; table, JSON or CSV |
|
|
90
|
+
| `audit_indexing` | Sitemap URLs with zero impressions, inspected to show why |
|
|
91
|
+
| `inspect_url` | Index status for up to 100 URLs: coverage, canonical, robots, rich result issues |
|
|
92
|
+
| `page_speed` | Core Web Vitals from real users plus Lighthouse, with the biggest fixes |
|
|
93
|
+
| `list_sitemaps`, `list_sites` | What's submitted and what you can access |
|
|
94
|
+
| `connect_account` | Sign in from inside the chat |
|
|
95
|
+
|
|
96
|
+
Turn on `GSC_ALLOW_WRITES=1` for `submit_sitemap`, `delete_sitemap`, `add_site`, `delete_site` and `request_indexing`.
|
|
97
|
+
|
|
98
|
+
It also ships five prompts your app can show as shortcuts: **SEO report**, **Why did my traffic drop?**, **Quick wins**, **Indexing check**, **Content refresh plan**.
|
|
99
|
+
|
|
100
|
+
## Authentication
|
|
101
|
+
|
|
102
|
+
### The easy way
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
npx -y @xevrion/gsc-mcp setup
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Google requires each person to have a free "OAuth client", which is a key that lets an app ask for your permission. It lives in a Google Cloud project. That sounds heavy, but it's free and needs no billing or card, and your data still goes straight from Google to your computer. Setup opens each page for you:
|
|
109
|
+
|
|
110
|
+
1. [Create a project](https://console.cloud.google.com/projectcreate) (any name)
|
|
111
|
+
2. [Turn on the Search Console API](https://console.cloud.google.com/apis/library/searchconsole.googleapis.com)
|
|
112
|
+
3. [Get started](https://console.cloud.google.com/auth/overview/create): app name, your email, audience **External**, agree, Create
|
|
113
|
+
4. [Branding](https://console.cloud.google.com/auth/branding): Google won't publish the app without a home page and privacy policy, so you can use this project's: home page `https://github.com/xevrion/gsc-mcp`, privacy policy `https://github.com/xevrion/gsc-mcp/blob/main/PRIVACY.md`, authorised domain `github.com`. Save.
|
|
114
|
+
5. [Audience](https://console.cloud.google.com/auth/audience): click **Publish app**. If you skip this, Google signs you out every 7 days.
|
|
115
|
+
6. [Create a client](https://console.cloud.google.com/auth/clients/create): type **Desktop app**, then **Download JSON**
|
|
116
|
+
|
|
117
|
+
Setup notices the file in your Downloads folder and opens Google sign-in. (On macOS your terminal may ask for permission to read Downloads. If you say no, setup lets you paste the file path instead.) Google may warn that the app is unverified. That's expected, because it's your own app: click **Advanced**, then **Go to ... (unsafe)**.
|
|
118
|
+
|
|
119
|
+
A one-click "Sign in with Google" that skips all of this is on the roadmap. It needs a shared app verified by Google, which is in progress.
|
|
120
|
+
|
|
121
|
+
### Several Google accounts
|
|
122
|
+
|
|
123
|
+
```bash
|
|
124
|
+
npx -y @xevrion/gsc-mcp auth --profile client-a
|
|
125
|
+
npx -y @xevrion/gsc-mcp auth --profile client-b
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
Every saved account is used at once, and each property goes through whichever account can see it. Agencies just name the site. Set `GSC_PROFILE` to pin a single account.
|
|
129
|
+
|
|
130
|
+
### Service account
|
|
131
|
+
|
|
132
|
+
For servers and CI: set `GSC_SERVICE_ACCOUNT` to the key file path or the JSON itself. Then add the service account's email as a user on each property (Search Console › Settings › Users and permissions).
|
|
133
|
+
|
|
134
|
+
### Application Default Credentials
|
|
135
|
+
|
|
136
|
+
`gcloud auth application-default login --client-id-file=client.json --scopes=https://www.googleapis.com/auth/webmasters.readonly` works too. Google blocks gcloud's built-in client for this scope, so the client file is required.
|
|
137
|
+
|
|
138
|
+
## Manual setup
|
|
139
|
+
|
|
140
|
+
If `setup` didn't find your app, add this to its MCP config:
|
|
141
|
+
|
|
142
|
+
```json
|
|
143
|
+
{
|
|
144
|
+
"mcpServers": {
|
|
145
|
+
"search-console": {
|
|
146
|
+
"command": "npx",
|
|
147
|
+
"args": ["-y", "@xevrion/gsc-mcp"]
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
- **Claude Code**: `claude mcp add --scope user search-console -- npx -y @xevrion/gsc-mcp`. It's also a plugin: `/plugin marketplace add xevrion/gsc-mcp`, then `/plugin install search-console@gsc-mcp`. The plugin bundles a skill that teaches Claude which tool to use when.
|
|
154
|
+
- **Claude Desktop**: download `gsc-mcp.mcpb` from the [latest release](https://github.com/xevrion/gsc-mcp/releases) and double-click it.
|
|
155
|
+
- **VS Code**: uses `"servers"` instead of `"mcpServers"` and needs `"type": "stdio"`.
|
|
156
|
+
- **Codex**: `~/.codex/config.toml` → `[mcp_servers.search-console]` with `command = "npx"` and `args = ["-y", "@xevrion/gsc-mcp"]`.
|
|
157
|
+
|
|
158
|
+
## Configuration
|
|
159
|
+
|
|
160
|
+
| Variable | What it does |
|
|
161
|
+
| --- | --- |
|
|
162
|
+
| `GSC_DEFAULT_SITE` | Property to use when a request doesn't name one |
|
|
163
|
+
| `GSC_ALLOWED_SITES` | Comma-separated list; the AI can only see these properties |
|
|
164
|
+
| `GSC_TOOLS` | Load only some tools, to save tokens: families `core`, `insights`, `indexing`, `write`, or tool names |
|
|
165
|
+
| `GSC_ALLOW_WRITES=1` | Enable tools that change things |
|
|
166
|
+
| `GSC_PROFILE` | Use one saved account instead of all of them |
|
|
167
|
+
| `GSC_SERVICE_ACCOUNT` | Service account key path or JSON |
|
|
168
|
+
| `GOOGLE_API_KEY` | Optional key for `page_speed` when the shared PageSpeed quota runs out |
|
|
169
|
+
| `GSC_DEMO=1` | Synthetic demo data |
|
|
170
|
+
|
|
171
|
+
## Command line
|
|
172
|
+
|
|
173
|
+
Every tool also runs from a terminal, which is handy for scripts and cron:
|
|
174
|
+
|
|
175
|
+
```bash
|
|
176
|
+
npx -y @xevrion/gsc-mcp tools
|
|
177
|
+
npx -y @xevrion/gsc-mcp run find_opportunities --site example.com --brand "acme" --limit 10
|
|
178
|
+
npx -y @xevrion/gsc-mcp run search_analytics --site example.com --dimensions date --format csv > clicks.csv
|
|
179
|
+
npx -y @xevrion/gsc-mcp status # checks credentials, properties, and which apps have it
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
## Remote / Docker
|
|
183
|
+
|
|
184
|
+
```bash
|
|
185
|
+
GSC_HTTP_TOKEN=$(openssl rand -hex 32) npx -y @xevrion/gsc-mcp serve --http --port 3000
|
|
186
|
+
docker build -t gsc-mcp . && docker run -p 3000:3000 -e GSC_HTTP_TOKEN=... -e GSC_SERVICE_ACCOUNT="$(cat key.json)" gsc-mcp
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
Streamable HTTP lives at `/mcp`, and `/health` is for load balancers. It won't listen on a public interface without a token.
|
|
190
|
+
|
|
191
|
+
## How the analysis works
|
|
192
|
+
|
|
193
|
+
Nothing hidden, so you can judge whether to trust it.
|
|
194
|
+
|
|
195
|
+
- **Expected CTR**: a CTR-by-position curve fitted to your own query rows. It starts from a site-wide factor (the median of each query's CTR over a standard curve), and each position's median is blended in according to how much data backs it. Outliers can't drag down their own benchmark, and small sites still get sensible numbers.
|
|
196
|
+
- **Opportunities**: impressions × expected CTR at the target position, minus the clicks you already get.
|
|
197
|
+
- **Drop attribution**: each page or query is checked in order. It either disappeared, lost at least 1 position (0.5 inside the top 3), lost 25%+ CTR at a steady position with steady impressions, or simply had less search demand.
|
|
198
|
+
- **Trend break**: the split point that maximizes the weighted difference in mean daily clicks. Google updates come from the public [Search Status Dashboard](https://status.search.google.com/).
|
|
199
|
+
- **Decay**: a least-squares line over consecutive 28-day periods. A page is flagged only when the fit is solid (R² ≥ 0.5) and the late half averages at least 25% below the early half, so one bad month never counts.
|
|
200
|
+
- **Cannibalization**: queries where 2+ pages each hold 10%+ of impressions, scored with 1 − HHI and ranked by impressions at stake. The worst five also get a day-by-day check of how often Google swapped the top page.
|
|
201
|
+
- **Anomalies**: each day compared with the same weekday over the previous four weeks, so weekends aren't flagged as outages.
|
|
202
|
+
- **Topics**: queries grouped by their most distinctive shared word (√impressions × IDF).
|
|
203
|
+
|
|
204
|
+
Search Console only reports top rows and hides rare queries. `site_overview` tells you what share of clicks that is, so you know how much of the picture you're seeing.
|
|
205
|
+
|
|
206
|
+
## Development
|
|
207
|
+
|
|
208
|
+
```bash
|
|
209
|
+
npm install
|
|
210
|
+
npm test # 163 tests, no Google account needed
|
|
211
|
+
npm run build
|
|
212
|
+
npm run smoke # real stdio server, demo data, every tool
|
|
213
|
+
npm run inspect # MCP Inspector
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md). Issues and ideas are welcome, especially "I wish I could ask it X".
|
|
217
|
+
|
|
218
|
+
## License
|
|
219
|
+
|
|
220
|
+
MIT
|
package/dist/analysis.js
ADDED
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
// Rough organic CTR by position, used only where a site has too little data of
|
|
2
|
+
// its own at that position to trust.
|
|
3
|
+
const FALLBACK_CTR = [0, 0.28, 0.155, 0.1, 0.07, 0.053, 0.04, 0.032, 0.026, 0.021, 0.018];
|
|
4
|
+
const MIN_ROW_IMPRESSIONS = 20;
|
|
5
|
+
const PRIOR_WEIGHT = 20;
|
|
6
|
+
export function fallbackCtr(position) {
|
|
7
|
+
const p = Math.max(1, Math.round(position));
|
|
8
|
+
if (p < FALLBACK_CTR.length)
|
|
9
|
+
return FALLBACK_CTR[p];
|
|
10
|
+
return Math.max(0.002, FALLBACK_CTR[10] * Math.pow(0.8, p - 10));
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Builds a CTR-by-position curve from the site's own query rows, so "expected
|
|
14
|
+
* CTR" reflects this site's SERP features and brand strength rather than an
|
|
15
|
+
* industry table.
|
|
16
|
+
*
|
|
17
|
+
* Two layers keep it robust on small sites, where a handful of weak rows can be
|
|
18
|
+
* most of a position bucket: a site-wide factor (median of each row's CTR over
|
|
19
|
+
* the industry curve) sets the prior, and each bucket's median is blended with
|
|
20
|
+
* that prior in proportion to how many rows back it.
|
|
21
|
+
*/
|
|
22
|
+
export function buildCtrCurve(rows) {
|
|
23
|
+
const usable = rows.filter((r) => r.impressions >= MIN_ROW_IMPRESSIONS && r.position >= 1 && r.position <= 20);
|
|
24
|
+
const siteFactor = usable.length >= 10 ? clamp(median(usable.map((r) => r.ctr / fallbackCtr(r.position))), 0.25, 3) : 1;
|
|
25
|
+
const buckets = new Map();
|
|
26
|
+
for (const r of usable) {
|
|
27
|
+
const p = Math.round(r.position);
|
|
28
|
+
const b = buckets.get(p) ?? [];
|
|
29
|
+
b.push(r.ctr);
|
|
30
|
+
buckets.set(p, b);
|
|
31
|
+
}
|
|
32
|
+
const table = new Map();
|
|
33
|
+
for (let p = 1; p <= 20; p++) {
|
|
34
|
+
const prior = fallbackCtr(p) * siteFactor;
|
|
35
|
+
const b = buckets.get(p);
|
|
36
|
+
const n = b?.length ?? 0;
|
|
37
|
+
table.set(p, n ? (n * median(b) + PRIOR_WEIGHT * prior) / (n + PRIOR_WEIGHT) : prior);
|
|
38
|
+
}
|
|
39
|
+
// A real curve never rises with position; clamp noisy buckets to keep it sane.
|
|
40
|
+
for (let p = 2; p <= 20; p++)
|
|
41
|
+
table.set(p, Math.min(table.get(p), table.get(p - 1)));
|
|
42
|
+
return {
|
|
43
|
+
curve: (position) => {
|
|
44
|
+
const p = Math.max(1, Math.round(position));
|
|
45
|
+
return p <= 20 ? table.get(p) : fallbackCtr(p) * siteFactor;
|
|
46
|
+
},
|
|
47
|
+
siteFactor,
|
|
48
|
+
personalized: [...buckets.entries()].filter(([, b]) => b.length >= PRIOR_WEIGHT).map(([p]) => p).sort((a, b) => a - b),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function clamp(x, lo, hi) {
|
|
52
|
+
return Math.min(hi, Math.max(lo, x));
|
|
53
|
+
}
|
|
54
|
+
function median(xs) {
|
|
55
|
+
const s = [...xs].sort((a, b) => a - b);
|
|
56
|
+
const m = s.length >> 1;
|
|
57
|
+
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
|
58
|
+
}
|
|
59
|
+
export function strikingDistance(rows, curve, opts) {
|
|
60
|
+
const targetCtr = curve(opts.targetPosition);
|
|
61
|
+
return rows
|
|
62
|
+
.filter((r) => r.position >= opts.minPosition && r.position <= opts.maxPosition && r.impressions >= opts.minImpressions)
|
|
63
|
+
.map((r) => ({
|
|
64
|
+
key: r.keys[0],
|
|
65
|
+
clicks: r.clicks,
|
|
66
|
+
impressions: r.impressions,
|
|
67
|
+
ctr: r.ctr,
|
|
68
|
+
position: r.position,
|
|
69
|
+
potentialClicks: Math.max(0, Math.round(r.impressions * targetCtr - r.clicks)),
|
|
70
|
+
}))
|
|
71
|
+
.sort((a, b) => b.potentialClicks - a.potentialClicks);
|
|
72
|
+
}
|
|
73
|
+
export function lowCtr(rows, curve, opts) {
|
|
74
|
+
return rows
|
|
75
|
+
.filter((r) => r.position <= opts.maxPosition && r.impressions >= opts.minImpressions)
|
|
76
|
+
.map((r) => {
|
|
77
|
+
const expectedCtr = curve(r.position);
|
|
78
|
+
return {
|
|
79
|
+
key: r.keys[0],
|
|
80
|
+
clicks: r.clicks,
|
|
81
|
+
impressions: r.impressions,
|
|
82
|
+
ctr: r.ctr,
|
|
83
|
+
position: r.position,
|
|
84
|
+
expectedCtr,
|
|
85
|
+
potentialClicks: Math.max(0, Math.round(r.impressions * expectedCtr - r.clicks)),
|
|
86
|
+
};
|
|
87
|
+
})
|
|
88
|
+
.filter((r) => r.ctr < r.expectedCtr * opts.threshold)
|
|
89
|
+
.sort((a, b) => b.potentialClicks - a.potentialClicks);
|
|
90
|
+
}
|
|
91
|
+
/** Expects rows with keys [query, page]. */
|
|
92
|
+
export function cannibalization(rows, opts) {
|
|
93
|
+
const byQuery = new Map();
|
|
94
|
+
for (const r of rows) {
|
|
95
|
+
const list = byQuery.get(r.keys[0]) ?? [];
|
|
96
|
+
list.push(r);
|
|
97
|
+
byQuery.set(r.keys[0], list);
|
|
98
|
+
}
|
|
99
|
+
const groups = [];
|
|
100
|
+
for (const [query, list] of byQuery) {
|
|
101
|
+
// site: and inurl: searches are the owner poking at their own site, not demand.
|
|
102
|
+
if (/^(site|inurl|intitle|cache|related):/i.test(query))
|
|
103
|
+
continue;
|
|
104
|
+
const impressions = sum(list, "impressions");
|
|
105
|
+
if (impressions < opts.minImpressions)
|
|
106
|
+
continue;
|
|
107
|
+
const pages = list
|
|
108
|
+
.map((r) => ({ page: r.keys[1], clicks: r.clicks, impressions: r.impressions, position: r.position, share: r.impressions / impressions }))
|
|
109
|
+
.filter((p) => p.share >= opts.minShare)
|
|
110
|
+
.sort((a, b) => b.impressions - a.impressions);
|
|
111
|
+
if (pages.length < 2)
|
|
112
|
+
continue;
|
|
113
|
+
const conflict = 1 - pages.reduce((a, p) => a + p.share * p.share, 0);
|
|
114
|
+
groups.push({ query, impressions, clicks: sum(list, "clicks"), topShare: pages[0].share, conflict, pages });
|
|
115
|
+
}
|
|
116
|
+
return groups.sort((a, b) => b.impressions * b.conflict - a.impressions * a.conflict);
|
|
117
|
+
}
|
|
118
|
+
export function compareRows(current, previous) {
|
|
119
|
+
const prev = new Map(previous.map((r) => [r.keys.join(" | "), r]));
|
|
120
|
+
const cur = new Map(current.map((r) => [r.keys.join(" | "), r]));
|
|
121
|
+
const keys = new Set([...cur.keys(), ...prev.keys()]);
|
|
122
|
+
const out = [];
|
|
123
|
+
for (const key of keys) {
|
|
124
|
+
const c = cur.get(key);
|
|
125
|
+
const p = prev.get(key);
|
|
126
|
+
const clicks = c?.clicks ?? 0;
|
|
127
|
+
const prevClicks = p?.clicks ?? 0;
|
|
128
|
+
out.push({
|
|
129
|
+
key,
|
|
130
|
+
clicks,
|
|
131
|
+
prevClicks,
|
|
132
|
+
clicksDelta: clicks - prevClicks,
|
|
133
|
+
clicksPct: prevClicks ? (clicks - prevClicks) / prevClicks : null,
|
|
134
|
+
impressions: c?.impressions ?? 0,
|
|
135
|
+
prevImpressions: p?.impressions ?? 0,
|
|
136
|
+
position: c?.position ?? 0,
|
|
137
|
+
prevPosition: p?.position ?? 0,
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
return out;
|
|
141
|
+
}
|
|
142
|
+
function sum(rows, k) {
|
|
143
|
+
return rows.reduce((a, r) => a + r[k], 0);
|
|
144
|
+
}
|
|
145
|
+
export function linearFit(ys) {
|
|
146
|
+
const n = ys.length;
|
|
147
|
+
if (n < 2)
|
|
148
|
+
return { slope: 0, intercept: ys[0] ?? 0, r2: 0 };
|
|
149
|
+
const mx = (n - 1) / 2;
|
|
150
|
+
const my = ys.reduce((a, b) => a + b, 0) / n;
|
|
151
|
+
let sxy = 0;
|
|
152
|
+
let sxx = 0;
|
|
153
|
+
let syy = 0;
|
|
154
|
+
ys.forEach((y, x) => {
|
|
155
|
+
sxy += (x - mx) * (y - my);
|
|
156
|
+
sxx += (x - mx) ** 2;
|
|
157
|
+
syy += (y - my) ** 2;
|
|
158
|
+
});
|
|
159
|
+
const slope = sxx ? sxy / sxx : 0;
|
|
160
|
+
return { slope, intercept: my - slope * mx, r2: syy ? (sxy * sxy) / (sxx * syy) : 0 };
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Pages whose clicks trend down across consecutive periods. A least-squares fit
|
|
164
|
+
* with a confidence floor separates real decline from one noisy month.
|
|
165
|
+
*/
|
|
166
|
+
export function contentDecay(periods, opts) {
|
|
167
|
+
const keys = new Set(periods.flatMap((p) => p.map((r) => r.keys[0])));
|
|
168
|
+
const maps = periods.map((p) => new Map(p.map((r) => [r.keys[0], r])));
|
|
169
|
+
const out = [];
|
|
170
|
+
for (const key of keys) {
|
|
171
|
+
const rows = maps.map((m) => m.get(key));
|
|
172
|
+
const series = rows.map((r) => r?.clicks ?? 0);
|
|
173
|
+
const half = Math.max(1, Math.floor(series.length / 2));
|
|
174
|
+
const early = avg(series.slice(0, half));
|
|
175
|
+
const late = avg(series.slice(-half));
|
|
176
|
+
if (early < opts.minClicks)
|
|
177
|
+
continue;
|
|
178
|
+
const change = (late - early) / early;
|
|
179
|
+
if (change > -opts.minDecline)
|
|
180
|
+
continue;
|
|
181
|
+
const fit = linearFit(series);
|
|
182
|
+
if (fit.slope >= 0 || fit.r2 < opts.minR2)
|
|
183
|
+
continue;
|
|
184
|
+
const first = rows.find(Boolean);
|
|
185
|
+
const last = [...rows].reverse().find(Boolean);
|
|
186
|
+
const positionChange = last ? last.position - first.position : 0;
|
|
187
|
+
const ctrChange = last && first.ctr ? (last.ctr - first.ctr) / first.ctr : 0;
|
|
188
|
+
const imprChange = last && first.impressions ? (last.impressions - first.impressions) / first.impressions : -1;
|
|
189
|
+
const cause = positionChange > 1.5 ? "ranking" : ctrChange < -0.25 && imprChange > -0.15 ? "ctr" : "demand";
|
|
190
|
+
out.push({ key, series, peak: Math.max(...series), latest: series[series.length - 1], change, r2: fit.r2, positionChange, cause });
|
|
191
|
+
}
|
|
192
|
+
return out.sort((a, b) => (b.peak - b.latest) - (a.peak - a.latest));
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Splits each row's click change into the most likely cause: it vanished,
|
|
196
|
+
* it ranks worse, it ranks the same but gets clicked less, or fewer people search.
|
|
197
|
+
*/
|
|
198
|
+
export function attributeChanges(current, previous) {
|
|
199
|
+
const cur = new Map(current.map((r) => [r.keys.join(" | "), r]));
|
|
200
|
+
const out = [];
|
|
201
|
+
for (const p of previous) {
|
|
202
|
+
const key = p.keys.join(" | ");
|
|
203
|
+
const c = cur.get(key);
|
|
204
|
+
cur.delete(key);
|
|
205
|
+
if (!c) {
|
|
206
|
+
out.push({ key, clicksDelta: -p.clicks, reason: "lost", detail: `no impressions any more (was pos ${p.position.toFixed(1)})` });
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
const delta = c.clicks - p.clicks;
|
|
210
|
+
const posDiff = c.position - p.position;
|
|
211
|
+
const ctrRatio = p.ctr ? c.ctr / p.ctr : 1;
|
|
212
|
+
const imprRatio = p.impressions ? c.impressions / p.impressions : 1;
|
|
213
|
+
let reason;
|
|
214
|
+
if (posDiff >= 1 || (p.position <= 3 && posDiff >= 0.5))
|
|
215
|
+
reason = "ranking";
|
|
216
|
+
else if (ctrRatio < 0.75 && imprRatio > 0.8)
|
|
217
|
+
reason = "ctr";
|
|
218
|
+
else
|
|
219
|
+
reason = "demand";
|
|
220
|
+
const detail = reason === "ranking"
|
|
221
|
+
? `position ${p.position.toFixed(1)} → ${c.position.toFixed(1)}`
|
|
222
|
+
: reason === "ctr"
|
|
223
|
+
? `CTR ${(p.ctr * 100).toFixed(1)}% → ${(c.ctr * 100).toFixed(1)}% at a similar position`
|
|
224
|
+
: `impressions ${Math.round(p.impressions)} → ${Math.round(c.impressions)}`;
|
|
225
|
+
out.push({ key, clicksDelta: delta, reason, detail });
|
|
226
|
+
}
|
|
227
|
+
for (const [key, c] of cur)
|
|
228
|
+
out.push({ key, clicksDelta: c.clicks, reason: "new", detail: `new, pos ${c.position.toFixed(1)}` });
|
|
229
|
+
return out;
|
|
230
|
+
}
|
|
231
|
+
/** Finds the single day where the mean of a daily series shifts the most. */
|
|
232
|
+
export function changePoint(series) {
|
|
233
|
+
if (series.length < 14)
|
|
234
|
+
return null;
|
|
235
|
+
let best = null;
|
|
236
|
+
const total = series.reduce((a, s) => a + s.value, 0);
|
|
237
|
+
let left = 0;
|
|
238
|
+
for (let i = 7; i <= series.length - 7; i++) {
|
|
239
|
+
left = series.slice(0, i).reduce((a, s) => a + s.value, 0);
|
|
240
|
+
const mBefore = left / i;
|
|
241
|
+
const mAfter = (total - left) / (series.length - i);
|
|
242
|
+
const score = Math.abs(mAfter - mBefore) * Math.sqrt((i * (series.length - i)) / series.length);
|
|
243
|
+
if (!best || score > best.score)
|
|
244
|
+
best = { idx: i, score };
|
|
245
|
+
}
|
|
246
|
+
if (!best)
|
|
247
|
+
return null;
|
|
248
|
+
const before = avg(series.slice(0, best.idx).map((s) => s.value));
|
|
249
|
+
const after = avg(series.slice(best.idx).map((s) => s.value));
|
|
250
|
+
if (Math.abs(after - before) / Math.max(1, before) < 0.1)
|
|
251
|
+
return null;
|
|
252
|
+
return { date: series[best.idx].date, before, after };
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Groups page rows into site sections by the first N path segments. Pass
|
|
256
|
+
* withHost for domain properties that span subdomains, so docs.example.com/
|
|
257
|
+
* and example.com/ stay apart.
|
|
258
|
+
*/
|
|
259
|
+
export function sectionOf(url, depth, withHost = false) {
|
|
260
|
+
try {
|
|
261
|
+
const u = new URL(url);
|
|
262
|
+
const host = withHost ? u.hostname.replace(/^www\./, "") : "";
|
|
263
|
+
const parts = u.pathname.split("/").filter(Boolean);
|
|
264
|
+
if (!parts.length)
|
|
265
|
+
return `${host}/ (home)`;
|
|
266
|
+
const dirs = parts.length > depth || u.pathname.endsWith("/") ? parts.slice(0, depth) : parts.slice(0, Math.max(0, Math.min(depth, parts.length - 1)));
|
|
267
|
+
return dirs.length ? `${host}/${dirs.join("/")}/` : `${host}/ (top-level pages)`;
|
|
268
|
+
}
|
|
269
|
+
catch {
|
|
270
|
+
return url;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
export function rollup(rows, keyFn) {
|
|
274
|
+
const m = new Map();
|
|
275
|
+
for (const r of rows) {
|
|
276
|
+
const k = keyFn(r);
|
|
277
|
+
const g = m.get(k) ?? { clicks: 0, impressions: 0, posSum: 0, n: 0 };
|
|
278
|
+
g.clicks += r.clicks;
|
|
279
|
+
g.impressions += r.impressions;
|
|
280
|
+
g.posSum += r.position * r.impressions;
|
|
281
|
+
g.n++;
|
|
282
|
+
m.set(k, g);
|
|
283
|
+
}
|
|
284
|
+
return [...m.entries()]
|
|
285
|
+
.map(([k, g]) => ({ keys: [k, String(g.n)], clicks: g.clicks, impressions: g.impressions, ctr: g.impressions ? g.clicks / g.impressions : 0, position: g.impressions ? g.posSum / g.impressions : 0 }))
|
|
286
|
+
.sort((a, b) => b.clicks - a.clicks);
|
|
287
|
+
}
|
|
288
|
+
function avg(xs) {
|
|
289
|
+
return xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : 0;
|
|
290
|
+
}
|
|
291
|
+
const QUESTION = /^(who|what|whats|what's|why|how|when|where|which|can|could|does|do|did|is|are|was|should|will|would)\b|\?$/i;
|
|
292
|
+
const COMPARISON = /\b(vs\.?|versus|or|compared? to|comparison|difference between|alternative(s)? to|better than)\b/i;
|
|
293
|
+
const COMMERCIAL = /\b(best|top \d*|review(s)?|rated|cheap(est)?|affordable|budget|under \$?\d+|price(s)?|pricing|cost|worth it)\b/i;
|
|
294
|
+
const TRANSACTIONAL = /\b(buy|order|deal(s)?|discount|coupon|promo|sale|shop|subscription|free trial|download|sign ?up)\b/i;
|
|
295
|
+
const LOCAL = /\b(near me|nearby|open now|in [a-z]+ (city|area)|directions)\b/i;
|
|
296
|
+
export function classifyQuery(q, brand) {
|
|
297
|
+
if (brand?.test(q))
|
|
298
|
+
return "branded";
|
|
299
|
+
if (LOCAL.test(q))
|
|
300
|
+
return "local";
|
|
301
|
+
if (TRANSACTIONAL.test(q))
|
|
302
|
+
return "transactional";
|
|
303
|
+
if (COMPARISON.test(q))
|
|
304
|
+
return "comparison";
|
|
305
|
+
if (QUESTION.test(q))
|
|
306
|
+
return "question";
|
|
307
|
+
if (COMMERCIAL.test(q))
|
|
308
|
+
return "commercial";
|
|
309
|
+
return "informational";
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Long, sentence-like searches are how people type into AI Mode and how AI
|
|
313
|
+
* Overviews get triggered; Search Console folds them into ordinary web data.
|
|
314
|
+
*/
|
|
315
|
+
export function isConversational(q) {
|
|
316
|
+
const words = q.trim().split(/\s+/).length;
|
|
317
|
+
if (LOCAL.test(q))
|
|
318
|
+
return false;
|
|
319
|
+
return words >= 8 || (words >= 6 && QUESTION.test(q)) || (words >= 5 && /\b(i|my|i'm|im|should i|can i|do i|is it)\b/i.test(q));
|
|
320
|
+
}
|
|
321
|
+
const STOP = new Set("a an the and or of for to in on at by with from is are was be how what why when where which who can do does i my me you your it this that vs best near not no without into about".split(" "));
|
|
322
|
+
/** Groups queries under their most significant shared word (by impressions), a cheap and surprisingly readable topic map. */
|
|
323
|
+
export function clusterQueries(rows, max = 15) {
|
|
324
|
+
const tokenImpr = new Map();
|
|
325
|
+
const df = new Map();
|
|
326
|
+
const tokens = rows.map((r) => {
|
|
327
|
+
const t = [...new Set(r.keys[0].toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((w) => w.length > 2 && !STOP.has(w) && !/^\d+$/.test(w)))];
|
|
328
|
+
for (const w of t) {
|
|
329
|
+
tokenImpr.set(w, (tokenImpr.get(w) ?? 0) + r.impressions);
|
|
330
|
+
df.set(w, (df.get(w) ?? 0) + 1);
|
|
331
|
+
}
|
|
332
|
+
return t;
|
|
333
|
+
});
|
|
334
|
+
// Weight each word by sqrt(impressions) times inverse document frequency, so words
|
|
335
|
+
// in nearly every query ("coffee" on a coffee site) fade out on their own.
|
|
336
|
+
// A word only one query uses cannot name a group.
|
|
337
|
+
const n = rows.length;
|
|
338
|
+
const score = (w) => ((df.get(w) ?? 0) < 2 ? -1 : Math.sqrt(tokenImpr.get(w) ?? 0) * Math.log((n + 1) / (df.get(w) ?? 1)));
|
|
339
|
+
const groups = new Map();
|
|
340
|
+
rows.forEach((r, i) => {
|
|
341
|
+
const t = tokens[i].filter((w) => score(w) > 0);
|
|
342
|
+
if (!t.length)
|
|
343
|
+
return;
|
|
344
|
+
const topic = t.reduce((a, b) => (score(b) > score(a) ? b : a));
|
|
345
|
+
const g = groups.get(topic) ?? { rows: [] };
|
|
346
|
+
g.rows.push(r);
|
|
347
|
+
groups.set(topic, g);
|
|
348
|
+
});
|
|
349
|
+
return [...groups.entries()]
|
|
350
|
+
.map(([topic, g]) => {
|
|
351
|
+
const impressions = g.rows.reduce((a, r) => a + r.impressions, 0);
|
|
352
|
+
return {
|
|
353
|
+
topic,
|
|
354
|
+
queries: g.rows.length,
|
|
355
|
+
clicks: g.rows.reduce((a, r) => a + r.clicks, 0),
|
|
356
|
+
impressions,
|
|
357
|
+
position: impressions ? g.rows.reduce((a, r) => a + r.position * r.impressions, 0) / impressions : 0,
|
|
358
|
+
examples: [...g.rows].sort((a, b) => b.impressions - a.impressions).slice(0, 3).map((r) => r.keys[0]),
|
|
359
|
+
};
|
|
360
|
+
})
|
|
361
|
+
.filter((c) => c.queries >= 2)
|
|
362
|
+
.sort((a, b) => b.impressions - a.impressions)
|
|
363
|
+
.slice(0, max);
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Flags days that break from the same weekday over the previous four weeks.
|
|
367
|
+
* Comparing like with like removes the weekly cycle that makes plain z-scores
|
|
368
|
+
* cry wolf every weekend.
|
|
369
|
+
*/
|
|
370
|
+
export function anomalies(series, threshold = 2.5) {
|
|
371
|
+
const out = [];
|
|
372
|
+
for (let i = 28; i < series.length; i++) {
|
|
373
|
+
const peers = [7, 14, 21, 28].map((k) => series[i - k].value);
|
|
374
|
+
const mean = peers.reduce((a, b) => a + b, 0) / peers.length;
|
|
375
|
+
const sd = Math.sqrt(peers.reduce((a, b) => a + (b - mean) ** 2, 0) / (peers.length - 1));
|
|
376
|
+
// Floor the spread so tiny, very steady series do not flag every wobble.
|
|
377
|
+
const spread = Math.max(sd, mean * 0.08, 3);
|
|
378
|
+
const z = (series[i].value - mean) / spread;
|
|
379
|
+
if (Math.abs(z) >= threshold)
|
|
380
|
+
out.push({ date: series[i].date, value: series[i].value, expected: mean, z });
|
|
381
|
+
}
|
|
382
|
+
return out;
|
|
383
|
+
}
|
|
384
|
+
/** Average daily clicks in the two weeks before an update started against the two weeks after it finished rolling out. */
|
|
385
|
+
export function updateImpact(days, updates, windowDays = 14) {
|
|
386
|
+
const byDate = new Map(days.map((d) => [d.keys[0], d]));
|
|
387
|
+
const shift = (date, n) => new Date(Date.parse(date + "T00:00:00Z") + n * 86_400_000).toISOString().slice(0, 10);
|
|
388
|
+
const window = (from, n) => Array.from({ length: n }, (_, i) => byDate.get(shift(from, i))).filter((r) => !!r);
|
|
389
|
+
const out = [];
|
|
390
|
+
for (const u of updates) {
|
|
391
|
+
const before = window(shift(u.begin, -windowDays), windowDays);
|
|
392
|
+
const after = window(shift(u.end ?? shift(u.begin, windowDays), 1), windowDays);
|
|
393
|
+
if (before.length < windowDays / 2 || after.length < windowDays / 2)
|
|
394
|
+
continue;
|
|
395
|
+
const avgClicks = (rs) => rs.reduce((a, r) => a + r.clicks, 0) / rs.length;
|
|
396
|
+
const avgPos = (rs) => {
|
|
397
|
+
const imp = rs.reduce((a, r) => a + r.impressions, 0);
|
|
398
|
+
return imp ? rs.reduce((a, r) => a + r.position * r.impressions, 0) / imp : 0;
|
|
399
|
+
};
|
|
400
|
+
const b = avgClicks(before);
|
|
401
|
+
const a = avgClicks(after);
|
|
402
|
+
out.push({ name: u.name, begin: u.begin, end: u.end, before: b, after: a, change: b ? (a - b) / b : 0, posBefore: avgPos(before), posAfter: avgPos(after) });
|
|
403
|
+
}
|
|
404
|
+
return out;
|
|
405
|
+
}
|