@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/dist/tools.js
ADDED
|
@@ -0,0 +1,971 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { resolveRange, previousPeriod, yearAgo, parse, fmt } from "./dates.js";
|
|
3
|
+
import { anomalies, classifyQuery, clusterQueries, isConversational, updateImpact, attributeChanges, buildCtrCurve, cannibalization, changePoint, compareRows, contentDecay, lowCtr, rollup, sectionOf, strikingDistance, } from "./analysis.js";
|
|
4
|
+
import { delta, int, pct, pos, signed, signedPct, table } from "./format.js";
|
|
5
|
+
import { NotConfiguredError, findClient, readStore, profileName, startLogin, SETUP_STEPS } from "./auth.js";
|
|
6
|
+
import { googleUpdates } from "./updates.js";
|
|
7
|
+
const DIMENSIONS = ["query", "page", "country", "device", "date", "hour", "searchAppearance", "brandedClassification"];
|
|
8
|
+
const FILTER_DIMS = ["query", "page", "country", "device", "searchAppearance", "brandedClassification"];
|
|
9
|
+
const TYPES = ["web", "image", "video", "news", "discover", "googleNews", "webMultimodal"];
|
|
10
|
+
const OPERATORS = ["equals", "notEquals", "contains", "notContains", "includingRegex", "excludingRegex"];
|
|
11
|
+
/** Some clients send arrays as JSON strings; accept both. */
|
|
12
|
+
function list(item) {
|
|
13
|
+
return z.preprocess((v) => {
|
|
14
|
+
if (typeof v !== "string")
|
|
15
|
+
return v;
|
|
16
|
+
try {
|
|
17
|
+
const parsed = JSON.parse(v);
|
|
18
|
+
return Array.isArray(parsed) ? parsed : [v];
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return v.split(",").map((s) => s.trim()).filter(Boolean);
|
|
22
|
+
}
|
|
23
|
+
}, z.array(item));
|
|
24
|
+
}
|
|
25
|
+
const site = z.string().optional().describe('e.g. "example.com" or any URL on it. Optional if there is one property.');
|
|
26
|
+
const range = z.string().optional().describe('last7d, last28d (default), last3m, last6m, last12m, last16m, or "2026-01-01..2026-01-31"');
|
|
27
|
+
const type = z.enum(TYPES).optional().describe("Default web");
|
|
28
|
+
const filterSpec = z.string().optional().describe('e.g. "page contains /blog/; country equals usa". Ops: equals, notEquals, contains, notContains, includingRegex, excludingRegex');
|
|
29
|
+
const filters = list(z.object({
|
|
30
|
+
dimension: z.enum(FILTER_DIMS),
|
|
31
|
+
operator: z.enum(OPERATORS).default("contains"),
|
|
32
|
+
expression: z.string(),
|
|
33
|
+
}))
|
|
34
|
+
.optional()
|
|
35
|
+
.describe("Structured form of filter, ANDed. Countries ISO alpha-3 lowercase, devices DESKTOP/MOBILE/TABLET, regex is RE2.");
|
|
36
|
+
const brand = z.string().optional().describe('Regex for branded queries to leave out, e.g. "acme|acme ?corp"');
|
|
37
|
+
const limit = (d, max = 500) => z.number().int().min(1).max(max).default(d).describe("Maximum rows to return");
|
|
38
|
+
function wrap(fn) {
|
|
39
|
+
return async (args, extra) => {
|
|
40
|
+
try {
|
|
41
|
+
return { content: [{ type: "text", text: await fn(args, extra) }] };
|
|
42
|
+
}
|
|
43
|
+
catch (e) {
|
|
44
|
+
const msg = e instanceof NotConfiguredError ? `${e.message}\n\nTip: call the connect_account tool to sign in from here.` : `Error: ${e.message}`;
|
|
45
|
+
return { content: [{ type: "text", text: msg }], isError: true };
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
function header(siteUrl, r, extra = "") {
|
|
50
|
+
return `**${siteUrl}** · ${r.startDate} to ${r.endDate}${extra ? ` · ${extra}` : ""}`;
|
|
51
|
+
}
|
|
52
|
+
const OP_ALIASES = {
|
|
53
|
+
"=": "equals", "==": "equals", is: "equals", "!=": "notEquals", "~": "contains", has: "contains", "!~": "notContains",
|
|
54
|
+
regex: "includingRegex", matches: "includingRegex", "!regex": "excludingRegex",
|
|
55
|
+
};
|
|
56
|
+
/** Parses "page contains /blog/; country equals usa" into API filters. */
|
|
57
|
+
export function parseFilter(spec) {
|
|
58
|
+
if (!spec?.trim())
|
|
59
|
+
return [];
|
|
60
|
+
return spec
|
|
61
|
+
.split(/\s*;\s*|\s+and\s+/i)
|
|
62
|
+
.filter(Boolean)
|
|
63
|
+
.map((part) => {
|
|
64
|
+
const m = part.trim().match(/^(\w+)\s+(\S+)\s+(.+)$/);
|
|
65
|
+
const dim = m && FILTER_DIMS.find((d) => d.toLowerCase() === m[1].toLowerCase());
|
|
66
|
+
const op = m && (OPERATORS.find((o) => o.toLowerCase() === m[2].toLowerCase()) ?? OP_ALIASES[m[2].toLowerCase()]);
|
|
67
|
+
if (!m || !dim || !op)
|
|
68
|
+
throw new Error(`Could not read filter "${part}". Write it like "page contains /blog/" (dimension, operator, value).`);
|
|
69
|
+
let expression = m[3].trim().replace(/^["']|["']$/g, "");
|
|
70
|
+
if (dim === "country")
|
|
71
|
+
expression = expression.toLowerCase();
|
|
72
|
+
if (dim === "device")
|
|
73
|
+
expression = expression.toUpperCase();
|
|
74
|
+
return { dimension: dim, operator: op, expression };
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
function filtersOf(a) {
|
|
78
|
+
return [...(a.filters ?? []), ...parseFilter(a.filter)];
|
|
79
|
+
}
|
|
80
|
+
function hostOf(url) {
|
|
81
|
+
try {
|
|
82
|
+
return new URL(url).hostname.replace(/^www\./, "");
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return url;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/** The domain's main word ("acme" for sc-domain:acme.co.uk), the cheapest decent guess at a brand. */
|
|
89
|
+
export function defaultBrand(siteUrl) {
|
|
90
|
+
const host = siteUrl.replace(/^sc-domain:|^https?:\/\/(www\.)?/, "").split("/")[0];
|
|
91
|
+
const parts = host.split(".");
|
|
92
|
+
const name = parts.length > 2 && parts.at(-2).length <= 3 ? parts.at(-3) : parts.at(-2) ?? parts[0];
|
|
93
|
+
// Allow a space or hyphen between any letters: people search "break scale" for breakscale.
|
|
94
|
+
return [...name.toLowerCase().replace(/[^a-z0-9]/g, "")].join("[ -]?");
|
|
95
|
+
}
|
|
96
|
+
function withBrand(f, brandRegex) {
|
|
97
|
+
const out = [...(f ?? [])];
|
|
98
|
+
if (brandRegex)
|
|
99
|
+
out.push({ dimension: "query", operator: "excludingRegex", expression: `(?i)${brandRegex}` });
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
function truncNote(truncated, shown) {
|
|
103
|
+
return truncated ? `\n_Showing the first ${int(shown)} rows; more exist. Raise maxRows or add filters for the rest._` : "";
|
|
104
|
+
}
|
|
105
|
+
const READ = { readOnlyHint: true, openWorldHint: true };
|
|
106
|
+
export const FAMILIES = {
|
|
107
|
+
core: ["connect_account", "list_sites", "site_overview", "search_analytics", "page_report"],
|
|
108
|
+
insights: ["all_sites_overview", "compare_periods", "diagnose_traffic_drop", "update_impact", "find_anomalies", "find_content_decay", "find_opportunities", "find_low_ctr", "find_cannibalization", "analyze_queries", "brand_split", "section_report"],
|
|
109
|
+
indexing: ["inspect_url", "audit_indexing", "list_sitemaps", "page_speed"],
|
|
110
|
+
write: ["submit_sitemap", "delete_sitemap", "add_site", "delete_site", "request_indexing"],
|
|
111
|
+
};
|
|
112
|
+
/** GSC_TOOLS="core,indexing" or "core,find_opportunities" trims the tool list so it costs fewer tokens in every conversation. */
|
|
113
|
+
export function toolFilter(spec = process.env.GSC_TOOLS) {
|
|
114
|
+
if (!spec?.trim())
|
|
115
|
+
return () => true;
|
|
116
|
+
const allowed = new Set(["connect_account"]);
|
|
117
|
+
for (const part of spec.split(",").map((x) => x.trim()).filter(Boolean)) {
|
|
118
|
+
for (const name of FAMILIES[part] ?? [part])
|
|
119
|
+
allowed.add(name);
|
|
120
|
+
}
|
|
121
|
+
return (name) => allowed.has(name);
|
|
122
|
+
}
|
|
123
|
+
export function registerTools(server, gsc, opts) {
|
|
124
|
+
const allow = toolFilter();
|
|
125
|
+
const reg = ((name, config, cb) => (allow(name) ? server.registerTool(name, config, cb) : undefined));
|
|
126
|
+
// ---------------------------------------------------------------- account
|
|
127
|
+
reg("connect_account", {
|
|
128
|
+
title: "Connect Google Search Console",
|
|
129
|
+
description: "Check whether Search Console is connected and, if not, start Google sign-in. Returns a link for the user to open. Use this whenever another tool says Search Console is not connected.",
|
|
130
|
+
inputSchema: {
|
|
131
|
+
profile: z.string().optional().describe("Save under this profile name, for connecting a second Google account"),
|
|
132
|
+
write: z.boolean().optional().describe("Also ask permission to submit and remove sitemaps"),
|
|
133
|
+
},
|
|
134
|
+
annotations: { readOnlyHint: false, openWorldHint: true, idempotentHint: true },
|
|
135
|
+
}, wrap(async (a) => {
|
|
136
|
+
if (opts.demo)
|
|
137
|
+
return "Demo mode is on (GSC_DEMO=1), so no Google account is needed. Remove GSC_DEMO from the MCP config to use real data.";
|
|
138
|
+
const wanted = a.profile || profileName();
|
|
139
|
+
if (!a.profile && !a.write) {
|
|
140
|
+
try {
|
|
141
|
+
const sites = await gsc.listSites(true);
|
|
142
|
+
const auth = await opts.auth?.get();
|
|
143
|
+
return `Already connected${auth ? ` via ${auth.method}` : ""}. ${sites.length} properties: ${sites.map((s) => s.siteUrl).join(", ")}`;
|
|
144
|
+
}
|
|
145
|
+
catch (e) {
|
|
146
|
+
if (!(e instanceof NotConfiguredError))
|
|
147
|
+
throw e;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const client = findClient({ profile: wanted });
|
|
151
|
+
if (!client) {
|
|
152
|
+
return [
|
|
153
|
+
"Search Console needs a one-time Google setup before signing in. Easiest path: ask the user to run this in a terminal, it walks them through everything:",
|
|
154
|
+
"",
|
|
155
|
+
" npx -y @xevrion/gsc-mcp setup",
|
|
156
|
+
"",
|
|
157
|
+
"Or do it by hand (about 2 minutes, free), then call connect_account again:",
|
|
158
|
+
...SETUP_STEPS.map((s, i) => `${i + 1}. ${s.title}: ${s.url}`),
|
|
159
|
+
"",
|
|
160
|
+
"Once the JSON is in the Downloads folder it is picked up automatically.",
|
|
161
|
+
].join("\n");
|
|
162
|
+
}
|
|
163
|
+
const { authUrl, done } = await startLogin({ client, profile: wanted, write: a.write });
|
|
164
|
+
done
|
|
165
|
+
.then(() => {
|
|
166
|
+
opts.auth?.reset();
|
|
167
|
+
gsc.clearCache();
|
|
168
|
+
})
|
|
169
|
+
.catch(() => { });
|
|
170
|
+
return [
|
|
171
|
+
"A Google sign-in page should have opened in the browser. If not, ask the user to open this link:",
|
|
172
|
+
"",
|
|
173
|
+
authUrl,
|
|
174
|
+
"",
|
|
175
|
+
`After they approve, Search Console is connected (profile "${wanted}"). Wait for the user to confirm, then retry the original request.`,
|
|
176
|
+
`If Google warns the app is unverified, click Advanced, then "Go to ... (unsafe)". It is their own OAuth app.`,
|
|
177
|
+
].join("\n");
|
|
178
|
+
}));
|
|
179
|
+
reg("list_sites", {
|
|
180
|
+
title: "List Search Console properties",
|
|
181
|
+
description: "Every Search Console property this account can access, with permission level. Use it when you do not know which site the user means.",
|
|
182
|
+
inputSchema: {},
|
|
183
|
+
annotations: READ,
|
|
184
|
+
}, wrap(async () => {
|
|
185
|
+
const sites = await gsc.listSites(true);
|
|
186
|
+
if (!sites.length)
|
|
187
|
+
return "This Google account has no Search Console properties. Add it as a user on a property (Search Console > Settings > Users and permissions).";
|
|
188
|
+
const profiles = Object.keys(readStore().profiles);
|
|
189
|
+
const multi = sites.some((s) => s.account);
|
|
190
|
+
return (table(["property", "permission", "kind", ...(multi ? ["account"] : [])], sites.map((s) => [s.siteUrl, s.permissionLevel, s.siteUrl.startsWith("sc-domain:") ? "domain" : "url-prefix", ...(multi ? [s.account] : [])])) +
|
|
191
|
+
(profiles.length > 1 ? `\n\nConnected accounts: ${profiles.join(", ")}. Each property is used through the account that can see it.` : ""));
|
|
192
|
+
}));
|
|
193
|
+
// ---------------------------------------------------------------- overviews
|
|
194
|
+
reg("site_overview", {
|
|
195
|
+
title: "Site performance overview",
|
|
196
|
+
description: "One-call health check: clicks, impressions, CTR and position against the previous period and last year, top queries and pages with changes, devices, countries, and how much traffic Google hides as anonymous queries. Best first tool for 'how is my site doing'.",
|
|
197
|
+
inputSchema: { site, range, type },
|
|
198
|
+
annotations: READ,
|
|
199
|
+
}, wrap(async (a) => {
|
|
200
|
+
const siteUrl = await gsc.resolveSite(a.site);
|
|
201
|
+
const cur = resolveRange(a);
|
|
202
|
+
const prev = previousPeriod(cur);
|
|
203
|
+
const yoy = yearAgo(cur);
|
|
204
|
+
const base = { type: a.type };
|
|
205
|
+
const [t, tp, ty, q, qp, p, pp, d, c, fresh] = await Promise.all([
|
|
206
|
+
gsc.totals(siteUrl, { ...cur, ...base }),
|
|
207
|
+
gsc.totals(siteUrl, { ...prev, ...base }),
|
|
208
|
+
gsc.totals(siteUrl, { ...yoy, ...base }).catch(() => null),
|
|
209
|
+
gsc.queryAll(siteUrl, { ...cur, ...base, dimensions: ["query"], maxRows: 25_000 }),
|
|
210
|
+
gsc.query(siteUrl, { ...prev, ...base, dimensions: ["query"], maxRows: 5_000 }),
|
|
211
|
+
gsc.query(siteUrl, { ...cur, ...base, dimensions: ["page"], maxRows: 10 }),
|
|
212
|
+
gsc.query(siteUrl, { ...prev, ...base, dimensions: ["page"], maxRows: 5_000 }),
|
|
213
|
+
gsc.query(siteUrl, { ...cur, ...base, dimensions: ["device"] }),
|
|
214
|
+
gsc.query(siteUrl, { ...cur, ...base, dimensions: ["country"], maxRows: 5 }),
|
|
215
|
+
gsc.freshness(siteUrl).catch(() => ({})),
|
|
216
|
+
]);
|
|
217
|
+
const qpm = new Map(qp.map((r) => [r.keys[0], r]));
|
|
218
|
+
const ppm = new Map(pp.map((r) => [r.keys[0], r]));
|
|
219
|
+
const yo = ty && ty.impressions ? ty : null;
|
|
220
|
+
const queryClicks = q.rows.reduce((s, r) => s + r.clicks, 0);
|
|
221
|
+
const hidden = t.clicks ? Math.max(0, 1 - queryClicks / t.clicks) : 0;
|
|
222
|
+
const top3 = q.rows.filter((r) => r.position <= 3).length;
|
|
223
|
+
const top10 = q.rows.filter((r) => r.position <= 10).length;
|
|
224
|
+
const posChange = tp.position - t.position;
|
|
225
|
+
return [
|
|
226
|
+
header(siteUrl, cur, `vs ${prev.startDate} to ${prev.endDate}`),
|
|
227
|
+
"",
|
|
228
|
+
table(["metric", "current", "previous", "change", ...(yo ? ["year ago", "YoY"] : [])], [
|
|
229
|
+
["clicks", int(t.clicks), int(tp.clicks), delta(t.clicks, tp.clicks), ...(yo ? [int(yo.clicks), delta(t.clicks, yo.clicks)] : [])],
|
|
230
|
+
["impressions", int(t.impressions), int(tp.impressions), delta(t.impressions, tp.impressions), ...(yo ? [int(yo.impressions), delta(t.impressions, yo.impressions)] : [])],
|
|
231
|
+
["CTR", pct(t.ctr, 2), pct(tp.ctr, 2), delta(t.ctr, tp.ctr), ...(yo ? [pct(yo.ctr, 2), delta(t.ctr, yo.ctr)] : [])],
|
|
232
|
+
["avg position", pos(t.position), pos(tp.position), `${posChange >= 0 ? "better by" : "worse by"} ${Math.abs(posChange).toFixed(1)}`, ...(yo ? [pos(yo.position), ""] : [])],
|
|
233
|
+
]),
|
|
234
|
+
"",
|
|
235
|
+
fresh.latest ? `Data is final through ${fresh.latestFinal ?? "?"}; partial data exists up to ${fresh.latest}.` : "",
|
|
236
|
+
`${int(q.rows.length)}${q.truncated ? "+" : ""} queries with impressions; ${int(top3)} in the top 3, ${int(top10)} on page one. ${pct(hidden, 0)} of clicks come from anonymized queries Google does not list.`,
|
|
237
|
+
"",
|
|
238
|
+
"**Top queries**",
|
|
239
|
+
table(["query", "clicks", "Δ clicks", "impr", "CTR", "pos"], q.rows.slice(0, 10).map((r) => [r.keys[0], int(r.clicks), delta(r.clicks, qpm.get(r.keys[0])?.clicks ?? 0), int(r.impressions), pct(r.ctr), pos(r.position)])),
|
|
240
|
+
"",
|
|
241
|
+
"**Top pages**",
|
|
242
|
+
table(["page", "clicks", "Δ clicks", "impr", "CTR", "pos"], p.map((r) => [r.keys[0], int(r.clicks), delta(r.clicks, ppm.get(r.keys[0])?.clicks ?? 0), int(r.impressions), pct(r.ctr), pos(r.position)])),
|
|
243
|
+
"",
|
|
244
|
+
"**Devices**",
|
|
245
|
+
table(["device", "clicks", "share", "CTR", "pos"], d.map((r) => [r.keys[0], int(r.clicks), pct(t.clicks ? r.clicks / t.clicks : 0), pct(r.ctr), pos(r.position)])),
|
|
246
|
+
"",
|
|
247
|
+
"**Top countries**",
|
|
248
|
+
table(["country", "clicks", "impr", "CTR", "pos"], c.map((r) => [r.keys[0], int(r.clicks), int(r.impressions), pct(r.ctr), pos(r.position)])),
|
|
249
|
+
].join("\n");
|
|
250
|
+
}));
|
|
251
|
+
reg("all_sites_overview", {
|
|
252
|
+
title: "Compare all properties",
|
|
253
|
+
description: "Clicks, impressions, CTR and position for every property side by side, with change against the previous period. Use it for agencies or anyone with several sites.",
|
|
254
|
+
inputSchema: { range },
|
|
255
|
+
annotations: READ,
|
|
256
|
+
}, wrap(async (a) => {
|
|
257
|
+
const cur = resolveRange(a);
|
|
258
|
+
const prev = previousPeriod(cur);
|
|
259
|
+
const sites = (await gsc.listSites(true)).filter((s) => s.permissionLevel !== "siteUnverifiedUser");
|
|
260
|
+
const rows = await mapLimit(sites, 4, async (s) => {
|
|
261
|
+
try {
|
|
262
|
+
const [t, p] = await Promise.all([gsc.totals(s.siteUrl, cur), gsc.totals(s.siteUrl, prev)]);
|
|
263
|
+
return { site: s.siteUrl, t, p };
|
|
264
|
+
}
|
|
265
|
+
catch (e) {
|
|
266
|
+
return { site: s.siteUrl, error: e.message };
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
rows.sort((x, y) => ("t" in x && x.t ? x.t.clicks : -1) < ("t" in y && y.t ? y.t.clicks : -1) ? 1 : -1);
|
|
270
|
+
return [
|
|
271
|
+
`${sites.length} properties · ${cur.startDate} to ${cur.endDate} vs previous period`,
|
|
272
|
+
"",
|
|
273
|
+
table(["property", "clicks", "Δ", "impr", "Δ", "CTR", "pos"], rows.map((r) => ("error" in r && r.error ? [r.site, "error", r.error, "", "", "", ""] : [r.site, int(r.t.clicks), delta(r.t.clicks, r.p.clicks), int(r.t.impressions), delta(r.t.impressions, r.p.impressions), pct(r.t.ctr), pos(r.t.position)]))),
|
|
274
|
+
].join("\n");
|
|
275
|
+
}));
|
|
276
|
+
// ---------------------------------------------------------------- raw data
|
|
277
|
+
reg("search_analytics", {
|
|
278
|
+
title: "Query search analytics",
|
|
279
|
+
description: "Raw Search Console performance data grouped by any dimensions, with filters. Pages past Google's 25,000-row limit automatically and says when results were cut off. Use dimensions [\"hour\"] for hourly data from the last 10 days, or [\"date\"] for a daily trend.",
|
|
280
|
+
inputSchema: {
|
|
281
|
+
site,
|
|
282
|
+
range,
|
|
283
|
+
dimensions: list(z.enum(DIMENSIONS)).optional().describe('Group by, e.g. ["query"], ["page","query"], ["date"], ["hour"]. Empty gives totals.'),
|
|
284
|
+
filter: filterSpec,
|
|
285
|
+
countries: list(z.string()).optional().describe('Match any of these countries (ISO alpha-3), e.g. ["usa","gbr"]'),
|
|
286
|
+
devices: list(z.enum(["DESKTOP", "MOBILE", "TABLET"])).optional().describe("Match any of these devices"),
|
|
287
|
+
type,
|
|
288
|
+
aggregationType: z.enum(["auto", "byPage", "byProperty"]).optional(),
|
|
289
|
+
fresh: z.boolean().optional().describe("Include fresh, not yet final data from the last ~2 days"),
|
|
290
|
+
orderBy: z.enum(["clicks", "impressions", "ctr", "position"]).optional().describe("Sort descending by this metric (position sorts best first). Default clicks; date and hour sort by time."),
|
|
291
|
+
maxRows: z.number().int().min(1).max(100_000).optional().describe("Default 100. Keep it small unless you need everything; 1,000 rows is about 30k tokens."),
|
|
292
|
+
format: z.enum(["table", "json", "csv"]).optional().describe("table (default, compact), json or csv"),
|
|
293
|
+
},
|
|
294
|
+
annotations: READ,
|
|
295
|
+
}, wrap(async (a) => {
|
|
296
|
+
const siteUrl = await gsc.resolveSite(a.site);
|
|
297
|
+
const dims = (a.dimensions ?? []);
|
|
298
|
+
const r = dims.includes("hour") && !a.range ? resolveRange({ range: "last7d", fresh: true }) : resolveRange(a);
|
|
299
|
+
const filterLists = [
|
|
300
|
+
...(a.countries?.length ? [{ dimension: "country", values: a.countries.map((c) => c.toLowerCase()) }] : []),
|
|
301
|
+
...(a.devices?.length ? [{ dimension: "device", values: a.devices }] : []),
|
|
302
|
+
];
|
|
303
|
+
const { rows, truncated } = await gsc.queryAll(siteUrl, {
|
|
304
|
+
...r,
|
|
305
|
+
dimensions: dims,
|
|
306
|
+
filters: filtersOf(a),
|
|
307
|
+
filterLists,
|
|
308
|
+
type: a.type,
|
|
309
|
+
aggregationType: a.aggregationType,
|
|
310
|
+
dataState: dims.includes("hour") ? "hourly_all" : a.fresh ? "all" : "final",
|
|
311
|
+
maxRows: a.maxRows ?? 100,
|
|
312
|
+
});
|
|
313
|
+
const key = a.orderBy ?? "clicks";
|
|
314
|
+
if ((dims[0] === "date" || dims[0] === "hour") && !a.orderBy)
|
|
315
|
+
rows.sort((x, y) => x.keys[0].localeCompare(y.keys[0]));
|
|
316
|
+
else
|
|
317
|
+
rows.sort((x, y) => (key === "position" ? x.position - y.position : y[key] - x[key]));
|
|
318
|
+
if (a.format === "json")
|
|
319
|
+
return JSON.stringify({ site: siteUrl, ...r, dimensions: dims, truncated, rows });
|
|
320
|
+
const cols = dims.length ? dims : ["total"];
|
|
321
|
+
if (a.format === "csv") {
|
|
322
|
+
const q = (v) => (/[",\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v);
|
|
323
|
+
return [[...cols, "clicks", "impressions", "ctr", "position"].join(","), ...rows.map((x) => [...(dims.length ? x.keys : ["all"]).map(q), x.clicks, x.impressions, x.ctr.toFixed(4), x.position.toFixed(2)].join(","))].join("\n");
|
|
324
|
+
}
|
|
325
|
+
return [
|
|
326
|
+
header(siteUrl, r, `${int(rows.length)} rows${dims.length ? ` by ${dims.join(", ")}` : ""}`),
|
|
327
|
+
"",
|
|
328
|
+
table([...cols, "clicks", "impr", "CTR", "pos"], rows.map((x) => [...(dims.length ? x.keys : ["all"]), int(x.clicks), int(x.impressions), pct(x.ctr, 2), pos(x.position)])),
|
|
329
|
+
truncNote(truncated, rows.length),
|
|
330
|
+
].join("\n");
|
|
331
|
+
}));
|
|
332
|
+
// ---------------------------------------------------------------- change
|
|
333
|
+
reg("compare_periods", {
|
|
334
|
+
title: "Compare two periods",
|
|
335
|
+
description: "Biggest winners and losers between this period and the previous one (or the same period last year), by query, page, country, device or search appearance.",
|
|
336
|
+
inputSchema: {
|
|
337
|
+
site,
|
|
338
|
+
range,
|
|
339
|
+
dimension: z.enum(["query", "page", "country", "device", "searchAppearance"]).default("page"),
|
|
340
|
+
against: z.enum(["previous", "yearAgo"]).default("previous"),
|
|
341
|
+
filter: filterSpec,
|
|
342
|
+
type,
|
|
343
|
+
limit: limit(15, 200),
|
|
344
|
+
},
|
|
345
|
+
annotations: READ,
|
|
346
|
+
}, wrap(async (a) => {
|
|
347
|
+
const siteUrl = await gsc.resolveSite(a.site);
|
|
348
|
+
const cur = resolveRange(a);
|
|
349
|
+
const prev = a.against === "yearAgo" ? yearAgo(cur) : previousPeriod(cur);
|
|
350
|
+
const q = (r) => gsc.query(siteUrl, { ...r, dimensions: [a.dimension], filters: filtersOf(a), type: a.type, maxRows: 25_000 });
|
|
351
|
+
const [c, p] = await Promise.all([q(cur), q(prev)]);
|
|
352
|
+
const changes = compareRows(c, p);
|
|
353
|
+
const totalNow = c.reduce((s, r) => s + r.clicks, 0);
|
|
354
|
+
const totalPrev = p.reduce((s, r) => s + r.clicks, 0);
|
|
355
|
+
const fmtRows = (rows) => table([a.dimension, "clicks", "before", "Δ", "Δ%", "pos", "pos before"], rows.map((x) => [x.key, int(x.clicks), int(x.prevClicks), signed(x.clicksDelta), signedPct(x.clicksPct), pos(x.position), pos(x.prevPosition)]));
|
|
356
|
+
const winners = changes.filter((x) => x.clicksDelta > 0).sort((x, y) => y.clicksDelta - x.clicksDelta).slice(0, a.limit);
|
|
357
|
+
const losers = changes.filter((x) => x.clicksDelta < 0).sort((x, y) => x.clicksDelta - y.clicksDelta).slice(0, a.limit);
|
|
358
|
+
const gone = changes.filter((x) => x.clicks === 0 && x.prevClicks > 0).length;
|
|
359
|
+
return [
|
|
360
|
+
header(siteUrl, cur, `vs ${prev.startDate} to ${prev.endDate}`),
|
|
361
|
+
`Clicks ${int(totalNow)} vs ${int(totalPrev)} (${delta(totalNow, totalPrev)}). ${gone} ${a.dimension} rows that had clicks before have none now.`,
|
|
362
|
+
"",
|
|
363
|
+
"**Losers**",
|
|
364
|
+
fmtRows(losers),
|
|
365
|
+
"",
|
|
366
|
+
"**Winners**",
|
|
367
|
+
fmtRows(winners),
|
|
368
|
+
].join("\n");
|
|
369
|
+
}));
|
|
370
|
+
reg("diagnose_traffic_drop", {
|
|
371
|
+
title: "Diagnose a traffic drop",
|
|
372
|
+
description: "Explains why clicks changed: finds the day the trend broke, checks it against Google's confirmed algorithm updates, and splits the change into lost pages, ranking drops, CTR drops (same rank, fewer clicks) and lower search demand. Use for 'why did my traffic drop?'.",
|
|
373
|
+
inputSchema: {
|
|
374
|
+
site,
|
|
375
|
+
range: range.describe('The period after the drop, compared with the one before it. last28d (default), last3m, ... or "2026-01-01..2026-01-31"'),
|
|
376
|
+
dimension: z.enum(["page", "query"]).default("page"),
|
|
377
|
+
limit: limit(10, 100),
|
|
378
|
+
},
|
|
379
|
+
annotations: READ,
|
|
380
|
+
}, wrap(async (a) => {
|
|
381
|
+
const siteUrl = await gsc.resolveSite(a.site);
|
|
382
|
+
const cur = resolveRange(a);
|
|
383
|
+
const prev = previousPeriod(cur);
|
|
384
|
+
const daily = { startDate: prev.startDate, endDate: cur.endDate };
|
|
385
|
+
const [c, p, days, updates] = await Promise.all([
|
|
386
|
+
gsc.query(siteUrl, { ...cur, dimensions: [a.dimension], maxRows: 25_000 }),
|
|
387
|
+
gsc.query(siteUrl, { ...prev, dimensions: [a.dimension], maxRows: 25_000 }),
|
|
388
|
+
gsc.query(siteUrl, { ...daily, dimensions: ["date"], maxRows: 1000 }),
|
|
389
|
+
googleUpdates(gsc.fetchImpl).catch(() => []),
|
|
390
|
+
]);
|
|
391
|
+
days.sort((x, y) => x.keys[0].localeCompare(y.keys[0]));
|
|
392
|
+
const cp = changePoint(days.map((d) => ({ date: d.keys[0], value: d.clicks })));
|
|
393
|
+
const parts = attributeChanges(c, p);
|
|
394
|
+
const totals = { lost: 0, ranking: 0, ctr: 0, demand: 0, new: 0 };
|
|
395
|
+
for (const x of parts)
|
|
396
|
+
totals[x.reason] += x.clicksDelta;
|
|
397
|
+
const now = c.reduce((s, r) => s + r.clicks, 0);
|
|
398
|
+
const before = p.reduce((s, r) => s + r.clicks, 0);
|
|
399
|
+
const windowStart = parse(daily.startDate).getTime();
|
|
400
|
+
const overlapping = updates.filter((u) => parse(u.end ?? fmt(new Date())).getTime() >= windowStart);
|
|
401
|
+
const near = cp ? overlapping.filter((u) => Math.abs(parse(u.begin).getTime() - parse(cp.date).getTime()) <= 14 * 86_400_000 || (parse(cp.date) >= parse(u.begin) && parse(cp.date) <= parse(u.end ?? fmt(new Date())))) : [];
|
|
402
|
+
if (before < 10 && now > before) {
|
|
403
|
+
return [
|
|
404
|
+
header(siteUrl, cur, `vs ${prev.startDate} to ${prev.endDate}`),
|
|
405
|
+
`Clicks ${int(now)} vs ${int(before)}: there is no drop to diagnose. The site had almost no search traffic in the previous period, so it is new or just started ranking.`,
|
|
406
|
+
cp ? `Traffic took off around **${cp.date}** (~${int(cp.before)} → ~${int(cp.after)} clicks a day).` : "",
|
|
407
|
+
"Use find_anomalies to see launch-day spikes, or site_overview for where the traffic comes from.",
|
|
408
|
+
].filter(Boolean).join("\n");
|
|
409
|
+
}
|
|
410
|
+
const losers = parts.filter((x) => x.clicksDelta < 0).sort((x, y) => x.clicksDelta - y.clicksDelta).slice(0, a.limit);
|
|
411
|
+
const labels = { lost: "Pages/queries that vanished", ranking: "Ranking drops", ctr: "CTR drops at similar rank", demand: "Lower search demand", new: "New pages/queries" };
|
|
412
|
+
return [
|
|
413
|
+
header(siteUrl, cur, `vs ${prev.startDate} to ${prev.endDate}`),
|
|
414
|
+
`Clicks ${int(now)} vs ${int(before)} (${delta(now, before)}, ${signed(now - before)}).`,
|
|
415
|
+
"",
|
|
416
|
+
cp
|
|
417
|
+
? `**Trend break:** around **${cp.date}**, daily clicks went from ~${int(cp.before)} to ~${int(cp.after)}.`
|
|
418
|
+
: "**Trend break:** no single day where the trend clearly changed; the change is gradual.",
|
|
419
|
+
near.length
|
|
420
|
+
? `**Matches a Google update:** ${near.map((u) => `${u.name} (${u.begin}${u.end ? ` to ${u.end}` : ", ongoing"})`).join("; ")}.`
|
|
421
|
+
: overlapping.length
|
|
422
|
+
? `Google updates in this window, not lined up with the break: ${overlapping.map((u) => `${u.name} (${u.begin})`).join("; ")}.`
|
|
423
|
+
: "No confirmed Google ranking updates in this window.",
|
|
424
|
+
"",
|
|
425
|
+
"**Where the change came from**",
|
|
426
|
+
table(["cause", "clicks Δ"], Object.entries(totals).filter(([, v]) => v !== 0).sort((x, y) => x[1] - y[1]).map(([k, v]) => [labels[k], signed(v)])),
|
|
427
|
+
"",
|
|
428
|
+
`**Biggest ${a.dimension} losses**`,
|
|
429
|
+
table([a.dimension, "clicks Δ", "cause", "detail"], losers.map((x) => [x.key, signed(x.clicksDelta), x.reason, x.detail])),
|
|
430
|
+
"",
|
|
431
|
+
"Reading it: ranking drops point at content quality or competition (and core updates); CTR drops at a similar rank usually mean a new SERP feature or AI Overview, or a weaker title; demand drops are seasonal or market-wide and not a site problem.",
|
|
432
|
+
].join("\n");
|
|
433
|
+
}));
|
|
434
|
+
reg("find_content_decay", {
|
|
435
|
+
title: "Find decaying content",
|
|
436
|
+
description: "Pages losing clicks steadily over several months, fitted with a trend line so one bad month is not flagged. Each page gets a likely cause (ranking, CTR, or demand). These are the best candidates for a content refresh.",
|
|
437
|
+
inputSchema: {
|
|
438
|
+
site,
|
|
439
|
+
periods: z.number().int().min(3).max(12).default(6).describe("Number of consecutive 28-day periods to analyse"),
|
|
440
|
+
minClicks: z.number().default(20).describe("Minimum average clicks per period in the early half"),
|
|
441
|
+
minDecline: z.number().min(0).max(1).default(0.25).describe("Minimum drop from the early to the late average, as a fraction"),
|
|
442
|
+
filter: filterSpec,
|
|
443
|
+
limit: limit(20, 200),
|
|
444
|
+
},
|
|
445
|
+
annotations: READ,
|
|
446
|
+
}, wrap(async (a) => {
|
|
447
|
+
const siteUrl = await gsc.resolveSite(a.site);
|
|
448
|
+
const last = resolveRange({ range: "last28d" });
|
|
449
|
+
const ranges = [last];
|
|
450
|
+
while (ranges.length < a.periods)
|
|
451
|
+
ranges.unshift(previousPeriod(ranges[0]));
|
|
452
|
+
const periods = await Promise.all(ranges.map((r) => gsc.query(siteUrl, { ...r, dimensions: ["page"], filters: filtersOf(a), maxRows: 25_000 })));
|
|
453
|
+
const decays = contentDecay(periods, { minClicks: a.minClicks, minDecline: a.minDecline, minR2: 0.5 }).slice(0, a.limit);
|
|
454
|
+
if (!decays.length)
|
|
455
|
+
return `${header(siteUrl, { startDate: ranges[0].startDate, endDate: last.endDate })}\n\nNo pages are in steady decline at these thresholds.`;
|
|
456
|
+
return [
|
|
457
|
+
header(siteUrl, { startDate: ranges[0].startDate, endDate: last.endDate }, `${a.periods} × 28-day periods`),
|
|
458
|
+
"",
|
|
459
|
+
table(["page", "clicks per period (oldest → newest)", "change", "trend fit", "pos Δ", "likely cause"], decays.map((d) => [d.key, d.series.map((n) => int(n)).join(" → "), signedPct(d.change), d.r2.toFixed(2), (d.positionChange >= 0 ? "+" : "") + d.positionChange.toFixed(1), d.cause])),
|
|
460
|
+
"",
|
|
461
|
+
"pos Δ above zero means the page ranks worse now. ranking: refresh and expand the content; ctr: rewrite the title and description; demand: interest is falling, refresh only if the topic matters.",
|
|
462
|
+
].join("\n");
|
|
463
|
+
}));
|
|
464
|
+
// ---------------------------------------------------------------- opportunities
|
|
465
|
+
reg("find_opportunities", {
|
|
466
|
+
title: "Find striking-distance keywords",
|
|
467
|
+
description: "Quick wins: queries (or pages) ranking just off the top spots with real impressions, ranked by extra clicks if they reached the target position. The estimate uses this site's own CTR curve, not an industry average.",
|
|
468
|
+
inputSchema: {
|
|
469
|
+
site,
|
|
470
|
+
range,
|
|
471
|
+
dimension: z.enum(["query", "page"]).default("query"),
|
|
472
|
+
minPosition: z.number().default(4),
|
|
473
|
+
maxPosition: z.number().default(20),
|
|
474
|
+
minImpressions: z.number().default(50),
|
|
475
|
+
targetPosition: z.number().default(3),
|
|
476
|
+
brand,
|
|
477
|
+
filter: filterSpec,
|
|
478
|
+
limit: limit(25),
|
|
479
|
+
},
|
|
480
|
+
annotations: READ,
|
|
481
|
+
}, wrap(async (a) => {
|
|
482
|
+
const siteUrl = await gsc.resolveSite(a.site);
|
|
483
|
+
const r = resolveRange(a);
|
|
484
|
+
const f = withBrand(filtersOf(a), a.brand);
|
|
485
|
+
const [rows, curve, fit] = await rowsAndCurve(gsc, siteUrl, r, a.dimension, f);
|
|
486
|
+
const all = strikingDistance(rows, curve, a);
|
|
487
|
+
const shown = all.slice(0, a.limit);
|
|
488
|
+
const total = all.reduce((s, x) => s + x.potentialClicks, 0);
|
|
489
|
+
return [
|
|
490
|
+
header(siteUrl, r, `positions ${a.minPosition}-${a.maxPosition}, ≥${a.minImpressions} impressions`),
|
|
491
|
+
`${all.length} opportunities worth up to ~${int(total)} extra clicks in this period. Expected CTR at position ${a.targetPosition}: ${pct(curve(a.targetPosition))} (${fit.personalized.includes(Math.round(a.targetPosition)) ? "measured on this site" : `industry curve scaled to this site's ${fit.siteFactor.toFixed(2)}× CTR`}).`,
|
|
492
|
+
"",
|
|
493
|
+
table([a.dimension, "pos", "impr", "clicks", "CTR", "+clicks at target"], shown.map((x) => [x.key, pos(x.position), int(x.impressions), int(x.clicks), pct(x.ctr), int(x.potentialClicks)])),
|
|
494
|
+
].join("\n");
|
|
495
|
+
}));
|
|
496
|
+
reg("find_low_ctr", {
|
|
497
|
+
title: "Find weak titles (low CTR)",
|
|
498
|
+
description: "Pages or queries that rank well but get clicked much less than this site normally does at that position. Usually fixed by a better title and meta description.",
|
|
499
|
+
inputSchema: {
|
|
500
|
+
site,
|
|
501
|
+
range,
|
|
502
|
+
dimension: z.enum(["query", "page"]).default("page"),
|
|
503
|
+
maxPosition: z.number().default(10),
|
|
504
|
+
minImpressions: z.number().default(200),
|
|
505
|
+
threshold: z.number().min(0).max(1).default(0.6).describe("Flag rows whose CTR is below this fraction of expected"),
|
|
506
|
+
brand,
|
|
507
|
+
filter: filterSpec,
|
|
508
|
+
limit: limit(25),
|
|
509
|
+
},
|
|
510
|
+
annotations: READ,
|
|
511
|
+
}, wrap(async (a) => {
|
|
512
|
+
const siteUrl = await gsc.resolveSite(a.site);
|
|
513
|
+
const r = resolveRange(a);
|
|
514
|
+
const f = withBrand(filtersOf(a), a.brand);
|
|
515
|
+
const [rows, curve, fit] = await rowsAndCurve(gsc, siteUrl, r, a.dimension, f);
|
|
516
|
+
const found = lowCtr(rows, curve, a).slice(0, a.limit);
|
|
517
|
+
return [
|
|
518
|
+
header(siteUrl, r, `CTR below ${pct(a.threshold, 0)} of what this site usually gets at that position`),
|
|
519
|
+
`This site's CTR runs at ${fit.siteFactor.toFixed(2)}× a typical search result, and expectations are scaled to match.`,
|
|
520
|
+
"",
|
|
521
|
+
table([a.dimension, "pos", "impr", "CTR", "expected", "clicks missed"], found.map((x) => [x.key, pos(x.position), int(x.impressions), pct(x.ctr), pct(x.expectedCtr), int(x.potentialClicks)])),
|
|
522
|
+
].join("\n");
|
|
523
|
+
}));
|
|
524
|
+
reg("find_cannibalization", {
|
|
525
|
+
title: "Find keyword cannibalization",
|
|
526
|
+
description: "Queries where two or more of your pages split the impressions, so they compete and usually both rank worse. Scored with a concentration index (0 means one page owns the query) and ranked by impressions at stake.",
|
|
527
|
+
inputSchema: {
|
|
528
|
+
site,
|
|
529
|
+
range,
|
|
530
|
+
minImpressions: z.number().default(100).describe("Minimum total impressions for a query"),
|
|
531
|
+
minShare: z.number().min(0).max(1).default(0.1).describe("A page needs at least this share of the query's impressions to count"),
|
|
532
|
+
brand,
|
|
533
|
+
filter: filterSpec,
|
|
534
|
+
limit: limit(20, 200),
|
|
535
|
+
},
|
|
536
|
+
annotations: READ,
|
|
537
|
+
}, wrap(async (a) => {
|
|
538
|
+
const siteUrl = await gsc.resolveSite(a.site);
|
|
539
|
+
const r = resolveRange(a);
|
|
540
|
+
// Brand searches show the homepage plus sitelinks, which is not competition, so leave them out by default.
|
|
541
|
+
const brandRegex = a.brand === "" ? undefined : (a.brand ?? defaultBrand(siteUrl));
|
|
542
|
+
const { rows, truncated } = await gsc.queryAll(siteUrl, { ...r, dimensions: ["query", "page"], filters: withBrand(filtersOf(a), brandRegex), maxRows: 50_000 });
|
|
543
|
+
const groups = cannibalization(rows, a).slice(0, a.limit);
|
|
544
|
+
const brandLabel = a.brand ? `/${a.brand}/i` : `"${brandRegex?.replace(/\[ -\]\?/g, "")}" (any spacing)`;
|
|
545
|
+
const brandNote = brandRegex ? `Branded queries matching ${brandLabel} are left out; pass brand: "" to include them.` : "";
|
|
546
|
+
if (!groups.length)
|
|
547
|
+
return `${header(siteUrl, r)}\n\nNo cannibalization at these thresholds. ${brandNote}`;
|
|
548
|
+
// Daily evidence for the worst few: if Google keeps swapping which page it
|
|
549
|
+
// shows, the pages really are competing rather than serving two intents.
|
|
550
|
+
const flips = new Map();
|
|
551
|
+
await mapLimit(groups.slice(0, 5), 5, async (g) => {
|
|
552
|
+
const daily = await gsc.query(siteUrl, { ...r, dimensions: ["date", "page"], filters: [{ dimension: "query", operator: "equals", expression: g.query }], maxRows: 5_000 });
|
|
553
|
+
const leader = new Map();
|
|
554
|
+
for (const d of daily)
|
|
555
|
+
if (!leader.has(d.keys[0]) || d.impressions > leader.get(d.keys[0]).impressions)
|
|
556
|
+
leader.set(d.keys[0], d);
|
|
557
|
+
const seq = [...leader.entries()].sort((x, y) => x[0].localeCompare(y[0])).map(([, d]) => d.keys[1]);
|
|
558
|
+
flips.set(g.query, seq.filter((p, i) => i > 0 && p !== seq[i - 1]).length);
|
|
559
|
+
});
|
|
560
|
+
return [
|
|
561
|
+
header(siteUrl, r, `${groups.length} queries split across pages`) + (brandNote ? `\n${brandNote}` : ""),
|
|
562
|
+
...groups.map((g) => `**${g.query}** · ${int(g.impressions)} impr, ${int(g.clicks)} clicks, split ${g.conflict.toFixed(2)}${flips.has(g.query) ? `, Google switched the top page ${flips.get(g.query)} times` : ""}\n` +
|
|
563
|
+
table(["page", "share", "impr", "clicks", "pos"], g.pages.map((p) => [p.page, pct(p.share, 0), int(p.impressions), int(p.clicks), pos(p.position)]))),
|
|
564
|
+
"Fix by merging the weaker page into the stronger one with a 301, or by making each page clearly target a different intent and linking between them." + truncNote(truncated, rows.length),
|
|
565
|
+
].join("\n\n");
|
|
566
|
+
}));
|
|
567
|
+
// ---------------------------------------------------------------- segments
|
|
568
|
+
reg("brand_split", {
|
|
569
|
+
title: "Branded vs non-branded traffic",
|
|
570
|
+
description: "Splits clicks into branded searches (people looking for you) and non-branded (SEO-earned), with change against the previous period. Uses Google's own brand classification when available, otherwise a brand regex.",
|
|
571
|
+
inputSchema: { site, range, brand: brand.describe('Regex for branded queries, e.g. "acme|acme ?corp". Defaults to the domain name.') },
|
|
572
|
+
annotations: READ,
|
|
573
|
+
}, wrap(async (a) => {
|
|
574
|
+
const siteUrl = await gsc.resolveSite(a.site);
|
|
575
|
+
const cur = resolveRange(a);
|
|
576
|
+
const prev = previousPeriod(cur);
|
|
577
|
+
const viaGoogle = async (r) => gsc.query(siteUrl, { ...r, dimensions: ["brandedClassification"], maxRows: 5 }).catch(() => []);
|
|
578
|
+
let source = "Google's branded query classification";
|
|
579
|
+
let [c, p] = await Promise.all([viaGoogle(cur), viaGoogle(prev)]);
|
|
580
|
+
const regex = a.brand ?? defaultBrand(siteUrl);
|
|
581
|
+
if (a.brand || !c.length) {
|
|
582
|
+
source = `queries matching /${regex}/i`;
|
|
583
|
+
const split = async (r) => {
|
|
584
|
+
const [b, n] = await Promise.all([
|
|
585
|
+
gsc.totals(siteUrl, { ...r, filters: [{ dimension: "query", operator: "includingRegex", expression: `(?i)${regex}` }] }),
|
|
586
|
+
gsc.totals(siteUrl, { ...r, filters: [{ dimension: "query", operator: "excludingRegex", expression: `(?i)${regex}` }] }),
|
|
587
|
+
]);
|
|
588
|
+
return [{ ...b, keys: ["BRANDED"] }, { ...n, keys: ["NON_BRANDED"] }];
|
|
589
|
+
};
|
|
590
|
+
[c, p] = await Promise.all([split(cur), split(prev)]);
|
|
591
|
+
}
|
|
592
|
+
const pm = new Map(p.map((r) => [r.keys[0], r]));
|
|
593
|
+
const total = c.reduce((s, r) => s + r.clicks, 0);
|
|
594
|
+
return [
|
|
595
|
+
header(siteUrl, cur, `source: ${source}`),
|
|
596
|
+
"",
|
|
597
|
+
table(["segment", "clicks", "share", "Δ clicks", "impr", "CTR", "pos"], c.map((r) => [r.keys[0] === "BRANDED" ? "branded" : "non-branded", int(r.clicks), pct(total ? r.clicks / total : 0), delta(r.clicks, pm.get(r.keys[0])?.clicks ?? 0), int(r.impressions), pct(r.ctr), pos(r.position)])),
|
|
598
|
+
"",
|
|
599
|
+
"Anonymized queries are only counted when Google's classification is used, so regex totals can be lower than site totals.",
|
|
600
|
+
].join("\n");
|
|
601
|
+
}));
|
|
602
|
+
reg("section_report", {
|
|
603
|
+
title: "Performance by site section",
|
|
604
|
+
description: "Rolls pages up into folders (/blog/, /products/, ...) with clicks, impressions and change, so you can see which part of the site is growing or shrinking.",
|
|
605
|
+
inputSchema: { site, range, depth: z.number().int().min(1).max(4).default(1).describe("Folder depth: 1 groups by /blog/, 2 by /blog/guides/"), limit: limit(30, 200) },
|
|
606
|
+
annotations: READ,
|
|
607
|
+
}, wrap(async (a) => {
|
|
608
|
+
const siteUrl = await gsc.resolveSite(a.site);
|
|
609
|
+
const cur = resolveRange(a);
|
|
610
|
+
const prev = previousPeriod(cur);
|
|
611
|
+
const [c, p] = await Promise.all([cur, prev].map((r) => gsc.query(siteUrl, { ...r, dimensions: ["page"], maxRows: 50_000 })));
|
|
612
|
+
const hosts = new Set(c.map((r) => hostOf(r.keys[0])));
|
|
613
|
+
const key = (r) => sectionOf(r.keys[0], a.depth, hosts.size > 1);
|
|
614
|
+
const rc = rollup(c, key);
|
|
615
|
+
const rp = new Map(rollup(p, key).map((r) => [r.keys[0], r]));
|
|
616
|
+
const total = rc.reduce((s, r) => s + r.clicks, 0);
|
|
617
|
+
return [
|
|
618
|
+
header(siteUrl, cur, `vs previous period, ${rc.length} sections`),
|
|
619
|
+
"",
|
|
620
|
+
table(["section", "pages", "clicks", "share", "Δ clicks", "impr", "CTR", "pos"], rc.slice(0, a.limit).map((r) => [r.keys[0], r.keys[1], int(r.clicks), pct(total ? r.clicks / total : 0), delta(r.clicks, rp.get(r.keys[0])?.clicks ?? 0), int(r.impressions), pct(r.ctr), pos(r.position)])),
|
|
621
|
+
].join("\n");
|
|
622
|
+
}));
|
|
623
|
+
reg("page_report", {
|
|
624
|
+
title: "Deep dive on one page",
|
|
625
|
+
description: "Everything about a single URL: clicks and position against the previous period, the queries it ranks for (with changes), devices, countries, and its index status.",
|
|
626
|
+
inputSchema: { url: z.string().url().describe("The page URL"), site, range, inspect: z.boolean().default(true).describe("Also run a URL inspection") },
|
|
627
|
+
annotations: READ,
|
|
628
|
+
}, wrap(async (a) => {
|
|
629
|
+
const siteUrl = await gsc.resolveSite(a.site ?? a.url);
|
|
630
|
+
const cur = resolveRange(a);
|
|
631
|
+
const prev = previousPeriod(cur);
|
|
632
|
+
const f = [{ dimension: "page", operator: "equals", expression: a.url }];
|
|
633
|
+
const [t, tp, q, qp, d, c, insp] = await Promise.all([
|
|
634
|
+
gsc.totals(siteUrl, { ...cur, filters: f }),
|
|
635
|
+
gsc.totals(siteUrl, { ...prev, filters: f }),
|
|
636
|
+
gsc.query(siteUrl, { ...cur, dimensions: ["query"], filters: f, maxRows: 5_000 }),
|
|
637
|
+
gsc.query(siteUrl, { ...prev, dimensions: ["query"], filters: f, maxRows: 5_000 }),
|
|
638
|
+
gsc.query(siteUrl, { ...cur, dimensions: ["device"], filters: f }),
|
|
639
|
+
gsc.query(siteUrl, { ...cur, dimensions: ["country"], filters: f, maxRows: 5 }),
|
|
640
|
+
a.inspect ? gsc.inspect(siteUrl, a.url).catch((e) => ({ error: e.message })) : Promise.resolve(null),
|
|
641
|
+
]);
|
|
642
|
+
const qpm = new Map(qp.map((r) => [r.keys[0], r]));
|
|
643
|
+
const i = insp && "inspectionResult" in insp ? insp.inspectionResult.indexStatusResult ?? {} : null;
|
|
644
|
+
return [
|
|
645
|
+
`**${a.url}** · ${cur.startDate} to ${cur.endDate}`,
|
|
646
|
+
"",
|
|
647
|
+
table(["metric", "current", "previous", "change"], [
|
|
648
|
+
["clicks", int(t.clicks), int(tp.clicks), delta(t.clicks, tp.clicks)],
|
|
649
|
+
["impressions", int(t.impressions), int(tp.impressions), delta(t.impressions, tp.impressions)],
|
|
650
|
+
["CTR", pct(t.ctr, 2), pct(tp.ctr, 2), delta(t.ctr, tp.ctr)],
|
|
651
|
+
["avg position", pos(t.position), pos(tp.position), tp.position && t.position ? (tp.position - t.position >= 0 ? "better by " : "worse by ") + Math.abs(tp.position - t.position).toFixed(1) : "-"],
|
|
652
|
+
]),
|
|
653
|
+
i
|
|
654
|
+
? `\nIndex: **${i.verdict ?? "?"}**, ${i.coverageState ?? ""}; last crawl ${i.lastCrawlTime?.slice(0, 10) ?? "never"}${i.googleCanonical && i.userCanonical && i.googleCanonical !== i.userCanonical ? `; Google picked a different canonical: ${i.googleCanonical}` : ""}`
|
|
655
|
+
: insp && "error" in insp
|
|
656
|
+
? `\nIndex check failed: ${insp.error}`
|
|
657
|
+
: "",
|
|
658
|
+
"",
|
|
659
|
+
`**Queries (${q.length})**`,
|
|
660
|
+
table(["query", "clicks", "Δ clicks", "impr", "CTR", "pos", "pos before"], q.slice(0, 25).map((r) => [r.keys[0], int(r.clicks), delta(r.clicks, qpm.get(r.keys[0])?.clicks ?? 0), int(r.impressions), pct(r.ctr), pos(r.position), pos(qpm.get(r.keys[0])?.position ?? 0)])),
|
|
661
|
+
"",
|
|
662
|
+
"**Devices**",
|
|
663
|
+
table(["device", "clicks", "impr", "CTR", "pos"], d.map((r) => [r.keys[0], int(r.clicks), int(r.impressions), pct(r.ctr), pos(r.position)])),
|
|
664
|
+
"",
|
|
665
|
+
"**Top countries**",
|
|
666
|
+
table(["country", "clicks", "impr", "CTR", "pos"], c.map((r) => [r.keys[0], int(r.clicks), int(r.impressions), pct(r.ctr), pos(r.position)])),
|
|
667
|
+
].join("\n");
|
|
668
|
+
}));
|
|
669
|
+
reg("analyze_queries", {
|
|
670
|
+
title: "Analyze search intent and topics",
|
|
671
|
+
description: "Breaks the site's queries into intents (question, comparison, commercial, transactional, local, branded, informational), shows long conversational AI-style searches, and clusters queries into topics. Use it to plan content or to see what people really ask.",
|
|
672
|
+
inputSchema: { site, range, brand: brand.describe("Regex for branded queries. Defaults to the domain name."), filter: filterSpec, examples: z.number().int().min(0).max(20).default(5) },
|
|
673
|
+
annotations: READ,
|
|
674
|
+
}, wrap(async (a) => {
|
|
675
|
+
const siteUrl = await gsc.resolveSite(a.site);
|
|
676
|
+
const r = resolveRange(a);
|
|
677
|
+
const { rows, truncated } = await gsc.queryAll(siteUrl, { ...r, dimensions: ["query"], filters: filtersOf(a), maxRows: 25_000 });
|
|
678
|
+
const brandRe = new RegExp(a.brand ?? defaultBrand(siteUrl), "i");
|
|
679
|
+
const byIntent = new Map();
|
|
680
|
+
for (const row of rows) {
|
|
681
|
+
const k = classifyQuery(row.keys[0], brandRe);
|
|
682
|
+
byIntent.set(k, [...(byIntent.get(k) ?? []), row]);
|
|
683
|
+
}
|
|
684
|
+
const agg = (rs) => {
|
|
685
|
+
const clicks = rs.reduce((x, y) => x + y.clicks, 0);
|
|
686
|
+
const impressions = rs.reduce((x, y) => x + y.impressions, 0);
|
|
687
|
+
return { clicks, impressions, ctr: impressions ? clicks / impressions : 0, position: impressions ? rs.reduce((x, y) => x + y.position * y.impressions, 0) / impressions : 0 };
|
|
688
|
+
};
|
|
689
|
+
const conv = rows.filter((x) => isConversational(x.keys[0])).sort((x, y) => y.impressions - x.impressions);
|
|
690
|
+
const convAgg = agg(conv);
|
|
691
|
+
return [
|
|
692
|
+
header(siteUrl, r, `${int(rows.length)}${truncated ? "+" : ""} queries`),
|
|
693
|
+
"",
|
|
694
|
+
"**By intent**",
|
|
695
|
+
table(["intent", "queries", "clicks", "impr", "CTR", "pos", "examples"], [...byIntent.entries()].sort((x, y) => agg(y[1]).impressions - agg(x[1]).impressions).map(([k, rs]) => {
|
|
696
|
+
const g = agg(rs);
|
|
697
|
+
return [k, int(rs.length), int(g.clicks), int(g.impressions), pct(g.ctr), pos(g.position), [...rs].sort((x, y) => y.impressions - x.impressions).slice(0, Math.min(a.examples, 3)).map((x) => x.keys[0]).join("; ")];
|
|
698
|
+
})),
|
|
699
|
+
"",
|
|
700
|
+
`**Conversational / AI-style searches**: ${int(conv.length)} queries, ${int(convAgg.impressions)} impressions, ${pct(convAgg.ctr)} CTR. These long questions are what AI Overviews answer, so pages that answer them directly and early tend to keep the click.`,
|
|
701
|
+
conv.length ? table(["query", "impr", "clicks", "pos"], conv.slice(0, a.examples * 2).map((x) => [x.keys[0], int(x.impressions), int(x.clicks), pos(x.position)])) : "",
|
|
702
|
+
"",
|
|
703
|
+
"**Topics**",
|
|
704
|
+
table(["topic", "queries", "clicks", "impr", "pos", "top queries"], clusterQueries(rows).map((c) => [c.topic, c.queries, int(c.clicks), int(c.impressions), pos(c.position), c.examples.join("; ")])),
|
|
705
|
+
].join("\n");
|
|
706
|
+
}));
|
|
707
|
+
reg("find_anomalies", {
|
|
708
|
+
title: "Find unusual days",
|
|
709
|
+
description: "Days where clicks or impressions broke sharply from the same weekday in the previous four weeks: sudden drops, spikes, or tracking gaps. Good for monitoring and 'did anything weird happen?'.",
|
|
710
|
+
inputSchema: { site, days: z.number().int().min(35).max(480).default(90).describe("How many days back to scan"), metric: z.enum(["clicks", "impressions"]).default("clicks"), threshold: z.number().min(1).max(10).default(2.5).describe("How unusual a day must be (z-score)"), filter: filterSpec },
|
|
711
|
+
annotations: READ,
|
|
712
|
+
}, wrap(async (a) => {
|
|
713
|
+
const siteUrl = await gsc.resolveSite(a.site);
|
|
714
|
+
const end = resolveRange({ range: "last7d" }).endDate;
|
|
715
|
+
const start = fmt(new Date(parse(end).getTime() - (a.days + 27) * 86_400_000));
|
|
716
|
+
const days = await gsc.query(siteUrl, { startDate: start, endDate: end, dimensions: ["date"], filters: filtersOf(a), maxRows: 1000 });
|
|
717
|
+
days.sort((x, y) => x.keys[0].localeCompare(y.keys[0]));
|
|
718
|
+
const found = anomalies(days.map((d) => ({ date: d.keys[0], value: d[a.metric] })), a.threshold);
|
|
719
|
+
const updates = await googleUpdates(gsc.fetchImpl).catch(() => []);
|
|
720
|
+
const during = (date) => updates.find((u) => date >= u.begin && date <= (u.end ?? "9999"))?.name ?? "";
|
|
721
|
+
if (!found.length)
|
|
722
|
+
return `**${siteUrl}** · last ${a.days} days to ${end}\n\nNo unusual days in ${a.metric}. Traffic moved within its normal weekly range.`;
|
|
723
|
+
return [
|
|
724
|
+
`**${siteUrl}** · last ${a.days} days to ${end} · ${found.length} unusual days in ${a.metric}`,
|
|
725
|
+
"",
|
|
726
|
+
table(["date", "weekday", a.metric, "expected", "Δ", "z", "Google update running"], found.map((x) => [x.date, new Date(x.date + "T00:00:00Z").toLocaleDateString("en-US", { weekday: "short", timeZone: "UTC" }), int(x.value), int(x.expected), delta(x.value, x.expected), x.z.toFixed(1), during(x.date)])),
|
|
727
|
+
].join("\n");
|
|
728
|
+
}));
|
|
729
|
+
reg("update_impact", {
|
|
730
|
+
title: "Google update impact",
|
|
731
|
+
description: "How each confirmed Google core, spam and other ranking update over the last 16 months affected this site: average daily clicks and position in the two weeks before it started against the two weeks after it finished.",
|
|
732
|
+
inputSchema: { site, filter: filterSpec },
|
|
733
|
+
annotations: READ,
|
|
734
|
+
}, wrap(async (a) => {
|
|
735
|
+
const siteUrl = await gsc.resolveSite(a.site);
|
|
736
|
+
const r = resolveRange({ range: "last16m" });
|
|
737
|
+
const [days, updates] = await Promise.all([gsc.query(siteUrl, { ...r, dimensions: ["date"], filters: filtersOf(a), maxRows: 1000 }), googleUpdates(gsc.fetchImpl)]);
|
|
738
|
+
const impact = updateImpact(days, updates);
|
|
739
|
+
if (!impact.length)
|
|
740
|
+
return `**${siteUrl}**\n\nNot enough data around any confirmed update to measure impact.`;
|
|
741
|
+
return [
|
|
742
|
+
`**${siteUrl}** · ${impact.length} confirmed Google updates · avg daily clicks 14 days before vs 14 days after`,
|
|
743
|
+
"",
|
|
744
|
+
table(["update", "dates", "clicks/day before", "after", "change", "pos before", "pos after"], impact.map((u) => [u.name, `${u.begin} to ${u.end ?? "ongoing"}`, int(u.before), int(u.after), signedPct(u.change), pos(u.posBefore), pos(u.posAfter)])),
|
|
745
|
+
"",
|
|
746
|
+
"Seasonality, launches and promotions also move these numbers. Treat a change under about 10% as noise unless position moved too, and ignore updates from before the site had steady traffic.",
|
|
747
|
+
].join("\n");
|
|
748
|
+
}));
|
|
749
|
+
reg("page_speed", {
|
|
750
|
+
title: "Page speed and Core Web Vitals",
|
|
751
|
+
description: "Core Web Vitals from real Chrome users (LCP, INP, CLS at the 75th percentile, pass or fail) plus a Lighthouse lab score and the biggest fixes, for one or more URLs. Takes 10 to 30 seconds per URL.",
|
|
752
|
+
inputSchema: { urls: list(z.string().url()).describe("Up to 5 URLs"), strategy: z.enum(["mobile", "desktop"]).default("mobile") },
|
|
753
|
+
annotations: READ,
|
|
754
|
+
}, wrap(async (a, extra) => {
|
|
755
|
+
if (!a.urls.length || a.urls.length > 5)
|
|
756
|
+
throw new Error("Pass between 1 and 5 URLs");
|
|
757
|
+
let n = 0;
|
|
758
|
+
const results = await mapLimit(a.urls, 3, async (u) => {
|
|
759
|
+
const r = await gsc.pageSpeed(u, a.strategy).catch((e) => e);
|
|
760
|
+
n++;
|
|
761
|
+
const token = extra._meta?.progressToken;
|
|
762
|
+
if (token !== undefined)
|
|
763
|
+
await extra.sendNotification({ method: "notifications/progress", params: { progressToken: token, progress: n, total: a.urls.length } }).catch(() => { });
|
|
764
|
+
return r;
|
|
765
|
+
});
|
|
766
|
+
const cat = (m, unit = "ms") => (m ? `${unit === "cls" ? (m.p75 / 100).toFixed(2) : unit === "s" ? (m.p75 / 1000).toFixed(1) + " s" : m.p75 + " ms"} ${m.category === "FAST" ? "good" : m.category === "AVERAGE" ? "needs work" : "poor"}` : "no data");
|
|
767
|
+
return results
|
|
768
|
+
.map((r, i) => {
|
|
769
|
+
if (r instanceof Error)
|
|
770
|
+
return `**${a.urls[i]}**\n${r.message}`;
|
|
771
|
+
const f = r.field ?? r.origin;
|
|
772
|
+
const passes = f?.lcp && f?.cls && f.lcp.category === "FAST" && f.cls.category === "FAST" && (!f.inp || f.inp.category === "FAST");
|
|
773
|
+
return [
|
|
774
|
+
`**${r.url}** · ${r.strategy} · Lighthouse ${r.score !== undefined ? Math.round(r.score * 100) : "?"}/100`,
|
|
775
|
+
f
|
|
776
|
+
? `Real users${r.field?.originFallback || !r.field ? " (whole-site data, not enough for this page)" : ""}: Core Web Vitals **${passes ? "PASS" : "FAIL"}**`
|
|
777
|
+
: "Not enough real-user traffic for Core Web Vitals; lab numbers only.",
|
|
778
|
+
f ? table(["metric", "75th percentile"], [["LCP (loading)", cat(f.lcp, "s")], ["INP (responsiveness)", cat(f.inp)], ["CLS (layout shift)", cat(f.cls, "cls")], ["TTFB (server)", cat(f.ttfb)]]) : "",
|
|
779
|
+
`Lab: LCP ${r.lab.lcp ?? "-"}, CLS ${r.lab.cls ?? "-"}, TBT ${r.lab.tbt ?? "-"}, Speed Index ${r.lab.si ?? "-"}`,
|
|
780
|
+
r.opportunities.length ? `Biggest fixes: ${r.opportunities.map((o) => `${o.title} (~${(o.savingsMs / 1000).toFixed(1)} s)`).join("; ")}` : "",
|
|
781
|
+
]
|
|
782
|
+
.filter(Boolean)
|
|
783
|
+
.join("\n");
|
|
784
|
+
})
|
|
785
|
+
.join("\n\n");
|
|
786
|
+
}));
|
|
787
|
+
// ---------------------------------------------------------------- indexing
|
|
788
|
+
reg("inspect_url", {
|
|
789
|
+
title: "Check if URLs are indexed",
|
|
790
|
+
description: "Google's index status for up to 100 URLs: indexed or not and why, last crawl, Google-chosen vs declared canonical, robots, rich results. Google allows about 2,000 inspections per property per day.",
|
|
791
|
+
inputSchema: {
|
|
792
|
+
site,
|
|
793
|
+
urls: list(z.string().url()).describe("Full URLs on the property, up to 100"),
|
|
794
|
+
languageCode: z.string().optional(),
|
|
795
|
+
},
|
|
796
|
+
annotations: READ,
|
|
797
|
+
}, wrap(async (a, extra) => {
|
|
798
|
+
if (!a.urls.length || a.urls.length > 100)
|
|
799
|
+
throw new Error("Pass between 1 and 100 URLs");
|
|
800
|
+
const siteUrl = await gsc.resolveSite(a.site ?? a.urls[0]);
|
|
801
|
+
const results = await inspectMany(gsc, siteUrl, a.urls, extra, a.languageCode);
|
|
802
|
+
return `**${siteUrl}** · ${results.length} URLs inspected, ${results.filter((x) => x.verdict !== "PASS").length} not passing\n\n${inspectionTable(results)}`;
|
|
803
|
+
}));
|
|
804
|
+
reg("audit_indexing", {
|
|
805
|
+
title: "Audit indexing from sitemaps",
|
|
806
|
+
description: "Finds pages that are in your sitemap but get no search impressions, then inspects them to show why Google is not showing them (not indexed, canonical points elsewhere, crawled but not indexed, ...).",
|
|
807
|
+
inputSchema: {
|
|
808
|
+
site,
|
|
809
|
+
sitemapUrl: z.string().url().optional().describe("Sitemap to audit. Defaults to every sitemap submitted in Search Console."),
|
|
810
|
+
inspect: z.number().int().min(0).max(100).default(20).describe("How many zero-impression URLs to inspect (each uses daily inspection quota)"),
|
|
811
|
+
},
|
|
812
|
+
annotations: READ,
|
|
813
|
+
}, wrap(async (a, extra) => {
|
|
814
|
+
const siteUrl = await gsc.resolveSite(a.site ?? a.sitemapUrl);
|
|
815
|
+
const maps = a.sitemapUrl ? [a.sitemapUrl] : (await gsc.listSitemaps(siteUrl)).map((m) => m.path);
|
|
816
|
+
if (!maps.length)
|
|
817
|
+
return `**${siteUrl}** has no submitted sitemaps. Pass sitemapUrl, or submit one in Search Console.`;
|
|
818
|
+
const errors = [];
|
|
819
|
+
const urls = new Set();
|
|
820
|
+
for (const m of maps.slice(0, 10)) {
|
|
821
|
+
try {
|
|
822
|
+
for (const u of await gsc.sitemapUrls(m))
|
|
823
|
+
urls.add(u);
|
|
824
|
+
}
|
|
825
|
+
catch (e) {
|
|
826
|
+
errors.push(e.message);
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
const r = resolveRange({ range: "last3m" });
|
|
830
|
+
const pages = await gsc.query(siteUrl, { ...r, dimensions: ["page"], maxRows: 50_000 });
|
|
831
|
+
const seen = new Set(pages.map((p) => p.keys[0]));
|
|
832
|
+
const invisible = [...urls].filter((u) => !seen.has(u));
|
|
833
|
+
const toInspect = invisible.slice(0, a.inspect);
|
|
834
|
+
const results = toInspect.length ? await inspectMany(gsc, siteUrl, toInspect, extra) : [];
|
|
835
|
+
return [
|
|
836
|
+
`**${siteUrl}** · ${maps.length} sitemap(s), ${int(urls.size)} URLs listed, ${int(invisible.length)} with zero impressions in ${r.startDate} to ${r.endDate} (${pct(urls.size ? invisible.length / urls.size : 0)}).`,
|
|
837
|
+
errors.length ? `\nCould not read: ${errors.join("; ")}` : "",
|
|
838
|
+
"",
|
|
839
|
+
results.length ? `**Inspection of ${results.length} of them**\n\n${inspectionTable(results)}` : invisible.length ? invisible.slice(0, 50).join("\n") : "Every sitemap URL is getting impressions.",
|
|
840
|
+
invisible.length > toInspect.length ? `\n${invisible.length - toInspect.length} more not inspected. Raise "inspect" to check more.` : "",
|
|
841
|
+
].join("\n");
|
|
842
|
+
}));
|
|
843
|
+
reg("list_sitemaps", {
|
|
844
|
+
title: "List sitemaps",
|
|
845
|
+
description: "Sitemaps submitted for a property, with when Google last read them, errors, warnings and how many URLs they list.",
|
|
846
|
+
inputSchema: { site },
|
|
847
|
+
annotations: READ,
|
|
848
|
+
}, wrap(async (a) => {
|
|
849
|
+
const siteUrl = await gsc.resolveSite(a.site);
|
|
850
|
+
const maps = await gsc.listSitemaps(siteUrl);
|
|
851
|
+
if (!maps.length)
|
|
852
|
+
return `**${siteUrl}** has no submitted sitemaps.`;
|
|
853
|
+
return [
|
|
854
|
+
`**${siteUrl}** · ${maps.length} sitemaps`,
|
|
855
|
+
"",
|
|
856
|
+
table(["sitemap", "last read", "status", "errors", "warnings", "URLs"], maps.map((m) => [m.path, m.lastDownloaded?.slice(0, 10) ?? "never", m.isPending ? "pending" : Number(m.errors ?? 0) > 0 ? "has errors" : Number(m.warnings ?? 0) > 0 ? "warnings" : m.isSitemapsIndex ? "index ok" : "ok", m.errors ?? "0", m.warnings ?? "0", (m.contents ?? []).map((c) => `${c.submitted ?? 0} ${c.type}`).join(", ")])),
|
|
857
|
+
].join("\n");
|
|
858
|
+
}));
|
|
859
|
+
if (!opts.writes)
|
|
860
|
+
return;
|
|
861
|
+
reg("submit_sitemap", {
|
|
862
|
+
title: "Submit a sitemap",
|
|
863
|
+
description: "Submit or resubmit a sitemap to Google. Only available when GSC_ALLOW_WRITES=1.",
|
|
864
|
+
inputSchema: { site, sitemapUrl: z.string().url() },
|
|
865
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
866
|
+
}, wrap(async (a) => {
|
|
867
|
+
const siteUrl = await gsc.resolveSite(a.site ?? a.sitemapUrl);
|
|
868
|
+
await gsc.submitSitemap(siteUrl, a.sitemapUrl);
|
|
869
|
+
return `Submitted ${a.sitemapUrl} to ${siteUrl}. Google usually reads it within hours to a few days.`;
|
|
870
|
+
}));
|
|
871
|
+
reg("delete_sitemap", {
|
|
872
|
+
title: "Remove a sitemap",
|
|
873
|
+
description: "Remove a sitemap from Search Console. The file on your server is not touched. Only available when GSC_ALLOW_WRITES=1.",
|
|
874
|
+
inputSchema: { site, sitemapUrl: z.string().url() },
|
|
875
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
876
|
+
}, wrap(async (a) => {
|
|
877
|
+
const siteUrl = await gsc.resolveSite(a.site ?? a.sitemapUrl);
|
|
878
|
+
await gsc.deleteSitemap(siteUrl, a.sitemapUrl);
|
|
879
|
+
return `Removed ${a.sitemapUrl} from ${siteUrl}.`;
|
|
880
|
+
}));
|
|
881
|
+
reg("add_site", {
|
|
882
|
+
title: "Add a property",
|
|
883
|
+
description: "Add a website to Search Console. It still has to be verified in the Search Console UI before data appears. Only available when GSC_ALLOW_WRITES=1.",
|
|
884
|
+
inputSchema: { siteUrl: z.string().describe('"https://example.com/" or "sc-domain:example.com"') },
|
|
885
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
886
|
+
}, wrap(async (a) => {
|
|
887
|
+
await gsc.addSite(a.siteUrl);
|
|
888
|
+
return `Added ${a.siteUrl}. Verify ownership at https://search.google.com/search-console to start getting data.`;
|
|
889
|
+
}));
|
|
890
|
+
reg("delete_site", {
|
|
891
|
+
title: "Remove a property",
|
|
892
|
+
description: "Remove a property from this account's Search Console. Historical data stays with Google and comes back if re-added. Only available when GSC_ALLOW_WRITES=1. Confirm with the user first.",
|
|
893
|
+
inputSchema: { site: z.string() },
|
|
894
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
895
|
+
}, wrap(async (a) => {
|
|
896
|
+
const siteUrl = await gsc.resolveSite(a.site);
|
|
897
|
+
await gsc.deleteSite(siteUrl);
|
|
898
|
+
return `Removed ${siteUrl} from this account.`;
|
|
899
|
+
}));
|
|
900
|
+
reg("request_indexing", {
|
|
901
|
+
title: "Ask Google to recrawl URLs",
|
|
902
|
+
description: "Notify Google's Indexing API that URLs changed or were removed. Google only officially supports this for job posting and livestream pages; for other pages it may be ignored. Needs a service account (or OAuth with --write) that is an Owner of the property. Only available when GSC_ALLOW_WRITES=1.",
|
|
903
|
+
inputSchema: { site, urls: list(z.string().url()).describe("Up to 100 URLs"), type: z.enum(["URL_UPDATED", "URL_DELETED"]).default("URL_UPDATED") },
|
|
904
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
905
|
+
}, wrap(async (a) => {
|
|
906
|
+
if (!a.urls.length || a.urls.length > 100)
|
|
907
|
+
throw new Error("Pass between 1 and 100 URLs");
|
|
908
|
+
const siteUrl = await gsc.resolveSite(a.site ?? a.urls[0]);
|
|
909
|
+
const results = await mapLimit(a.urls, 4, async (u) => {
|
|
910
|
+
try {
|
|
911
|
+
await gsc.requestIndexing(siteUrl, u, a.type);
|
|
912
|
+
return [u, "sent"];
|
|
913
|
+
}
|
|
914
|
+
catch (e) {
|
|
915
|
+
return [u, e.message];
|
|
916
|
+
}
|
|
917
|
+
});
|
|
918
|
+
return `Indexing API · ${results.filter((x) => x[1] === "sent").length}/${results.length} accepted (Google has a default quota of 200 per day)\n\n${table(["url", "result"], results)}`;
|
|
919
|
+
}));
|
|
920
|
+
}
|
|
921
|
+
/** Rows for the requested dimension plus a CTR curve, always fitted on query rows (pages blend too many intents). */
|
|
922
|
+
async function rowsAndCurve(gsc, siteUrl, r, dimension, f) {
|
|
923
|
+
const queries = gsc.query(siteUrl, { ...r, dimensions: ["query"], filters: f, maxRows: 25_000 });
|
|
924
|
+
const rows = dimension === "query" ? await queries : await gsc.query(siteUrl, { ...r, dimensions: [dimension], filters: f, maxRows: 25_000 });
|
|
925
|
+
const fit = buildCtrCurve(await queries);
|
|
926
|
+
return [rows, fit.curve, fit];
|
|
927
|
+
}
|
|
928
|
+
async function inspectMany(gsc, siteUrl, urls, extra, languageCode) {
|
|
929
|
+
let doneCount = 0;
|
|
930
|
+
const token = extra._meta?.progressToken;
|
|
931
|
+
return mapLimit(urls, 5, async (url) => {
|
|
932
|
+
let out;
|
|
933
|
+
try {
|
|
934
|
+
const { inspectionResult: r } = await gsc.inspect(siteUrl, url, languageCode);
|
|
935
|
+
const i = r.indexStatusResult ?? {};
|
|
936
|
+
const mismatch = i.googleCanonical && i.userCanonical && i.googleCanonical !== i.userCanonical;
|
|
937
|
+
const richIssues = (r.richResultsResult?.detectedItems ?? []).flatMap((d) => (d.items ?? []).flatMap((it) => (it.issues ?? []).map((x) => `${d.richResultType}: ${x.issueMessage}`)));
|
|
938
|
+
out = {
|
|
939
|
+
url,
|
|
940
|
+
verdict: i.verdict ?? "?",
|
|
941
|
+
coverage: i.coverageState ?? "",
|
|
942
|
+
crawled: i.lastCrawlTime?.slice(0, 10) ?? "never",
|
|
943
|
+
robots: i.robotsTxtState === "DISALLOWED" ? "BLOCKED" : i.robotsTxtState === "ALLOWED" ? "ok" : (i.robotsTxtState ?? ""),
|
|
944
|
+
canonical: mismatch ? `Google chose ${i.googleCanonical}` : i.googleCanonical ? "ok" : "",
|
|
945
|
+
rich: richIssues.length ? richIssues.slice(0, 2).join("; ") : (r.richResultsResult?.detectedItems ?? []).map((d) => d.richResultType).join(", "),
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
catch (e) {
|
|
949
|
+
out = { url, verdict: "ERROR", coverage: e.message, crawled: "", robots: "", canonical: "", rich: "" };
|
|
950
|
+
}
|
|
951
|
+
doneCount++;
|
|
952
|
+
if (token !== undefined) {
|
|
953
|
+
await extra.sendNotification({ method: "notifications/progress", params: { progressToken: token, progress: doneCount, total: urls.length, message: `Inspected ${doneCount}/${urls.length}` } }).catch(() => { });
|
|
954
|
+
}
|
|
955
|
+
return out;
|
|
956
|
+
});
|
|
957
|
+
}
|
|
958
|
+
function inspectionTable(results) {
|
|
959
|
+
return table(["url", "verdict", "coverage", "last crawl", "robots", "canonical", "rich results"], results.map((x) => [x.url, x.verdict, x.coverage, x.crawled, x.robots, x.canonical, x.rich]));
|
|
960
|
+
}
|
|
961
|
+
async function mapLimit(items, n, fn) {
|
|
962
|
+
const out = new Array(items.length);
|
|
963
|
+
let i = 0;
|
|
964
|
+
await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => {
|
|
965
|
+
while (i < items.length) {
|
|
966
|
+
const idx = i++;
|
|
967
|
+
out[idx] = await fn(items[idx]);
|
|
968
|
+
}
|
|
969
|
+
}));
|
|
970
|
+
return out;
|
|
971
|
+
}
|