@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/gsc.js
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
export class GscError extends Error {
|
|
2
|
+
status;
|
|
3
|
+
constructor(message, status) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.status = status;
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
const V3 = "https://www.googleapis.com/webmasters/v3";
|
|
9
|
+
const V1 = "https://searchconsole.googleapis.com/v1";
|
|
10
|
+
const PAGE = 25_000;
|
|
11
|
+
const PERMISSION_RANK = { siteOwner: 4, siteFullUser: 3, siteRestrictedUser: 2, siteUnverifiedUser: 0 };
|
|
12
|
+
const CACHE_TTL = 10 * 60_000;
|
|
13
|
+
const CACHE_MAX = 300;
|
|
14
|
+
export class GscClient {
|
|
15
|
+
fetchImpl;
|
|
16
|
+
sitesCache;
|
|
17
|
+
siteAuth = new Map();
|
|
18
|
+
cache = new Map();
|
|
19
|
+
source;
|
|
20
|
+
constructor(auth, fetchImpl = fetch) {
|
|
21
|
+
this.fetchImpl = fetchImpl;
|
|
22
|
+
this.source = "accounts" in auth ? auth : { accounts: async () => [{ name: "default", auth }] };
|
|
23
|
+
}
|
|
24
|
+
async authFor(siteUrl) {
|
|
25
|
+
if (siteUrl) {
|
|
26
|
+
if (!this.siteAuth.size)
|
|
27
|
+
await this.listSites().catch(() => { });
|
|
28
|
+
const a = this.siteAuth.get(siteUrl);
|
|
29
|
+
if (a)
|
|
30
|
+
return a;
|
|
31
|
+
}
|
|
32
|
+
const [first] = await this.source.accounts();
|
|
33
|
+
return first.auth;
|
|
34
|
+
}
|
|
35
|
+
async request(method, url, body, opts = {}) {
|
|
36
|
+
const auth = opts.auth ?? (await this.authFor(opts.siteUrl));
|
|
37
|
+
if (opts.cache) {
|
|
38
|
+
// Identical analytics requests are common when one prompt chains several
|
|
39
|
+
// tools; reusing them saves Google quota and makes follow-ups instant.
|
|
40
|
+
const key = `${method} ${url} ${JSON.stringify(body)} ${opts.siteUrl ?? ""}`;
|
|
41
|
+
const hit = this.cache.get(key);
|
|
42
|
+
if (hit && Date.now() - hit.at < CACHE_TTL)
|
|
43
|
+
return hit.value;
|
|
44
|
+
const value = this.send(method, url, body, auth);
|
|
45
|
+
this.cache.set(key, { at: Date.now(), value });
|
|
46
|
+
value.catch(() => this.cache.delete(key));
|
|
47
|
+
if (this.cache.size > CACHE_MAX)
|
|
48
|
+
this.cache.delete(this.cache.keys().next().value);
|
|
49
|
+
return value;
|
|
50
|
+
}
|
|
51
|
+
return this.send(method, url, body, auth);
|
|
52
|
+
}
|
|
53
|
+
async send(method, url, body, auth) {
|
|
54
|
+
for (let attempt = 0;; attempt++) {
|
|
55
|
+
const headers = await auth.headers();
|
|
56
|
+
if (body !== undefined)
|
|
57
|
+
headers.set("content-type", "application/json");
|
|
58
|
+
let res;
|
|
59
|
+
try {
|
|
60
|
+
res = await this.fetchImpl(url, {
|
|
61
|
+
method,
|
|
62
|
+
headers,
|
|
63
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
64
|
+
signal: AbortSignal.timeout(60_000),
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
catch (e) {
|
|
68
|
+
if (attempt < 2) {
|
|
69
|
+
await sleep(500 * 2 ** attempt);
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
throw new GscError(`Could not reach Google (${e.message}). Check the internet connection and retry.`, 0);
|
|
73
|
+
}
|
|
74
|
+
if ((res.status === 429 || res.status >= 500) && attempt < 3) {
|
|
75
|
+
await sleep(Number(res.headers.get("retry-after")) * 1000 || 600 * 2 ** attempt);
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
const text = await res.text();
|
|
79
|
+
if (!res.ok) {
|
|
80
|
+
let msg = text;
|
|
81
|
+
try {
|
|
82
|
+
msg = JSON.parse(text)?.error?.message ?? text;
|
|
83
|
+
}
|
|
84
|
+
catch { }
|
|
85
|
+
throw new GscError(explain(res.status, msg), res.status);
|
|
86
|
+
}
|
|
87
|
+
return (text ? JSON.parse(text) : {});
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
clearCache() {
|
|
91
|
+
this.cache.clear();
|
|
92
|
+
this.sitesCache = undefined;
|
|
93
|
+
}
|
|
94
|
+
/** Properties across every connected account. Each property is served by the account with the most access to it. */
|
|
95
|
+
async listSites(force = false) {
|
|
96
|
+
if (!force && this.sitesCache && Date.now() - this.sitesCache.at < 300_000)
|
|
97
|
+
return this.sitesCache.sites;
|
|
98
|
+
const accounts = await this.source.accounts();
|
|
99
|
+
const results = await Promise.allSettled(accounts.map((a) => this.send("GET", `${V3}/sites`, undefined, a.auth)));
|
|
100
|
+
const best = new Map();
|
|
101
|
+
results.forEach((r, i) => {
|
|
102
|
+
if (r.status !== "fulfilled")
|
|
103
|
+
return;
|
|
104
|
+
for (const s of r.value.siteEntry ?? []) {
|
|
105
|
+
const cur = best.get(s.siteUrl);
|
|
106
|
+
if (!cur || (PERMISSION_RANK[s.permissionLevel] ?? 1) > (PERMISSION_RANK[cur.permissionLevel] ?? 1)) {
|
|
107
|
+
best.set(s.siteUrl, { ...s, account: accounts.length > 1 ? accounts[i].name : undefined, auth: accounts[i].auth });
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
const failed = results.find((r) => r.status === "rejected");
|
|
112
|
+
if (!best.size && failed)
|
|
113
|
+
throw failed.reason;
|
|
114
|
+
this.siteAuth = new Map([...best.values()].map((s) => [s.siteUrl, s.auth]));
|
|
115
|
+
// GSC_ALLOWED_SITES limits which properties the assistant can see at all.
|
|
116
|
+
const allowed = (process.env.GSC_ALLOWED_SITES ?? "").split(",").map((x) => x.trim()).filter(Boolean);
|
|
117
|
+
const sites = [...best.values()]
|
|
118
|
+
.map(({ auth: _auth, ...s }) => s)
|
|
119
|
+
.filter((s) => !allowed.length || allowed.some((a) => s.siteUrl === a || bareHost(s.siteUrl) === bareHost(a)))
|
|
120
|
+
.sort((a, b) => a.siteUrl.localeCompare(b.siteUrl));
|
|
121
|
+
this.sitesCache = { at: Date.now(), sites };
|
|
122
|
+
return sites;
|
|
123
|
+
}
|
|
124
|
+
// Accepts "example.com", "https://example.com/blog/post", or an exact
|
|
125
|
+
// property and returns the property the user actually has access to.
|
|
126
|
+
// Resolution is deterministic: exact match, then the URL-prefix property
|
|
127
|
+
// that most specifically contains the URL, then the covering domain property.
|
|
128
|
+
async resolveSite(input) {
|
|
129
|
+
const sites = (await this.listSites()).filter((s) => s.permissionLevel !== "siteUnverifiedUser");
|
|
130
|
+
const wanted = input?.trim() || process.env.GSC_DEFAULT_SITE;
|
|
131
|
+
const names = () => sites.map((s) => s.siteUrl).join(", ") || "none";
|
|
132
|
+
if (!wanted) {
|
|
133
|
+
if (sites.length === 1)
|
|
134
|
+
return sites[0].siteUrl;
|
|
135
|
+
throw new Error(`Which site? This account has ${sites.length} properties: ${names()}. Pass one as "site".`);
|
|
136
|
+
}
|
|
137
|
+
const exact = sites.find((s) => s.siteUrl === wanted || s.siteUrl === wanted + "/");
|
|
138
|
+
if (exact)
|
|
139
|
+
return exact.siteUrl;
|
|
140
|
+
const asUrl = /^https?:\/\//i.test(wanted) ? wanted : null;
|
|
141
|
+
const host = bareHost(wanted);
|
|
142
|
+
if (asUrl) {
|
|
143
|
+
const prefix = sites
|
|
144
|
+
.filter((s) => !s.siteUrl.startsWith("sc-domain:") && asUrl.toLowerCase().startsWith(s.siteUrl.toLowerCase()))
|
|
145
|
+
.sort((a, b) => b.siteUrl.length - a.siteUrl.length)[0];
|
|
146
|
+
if (prefix)
|
|
147
|
+
return prefix.siteUrl;
|
|
148
|
+
}
|
|
149
|
+
// Domain properties cover every protocol and subdomain, so they win next.
|
|
150
|
+
const domain = sites
|
|
151
|
+
.filter((s) => s.siteUrl.startsWith("sc-domain:"))
|
|
152
|
+
.filter((s) => host === bareHost(s.siteUrl) || host.endsWith("." + bareHost(s.siteUrl)))
|
|
153
|
+
.sort((a, b) => b.siteUrl.length - a.siteUrl.length)[0];
|
|
154
|
+
if (domain)
|
|
155
|
+
return domain.siteUrl;
|
|
156
|
+
const sameHost = sites.filter((s) => bareHost(s.siteUrl) === host && new URL(s.siteUrl).pathname === "/");
|
|
157
|
+
if (sameHost.length) {
|
|
158
|
+
return (sameHost.find((s) => s.siteUrl.startsWith("https://www.")) ?? sameHost.find((s) => s.siteUrl.startsWith("https://")) ?? sameHost[0]).siteUrl;
|
|
159
|
+
}
|
|
160
|
+
throw new Error(`No Search Console property matches "${wanted}". This account has: ${names()}`);
|
|
161
|
+
}
|
|
162
|
+
async query(siteUrl, opts) {
|
|
163
|
+
return (await this.queryAll(siteUrl, opts)).rows;
|
|
164
|
+
}
|
|
165
|
+
async queryAll(siteUrl, opts) {
|
|
166
|
+
const max = opts.maxRows ?? 1000;
|
|
167
|
+
const rows = [];
|
|
168
|
+
let truncated = false;
|
|
169
|
+
const dims = opts.dimensions ?? [];
|
|
170
|
+
for (let startRow = 0; rows.length < max; startRow += PAGE) {
|
|
171
|
+
// Ask for one extra row on the last page so we can tell the caller
|
|
172
|
+
// whether the result was cut off, instead of silently truncating.
|
|
173
|
+
const want = max - rows.length;
|
|
174
|
+
const rowLimit = Math.min(PAGE, want + (want < PAGE ? 1 : 0));
|
|
175
|
+
const body = {
|
|
176
|
+
startDate: opts.startDate,
|
|
177
|
+
endDate: opts.endDate,
|
|
178
|
+
dimensions: dims,
|
|
179
|
+
type: opts.type ?? "web",
|
|
180
|
+
dataState: opts.dataState ?? (dims.includes("hour") ? "hourly_all" : "final"),
|
|
181
|
+
rowLimit,
|
|
182
|
+
startRow,
|
|
183
|
+
};
|
|
184
|
+
if (opts.aggregationType)
|
|
185
|
+
body.aggregationType = opts.aggregationType;
|
|
186
|
+
if (opts.filters?.length)
|
|
187
|
+
body.dimensionFilterGroups = [{ groupType: "and", filters: opts.filters }];
|
|
188
|
+
if (opts.filterLists?.length)
|
|
189
|
+
body.filterLists = opts.filterLists;
|
|
190
|
+
const data = await this.request("POST", `${V3}/sites/${encodeURIComponent(siteUrl)}/searchAnalytics/query`, body, { siteUrl, cache: true });
|
|
191
|
+
const page = (data.rows ?? []).map((r) => ({ ...r, keys: r.keys ?? [] }));
|
|
192
|
+
if (page.length > want) {
|
|
193
|
+
rows.push(...page.slice(0, want));
|
|
194
|
+
truncated = true;
|
|
195
|
+
break;
|
|
196
|
+
}
|
|
197
|
+
rows.push(...page);
|
|
198
|
+
if (page.length < rowLimit)
|
|
199
|
+
break;
|
|
200
|
+
if (rows.length >= max) {
|
|
201
|
+
// A full final page might be the exact end of the data; ask for one more row to know.
|
|
202
|
+
const probe = await this.request("POST", `${V3}/sites/${encodeURIComponent(siteUrl)}/searchAnalytics/query`, { ...body, rowLimit: 1, startRow: startRow + page.length }, { siteUrl, cache: true });
|
|
203
|
+
truncated = (probe.rows ?? []).length > 0;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return { rows, truncated };
|
|
207
|
+
}
|
|
208
|
+
/** The most recent day with any data, including not-yet-final data, so answers can say how fresh they are. */
|
|
209
|
+
async freshness(siteUrl) {
|
|
210
|
+
const end = new Date().toISOString().slice(0, 10);
|
|
211
|
+
const start = new Date(Date.now() - 10 * 86_400_000).toISOString().slice(0, 10);
|
|
212
|
+
const [all, fin] = await Promise.all(["all", "final"].map((dataState) => this.query(siteUrl, { startDate: start, endDate: end, dimensions: ["date"], dataState, maxRows: 20 })));
|
|
213
|
+
const last = (rows) => rows.map((r) => r.keys[0]).sort().pop();
|
|
214
|
+
return { latest: last(all), latestFinal: last(fin) };
|
|
215
|
+
}
|
|
216
|
+
async totals(siteUrl, opts) {
|
|
217
|
+
const [row] = await this.query(siteUrl, { ...opts, dimensions: [], maxRows: 1 });
|
|
218
|
+
return row ?? { keys: [], clicks: 0, impressions: 0, ctr: 0, position: 0 };
|
|
219
|
+
}
|
|
220
|
+
inspect(siteUrl, inspectionUrl, languageCode = "en-US") {
|
|
221
|
+
return this.request("POST", `${V1}/urlInspection/index:inspect`, { inspectionUrl, siteUrl, languageCode }, { siteUrl });
|
|
222
|
+
}
|
|
223
|
+
async listSitemaps(siteUrl) {
|
|
224
|
+
const data = await this.request("GET", `${V3}/sites/${encodeURIComponent(siteUrl)}/sitemaps`, undefined, { siteUrl });
|
|
225
|
+
return data.sitemap ?? [];
|
|
226
|
+
}
|
|
227
|
+
submitSitemap(siteUrl, feedpath) {
|
|
228
|
+
return this.request("PUT", `${V3}/sites/${encodeURIComponent(siteUrl)}/sitemaps/${encodeURIComponent(feedpath)}`, undefined, { siteUrl });
|
|
229
|
+
}
|
|
230
|
+
deleteSitemap(siteUrl, feedpath) {
|
|
231
|
+
return this.request("DELETE", `${V3}/sites/${encodeURIComponent(siteUrl)}/sitemaps/${encodeURIComponent(feedpath)}`, undefined, { siteUrl });
|
|
232
|
+
}
|
|
233
|
+
async addSite(siteUrl, account) {
|
|
234
|
+
const accounts = await this.source.accounts();
|
|
235
|
+
const auth = (account && accounts.find((a) => a.name === account)?.auth) || accounts[0].auth;
|
|
236
|
+
await this.request("PUT", `${V3}/sites/${encodeURIComponent(siteUrl)}`, undefined, { auth });
|
|
237
|
+
this.sitesCache = undefined;
|
|
238
|
+
}
|
|
239
|
+
async deleteSite(siteUrl) {
|
|
240
|
+
await this.request("DELETE", `${V3}/sites/${encodeURIComponent(siteUrl)}`, undefined, { siteUrl });
|
|
241
|
+
this.sitesCache = undefined;
|
|
242
|
+
}
|
|
243
|
+
/** Google Indexing API. Officially only for JobPosting and BroadcastEvent pages. */
|
|
244
|
+
async requestIndexing(siteUrl, url, type) {
|
|
245
|
+
return this.request("POST", "https://indexing.googleapis.com/v3/urlNotifications:publish", { url, type }, { siteUrl });
|
|
246
|
+
}
|
|
247
|
+
/** Lighthouse lab score plus real-user Core Web Vitals (CrUX) from the PageSpeed Insights API. */
|
|
248
|
+
async pageSpeed(url, strategy) {
|
|
249
|
+
const base = `https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=${encodeURIComponent(url)}&strategy=${strategy}&category=performance`;
|
|
250
|
+
const key = process.env.GSC_PAGESPEED_KEY || process.env.GOOGLE_API_KEY;
|
|
251
|
+
const attempt = async (u, headers) => {
|
|
252
|
+
const res = await this.fetchImpl(u, { headers, signal: AbortSignal.timeout(90_000) });
|
|
253
|
+
const data = (await res.json().catch(() => ({})));
|
|
254
|
+
return { ok: res.ok, status: res.status, data };
|
|
255
|
+
};
|
|
256
|
+
let r = key ? await attempt(`${base}&key=${encodeURIComponent(key)}`) : await attempt(base, await (await this.authFor(url)).headers().catch(() => undefined));
|
|
257
|
+
if (!r.ok && !key)
|
|
258
|
+
r = await attempt(base);
|
|
259
|
+
if (!r.ok) {
|
|
260
|
+
const msg = r.data?.error?.message ?? `HTTP ${r.status}`;
|
|
261
|
+
throw new Error(/quota/i.test(msg)
|
|
262
|
+
? `PageSpeed Insights quota is used up (${msg}). Get a free API key at https://developers.google.com/speed/docs/insights/v5/get-started and set GOOGLE_API_KEY in the MCP config.`
|
|
263
|
+
: `PageSpeed Insights failed: ${msg}`);
|
|
264
|
+
}
|
|
265
|
+
const d = r.data;
|
|
266
|
+
const metric = (m) => (m ? { p75: m.percentile, category: m.category } : undefined);
|
|
267
|
+
const field = (le) => le?.metrics
|
|
268
|
+
? {
|
|
269
|
+
lcp: metric(le.metrics.LARGEST_CONTENTFUL_PAINT_MS),
|
|
270
|
+
inp: metric(le.metrics.INTERACTION_TO_NEXT_PAINT),
|
|
271
|
+
cls: metric(le.metrics.CUMULATIVE_LAYOUT_SHIFT_SCORE),
|
|
272
|
+
fcp: metric(le.metrics.FIRST_CONTENTFUL_PAINT_MS),
|
|
273
|
+
ttfb: metric(le.metrics.EXPERIMENTAL_TIME_TO_FIRST_BYTE),
|
|
274
|
+
overall: le.overall_category,
|
|
275
|
+
originFallback: !!le.origin_fallback,
|
|
276
|
+
}
|
|
277
|
+
: undefined;
|
|
278
|
+
const audits = d.lighthouseResult?.audits ?? {};
|
|
279
|
+
const lab = (id) => audits[id]?.displayValue;
|
|
280
|
+
const opportunities = Object.values(audits)
|
|
281
|
+
.filter((a) => a?.details?.type === "opportunity" && typeof a.score === "number" && a.score < 0.9)
|
|
282
|
+
.sort((a, b) => (b.details.overallSavingsMs ?? 0) - (a.details.overallSavingsMs ?? 0))
|
|
283
|
+
.slice(0, 6)
|
|
284
|
+
.map((a) => ({ title: a.title, savingsMs: Math.round(a.details.overallSavingsMs ?? 0) }));
|
|
285
|
+
return {
|
|
286
|
+
url,
|
|
287
|
+
strategy,
|
|
288
|
+
score: d.lighthouseResult?.categories?.performance?.score,
|
|
289
|
+
field: field(d.loadingExperience),
|
|
290
|
+
origin: field(d.originLoadingExperience),
|
|
291
|
+
lab: { lcp: lab("largest-contentful-paint"), cls: lab("cumulative-layout-shift"), tbt: lab("total-blocking-time"), fcp: lab("first-contentful-paint"), si: lab("speed-index") },
|
|
292
|
+
opportunities,
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
/** Downloads a sitemap (following one level of sitemap index) and returns its URLs. */
|
|
296
|
+
async sitemapUrls(sitemapUrl, limit = 5000) {
|
|
297
|
+
const out = [];
|
|
298
|
+
const visit = async (url, depth) => {
|
|
299
|
+
if (out.length >= limit)
|
|
300
|
+
return;
|
|
301
|
+
const res = await this.fetchImpl(url, { headers: { "user-agent": "gsc-mcp (+https://github.com/xevrion/gsc-mcp)" } });
|
|
302
|
+
if (!res.ok)
|
|
303
|
+
throw new Error(`Could not download sitemap ${url}: HTTP ${res.status}`);
|
|
304
|
+
const xml = await res.text();
|
|
305
|
+
const locs = [...xml.matchAll(/<loc>\s*(?:<!\[CDATA\[)?(.*?)(?:\]\]>)?\s*<\/loc>/gis)].map((m) => decodeXml(m[1].trim()));
|
|
306
|
+
if (/<sitemapindex/i.test(xml)) {
|
|
307
|
+
if (depth > 0)
|
|
308
|
+
return;
|
|
309
|
+
for (const child of locs.slice(0, 20))
|
|
310
|
+
await visit(child, depth + 1);
|
|
311
|
+
}
|
|
312
|
+
else {
|
|
313
|
+
out.push(...locs.slice(0, limit - out.length));
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
await visit(sitemapUrl, 0);
|
|
317
|
+
return out;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
function sleep(ms) {
|
|
321
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
322
|
+
}
|
|
323
|
+
function decodeXml(s) {
|
|
324
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'");
|
|
325
|
+
}
|
|
326
|
+
export function bareHost(s) {
|
|
327
|
+
return s
|
|
328
|
+
.replace(/^sc-domain:/, "")
|
|
329
|
+
.replace(/^https?:\/\//, "")
|
|
330
|
+
.replace(/\/.*$/, "")
|
|
331
|
+
.replace(/^www\./, "")
|
|
332
|
+
.toLowerCase();
|
|
333
|
+
}
|
|
334
|
+
function explain(status, msg) {
|
|
335
|
+
if (status === 401)
|
|
336
|
+
return `Google rejected the credentials (401): ${msg}. Run \`npx @xevrion/gsc-mcp auth\` again.`;
|
|
337
|
+
if (status === 403)
|
|
338
|
+
return `Permission denied (403): ${msg}. Check that this account (or the service account email) is added as a user on the property in Search Console > Settings > Users and permissions, and that the Search Console API is enabled in your Google Cloud project.`;
|
|
339
|
+
if (status === 429)
|
|
340
|
+
return `Rate limited by Google (429): ${msg}. Wait a minute and retry.`;
|
|
341
|
+
return `Search Console API error ${status}: ${msg}`;
|
|
342
|
+
}
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { createServer as createHttpServer } from "node:http";
|
|
2
|
+
import { timingSafeEqual } from "node:crypto";
|
|
3
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
4
|
+
import { createServer, VERSION } from "./server.js";
|
|
5
|
+
import { GscClient } from "./gsc.js";
|
|
6
|
+
import { LazyAuth } from "./auth.js";
|
|
7
|
+
/**
|
|
8
|
+
* Streamable HTTP transport for running gsc-mcp as a shared service (a team
|
|
9
|
+
* box, Docker, a remote agent). Stateless: each request gets a fresh MCP
|
|
10
|
+
* server, while the Google client and its cache are shared.
|
|
11
|
+
*/
|
|
12
|
+
export async function serveHttp(opts) {
|
|
13
|
+
const local = opts.host === "127.0.0.1" || opts.host === "localhost" || opts.host === "::1";
|
|
14
|
+
if (!local && !opts.token)
|
|
15
|
+
throw new Error("Refusing to listen on a public interface without GSC_HTTP_TOKEN. Set a long random token, or use --host 127.0.0.1.");
|
|
16
|
+
const shared = new GscClient(new LazyAuth());
|
|
17
|
+
const expected = opts.token ? Buffer.from(`Bearer ${opts.token}`) : null;
|
|
18
|
+
const http = createHttpServer(async (req, res) => {
|
|
19
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
20
|
+
if (url.pathname === "/health") {
|
|
21
|
+
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ ok: true, version: VERSION }));
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
if (url.pathname !== "/mcp") {
|
|
25
|
+
res.writeHead(404).end();
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
if (expected) {
|
|
29
|
+
const got = Buffer.from(req.headers.authorization ?? "");
|
|
30
|
+
if (got.length !== expected.length || !timingSafeEqual(got, expected)) {
|
|
31
|
+
res.writeHead(401, { "www-authenticate": "Bearer" }).end("Unauthorized");
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
try {
|
|
36
|
+
const server = createServer(process.env.GSC_DEMO ? undefined : shared);
|
|
37
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
|
38
|
+
res.on("close", () => {
|
|
39
|
+
transport.close().catch(() => { });
|
|
40
|
+
server.close().catch(() => { });
|
|
41
|
+
});
|
|
42
|
+
await server.connect(transport);
|
|
43
|
+
let body;
|
|
44
|
+
if (req.method === "POST") {
|
|
45
|
+
const chunks = [];
|
|
46
|
+
for await (const c of req)
|
|
47
|
+
chunks.push(c);
|
|
48
|
+
body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) : undefined;
|
|
49
|
+
}
|
|
50
|
+
await transport.handleRequest(req, res, body);
|
|
51
|
+
}
|
|
52
|
+
catch (e) {
|
|
53
|
+
if (!res.headersSent)
|
|
54
|
+
res.writeHead(400, { "content-type": "application/json" }).end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32700, message: e.message }, id: null }));
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
await new Promise((resolve) => http.listen(opts.port, opts.host, resolve));
|
|
58
|
+
console.error(`gsc-mcp ${VERSION} listening on http://${opts.host}:${opts.port}/mcp${expected ? " (bearer token required)" : ""}`);
|
|
59
|
+
return http;
|
|
60
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
3
|
+
import { login, logout, readStore, resolveAuth, NotConfiguredError, profileName, configDir } from "./auth.js";
|
|
4
|
+
import { GscClient } from "./gsc.js";
|
|
5
|
+
import { createServer, isDemo, VERSION } from "./server.js";
|
|
6
|
+
import { installInto, manualConfig, targets } from "./install.js";
|
|
7
|
+
const HELP = `gsc-mcp ${VERSION} Google Search Console for Claude, Cursor and any MCP client
|
|
8
|
+
|
|
9
|
+
Usage:
|
|
10
|
+
gsc-mcp setup Guided setup: sign in with Google, then add gsc-mcp to your AI apps
|
|
11
|
+
gsc-mcp demo Add gsc-mcp to your AI apps in demo mode (fake data, no Google account)
|
|
12
|
+
gsc-mcp install Add gsc-mcp to every AI app found on this computer
|
|
13
|
+
--apps <ids> Only these, comma separated: ${targets().map((t) => t.id).join(", ")}
|
|
14
|
+
gsc-mcp Start the MCP server on stdio (what your AI app runs)
|
|
15
|
+
gsc-mcp serve --http Serve over Streamable HTTP instead (--port 3000, --host 127.0.0.1)
|
|
16
|
+
gsc-mcp tools List every tool
|
|
17
|
+
gsc-mcp run <tool> ... Run a tool from the terminal: gsc-mcp run find_opportunities --site example.com --limit 10
|
|
18
|
+
gsc-mcp auth Sign in with Google in your browser (one time)
|
|
19
|
+
--client <file> OAuth client JSON downloaded from Google Cloud
|
|
20
|
+
--write Also request permission to submit/remove sitemaps
|
|
21
|
+
--profile <name> Save under a named profile (for several Google accounts)
|
|
22
|
+
--no-browser Print the sign-in URL instead of opening it
|
|
23
|
+
gsc-mcp status Check the setup: credentials, properties, and which AI apps have it
|
|
24
|
+
gsc-mcp logout Forget the saved sign-in for the current profile
|
|
25
|
+
|
|
26
|
+
Environment:
|
|
27
|
+
GSC_SERVICE_ACCOUNT Service account key file path, or the JSON itself
|
|
28
|
+
GSC_PROFILE Saved profile to use (default "default")
|
|
29
|
+
GSC_DEFAULT_SITE Property used when a tool call does not name one
|
|
30
|
+
GSC_ALLOW_WRITES=1 Enable tools that change things (sitemaps, properties, indexing requests)
|
|
31
|
+
GSC_TOOLS Only load some tools, e.g. "core,insights" (families: core, insights, indexing, write)
|
|
32
|
+
GSC_DEMO=1 Serve realistic fake data, no Google account needed
|
|
33
|
+
GSC_HTTP_TOKEN Bearer token required by serve --http
|
|
34
|
+
|
|
35
|
+
Docs: https://github.com/xevrion/gsc-mcp`;
|
|
36
|
+
function flag(args, name) {
|
|
37
|
+
const i = args.indexOf(name);
|
|
38
|
+
return i >= 0 ? args[i + 1] : undefined;
|
|
39
|
+
}
|
|
40
|
+
async function main() {
|
|
41
|
+
const [cmd, ...args] = process.argv.slice(2);
|
|
42
|
+
if (cmd === "--help" || cmd === "-h" || cmd === "help")
|
|
43
|
+
return console.log(HELP);
|
|
44
|
+
if (cmd === "--version" || cmd === "-v")
|
|
45
|
+
return console.log(VERSION);
|
|
46
|
+
if (cmd === "auth" || cmd === "login") {
|
|
47
|
+
const res = await login({ clientFile: flag(args, "--client"), write: args.includes("--write"), profile: flag(args, "--profile"), noBrowser: args.includes("--no-browser") });
|
|
48
|
+
console.log(`\nSigned in${res.email ? ` as ${res.email}` : ""}. Saved to ${res.path} (profile "${res.profile}").`);
|
|
49
|
+
if (res.profile !== "default")
|
|
50
|
+
process.env.GSC_PROFILE = res.profile;
|
|
51
|
+
await printSites();
|
|
52
|
+
console.log("\nNext: run `npx -y @xevrion/gsc-mcp install` to add it to your AI apps.");
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
if (cmd === "setup") {
|
|
56
|
+
console.log(`\n gsc-mcp ${VERSION} setup\n Connects Google Search Console to your AI apps. Takes about 3 minutes.\n`);
|
|
57
|
+
const hasLogin = await resolveAuth().then(() => true, () => false);
|
|
58
|
+
if (hasLogin) {
|
|
59
|
+
console.log("Step 1/2 Google: already connected.");
|
|
60
|
+
await printSites();
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
console.log("Step 1/2 Connect your Google account");
|
|
64
|
+
const res = await login({ clientFile: flag(args, "--client"), write: args.includes("--write"), profile: flag(args, "--profile") });
|
|
65
|
+
console.log(`\nConnected${res.email ? ` as ${res.email}` : ""}.`);
|
|
66
|
+
await printSites();
|
|
67
|
+
}
|
|
68
|
+
console.log("\nStep 2/2 Add it to your AI apps");
|
|
69
|
+
reportInstall(installInto(clientIds(args)));
|
|
70
|
+
console.log(`\nDone. Restart your AI app, then ask it: "How is my site doing on Google?"\n`);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (cmd === "run" || cmd === "tools") {
|
|
74
|
+
const { Client } = await import("@modelcontextprotocol/sdk/client/index.js");
|
|
75
|
+
const { InMemoryTransport } = await import("@modelcontextprotocol/sdk/inMemory.js");
|
|
76
|
+
const [a, b] = InMemoryTransport.createLinkedPair();
|
|
77
|
+
const server = createServer();
|
|
78
|
+
await server.connect(b);
|
|
79
|
+
const client = new Client({ name: "gsc-mcp-cli", version: VERSION });
|
|
80
|
+
await client.connect(a);
|
|
81
|
+
if (cmd === "tools" || !args[0]) {
|
|
82
|
+
const { tools } = await client.listTools();
|
|
83
|
+
for (const t of tools)
|
|
84
|
+
console.log(`${t.name.padEnd(24)} ${(t.description ?? "").split(". ")[0]}`);
|
|
85
|
+
console.log(`\nRun one: gsc-mcp run site_overview --site example.com --range last28d`);
|
|
86
|
+
}
|
|
87
|
+
else {
|
|
88
|
+
const res = await client.callTool({ name: args[0], arguments: parseArgs(args.slice(1)) });
|
|
89
|
+
for (const c of res.content)
|
|
90
|
+
if (c.text)
|
|
91
|
+
console.log(c.text);
|
|
92
|
+
if (res.isError)
|
|
93
|
+
process.exitCode = 1;
|
|
94
|
+
}
|
|
95
|
+
await client.close();
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (cmd === "install") {
|
|
99
|
+
reportInstall(installInto(clientIds(args), args.includes("--demo") ? { GSC_DEMO: "1" } : {}));
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (cmd === "demo") {
|
|
103
|
+
console.log("Adding gsc-mcp in demo mode: it serves a realistic made-up coffee blog, so you can try every tool without a Google account.\n");
|
|
104
|
+
reportInstall(installInto(clientIds(args), { GSC_DEMO: "1" }));
|
|
105
|
+
console.log(`\nRestart your AI app and ask: "Why did my traffic drop?" When you are ready for real data, run: npx -y @xevrion/gsc-mcp setup\n`);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (cmd === "status" || cmd === "whoami" || cmd === "doctor") {
|
|
109
|
+
console.log(`gsc-mcp ${VERSION} on Node ${process.version}${Number(process.versions.node.split(".")[0]) < 20 ? " (Node 20 or newer is required)" : ""}`);
|
|
110
|
+
if (isDemo())
|
|
111
|
+
console.log("Demo mode is on (GSC_DEMO=1). Serving synthetic data.");
|
|
112
|
+
const profiles = Object.keys(readStore().profiles);
|
|
113
|
+
console.log(`Config folder: ${configDir()}`);
|
|
114
|
+
if (profiles.length)
|
|
115
|
+
console.log(`Saved Google accounts: ${profiles.join(", ")} (active: ${profileName()})`);
|
|
116
|
+
await printSites();
|
|
117
|
+
const found = targets().filter((t) => t.detected);
|
|
118
|
+
console.log(`\nAI apps found: ${found.map((t) => t.label).join(", ") || "none"}`);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
if (cmd === "logout") {
|
|
122
|
+
const name = flag(args, "--profile") ?? profileName();
|
|
123
|
+
console.log(logout(name) ? `Removed profile "${name}".` : `No saved profile "${name}".`);
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (cmd && cmd !== "serve") {
|
|
127
|
+
console.error(`Unknown command "${cmd}"\n\n${HELP}`);
|
|
128
|
+
process.exit(2);
|
|
129
|
+
}
|
|
130
|
+
if (args.includes("--http")) {
|
|
131
|
+
const { serveHttp } = await import("./http.js");
|
|
132
|
+
await serveHttp({ port: Number(flag(args, "--port") ?? process.env.PORT ?? 3000), host: flag(args, "--host") ?? process.env.HOST ?? "127.0.0.1", token: process.env.GSC_HTTP_TOKEN });
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
const server = createServer();
|
|
136
|
+
await server.connect(new StdioServerTransport());
|
|
137
|
+
console.error(`gsc-mcp ${VERSION} running on stdio${isDemo() ? " (demo mode)" : ""}`);
|
|
138
|
+
}
|
|
139
|
+
/** `--site x --limit 5 --dimensions query,page` or a single JSON object. Numbers and booleans are coerced. */
|
|
140
|
+
function parseArgs(argv) {
|
|
141
|
+
if (argv.length === 1 && argv[0].trim().startsWith("{"))
|
|
142
|
+
return JSON.parse(argv[0]);
|
|
143
|
+
const out = {};
|
|
144
|
+
for (let i = 0; i < argv.length; i++) {
|
|
145
|
+
const k = argv[i].replace(/^--/, "");
|
|
146
|
+
const next = argv[i + 1];
|
|
147
|
+
if (next === undefined || next.startsWith("--")) {
|
|
148
|
+
out[k] = true;
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
i++;
|
|
152
|
+
out[k] = /^-?\d+(\.\d+)?$/.test(next) ? Number(next) : next === "true" ? true : next === "false" ? false : next.startsWith("[") || next.startsWith("{") ? JSON.parse(next) : next;
|
|
153
|
+
}
|
|
154
|
+
return out;
|
|
155
|
+
}
|
|
156
|
+
function clientIds(args) {
|
|
157
|
+
const v = flag(args, "--apps");
|
|
158
|
+
return v ? v.split(",").map((x) => x.trim()) : "detected";
|
|
159
|
+
}
|
|
160
|
+
function reportInstall(results) {
|
|
161
|
+
if (!results.length) {
|
|
162
|
+
console.log("No AI apps found automatically. Add this to your app's MCP settings:\n");
|
|
163
|
+
console.log(manualConfig());
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
for (const r of results)
|
|
167
|
+
console.log(` ${r.ok ? "✓" : "✗"} ${r.label.padEnd(15)} ${r.where}`);
|
|
168
|
+
}
|
|
169
|
+
async function printSites() {
|
|
170
|
+
try {
|
|
171
|
+
const auth = await resolveAuth();
|
|
172
|
+
console.log(`Using ${auth.method}`);
|
|
173
|
+
const sites = await new GscClient(auth).listSites();
|
|
174
|
+
console.log(sites.length ? `\n${sites.length} properties:\n${sites.map((s) => ` ${s.siteUrl} (${s.permissionLevel})`).join("\n")}` : "\nThis account has no Search Console properties yet.");
|
|
175
|
+
}
|
|
176
|
+
catch (e) {
|
|
177
|
+
console.log(e instanceof NotConfiguredError ? e.message : `Could not reach Search Console: ${e.message}`);
|
|
178
|
+
process.exitCode = 1;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
main().catch((e) => {
|
|
182
|
+
console.error(e instanceof Error ? e.message : e);
|
|
183
|
+
process.exit(1);
|
|
184
|
+
});
|