mcp-google-search-console 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 +246 -0
- package/dist/client.js +290 -0
- package/dist/config.js +54 -0
- package/dist/index.js +69 -0
- package/dist/telemetry.js +120 -0
- package/dist/tools/analytics.js +123 -0
- package/dist/tools/inspection.js +31 -0
- package/dist/tools/raw.js +30 -0
- package/dist/tools/sitemaps.js +62 -0
- package/dist/tools/sites.js +55 -0
- package/dist/tools/util.js +65 -0
- package/dist/types.js +50 -0
- package/package.json +62 -0
- package/test/dist-smoke.test.js +129 -0
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Anonymous usage telemetry — fire-and-forget pings to usage.gistrec.cloud.
|
|
3
|
+
*
|
|
4
|
+
* Privacy contract (mirrored by the receiver): only an anonymous random
|
|
5
|
+
* instance id, event/tool names, a fixed-vocabulary failure reason and
|
|
6
|
+
* environment versions ever leave the machine. The OAuth credentials, Search
|
|
7
|
+
* Console data, tool arguments, prompts and the names or values of environment
|
|
8
|
+
* variables are never read, serialized or sent. Sends are capped at 2 s and
|
|
9
|
+
* swallow every error — telemetry must never affect the server's operation.
|
|
10
|
+
* Opt out for every server of this line at once: ASKADS_TELEMETRY=0
|
|
11
|
+
* (also accepts false/off/no).
|
|
12
|
+
*/
|
|
13
|
+
import { randomUUID } from "node:crypto";
|
|
14
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
15
|
+
import { homedir } from "node:os";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
const ENDPOINT = "https://usage.gistrec.cloud/v1/events";
|
|
18
|
+
const APP = "mcp-google-search-console";
|
|
19
|
+
const SEND_TIMEOUT_MS = 2000;
|
|
20
|
+
export function telemetryEnabled(env = process.env) {
|
|
21
|
+
const value = (env.ASKADS_TELEMETRY ?? "").trim().toLowerCase();
|
|
22
|
+
return !["0", "false", "off", "no"].includes(value);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Stable anonymous installation id, persisted under the user's config dir.
|
|
26
|
+
* Any filesystem failure degrades to an ephemeral id: the ping still counts
|
|
27
|
+
* today's activity, just not installation uniqueness across restarts.
|
|
28
|
+
*/
|
|
29
|
+
function loadInstanceId() {
|
|
30
|
+
try {
|
|
31
|
+
const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
|
|
32
|
+
const dir = join(base, APP);
|
|
33
|
+
const file = join(dir, "instance-id");
|
|
34
|
+
try {
|
|
35
|
+
const existing = readFileSync(file, "utf8").trim();
|
|
36
|
+
if (/^[0-9a-f]{8}-[0-9a-f-]{27}$/.test(existing))
|
|
37
|
+
return existing;
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
// first run — fall through and mint one
|
|
41
|
+
}
|
|
42
|
+
const id = randomUUID();
|
|
43
|
+
mkdirSync(dir, { recursive: true });
|
|
44
|
+
writeFileSync(file, `${id}\n`);
|
|
45
|
+
return id;
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return randomUUID();
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export class Telemetry {
|
|
52
|
+
appVersion;
|
|
53
|
+
enabled;
|
|
54
|
+
fetchImpl;
|
|
55
|
+
instanceId;
|
|
56
|
+
clientInfo;
|
|
57
|
+
constructor(appVersion, enabled = telemetryEnabled(), fetchImpl = fetch) {
|
|
58
|
+
this.appVersion = appVersion;
|
|
59
|
+
this.enabled = enabled;
|
|
60
|
+
this.fetchImpl = fetchImpl;
|
|
61
|
+
this.instanceId = enabled ? loadInstanceId() : "";
|
|
62
|
+
}
|
|
63
|
+
/** The MCP initialize handshake tells us which agent host is on the other side. */
|
|
64
|
+
setClientInfo(info) {
|
|
65
|
+
this.clientInfo = info;
|
|
66
|
+
}
|
|
67
|
+
/** Fire-and-forget: the server's own work never waits on a ping. */
|
|
68
|
+
send(event, fields = {}) {
|
|
69
|
+
void this.post(event, fields);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The same ping, awaited. Only for the startup_failed path: that caller
|
|
73
|
+
* calls process.exit() immediately after, which would kill an in-flight
|
|
74
|
+
* fire-and-forget request before it ever left the machine.
|
|
75
|
+
*/
|
|
76
|
+
async sendBlocking(event, fields = {}) {
|
|
77
|
+
await this.post(event, fields);
|
|
78
|
+
}
|
|
79
|
+
async post(event, fields) {
|
|
80
|
+
if (!this.enabled)
|
|
81
|
+
return;
|
|
82
|
+
const body = JSON.stringify({
|
|
83
|
+
app: APP,
|
|
84
|
+
event,
|
|
85
|
+
instance_id: this.instanceId,
|
|
86
|
+
app_version: this.appVersion,
|
|
87
|
+
client_name: this.clientInfo?.name,
|
|
88
|
+
client_version: this.clientInfo?.version,
|
|
89
|
+
tool: fields.tool,
|
|
90
|
+
reason: fields.reason,
|
|
91
|
+
node_version: process.version,
|
|
92
|
+
os: process.platform,
|
|
93
|
+
});
|
|
94
|
+
try {
|
|
95
|
+
await this.fetchImpl(ENDPOINT, {
|
|
96
|
+
method: "POST",
|
|
97
|
+
headers: { "Content-Type": "application/json" },
|
|
98
|
+
body,
|
|
99
|
+
signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
// network failure, timeout abort or a synchronous throw — all silent
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Count every tool invocation by name. Wraps registerTool once, before the
|
|
109
|
+
* domain modules register their tools, so no per-tool wiring is needed.
|
|
110
|
+
* Only the tool *name* is recorded — arguments never reach telemetry.
|
|
111
|
+
*/
|
|
112
|
+
export function instrumentToolCalls(server, telemetry) {
|
|
113
|
+
const original = server.registerTool.bind(server);
|
|
114
|
+
// registerTool's generic signature does not survive a wrapper; the runtime
|
|
115
|
+
// shape (name, config, callback) is stable per SDK contract.
|
|
116
|
+
server.registerTool = ((name, config, callback) => original(name, config, ((...args) => {
|
|
117
|
+
telemetry.send("tool_call", { tool: name });
|
|
118
|
+
return callback(...args);
|
|
119
|
+
})));
|
|
120
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { fail, ok, READ_ONLY, siteUrlSchema, ymdDate } from "./util.js";
|
|
3
|
+
export function registerAnalyticsTools(server, client) {
|
|
4
|
+
server.registerTool("search_analytics", {
|
|
5
|
+
title: "Search Analytics (performance) query",
|
|
6
|
+
annotations: READ_ONLY,
|
|
7
|
+
description: "Runs a Search Analytics (performance) query for a property: clicks, impressions, CTR and average position from Google Search, grouped by the requested dimensions. Each returned row has keys[] (one value per requested dimension, in the same order) plus clicks, impressions, ctr (a FRACTION 0..1, not a percent) and position; rows are sorted by clicks descending. With no dimensions you get one totals row for the range. Dates are calendar dates in Pacific Time and end_date is INCLUSIVE; final data lags ~2-3 days behind (use data_state \"all\" for fresh, still-changing rows). Pagination: there is no page token — repeat with start_row increased by row_limit until a response comes back with no rows. When grouping by query/page some anonymized long-tail data is never returned, so summed rows will not match a dimensionless totals query. Quota: 1,200 queries/minute per site and per user.",
|
|
8
|
+
inputSchema: {
|
|
9
|
+
site_url: siteUrlSchema(),
|
|
10
|
+
start_date: ymdDate().describe("First date of the range, YYYY-MM-DD, Pacific Time."),
|
|
11
|
+
end_date: ymdDate().describe("Last date of the range, YYYY-MM-DD, Pacific Time, inclusive."),
|
|
12
|
+
dimensions: z
|
|
13
|
+
.array(z.enum(["date", "query", "page", "country", "device", "searchAppearance", "hour"]))
|
|
14
|
+
.optional()
|
|
15
|
+
.describe('How to group rows; keys[] in each row follows this order. "country" values are ISO 3166-1 alpha-3 codes, "device" is DESKTOP/MOBILE/TABLET, "hour" requires data_state "hourly_all". Omit for one totals row.'),
|
|
16
|
+
search_type: z
|
|
17
|
+
.enum(["web", "image", "video", "news", "discover", "googleNews"])
|
|
18
|
+
.optional()
|
|
19
|
+
.describe('Which search surface to report: "web" (default), "image", "video", "news" (News tab of search), "discover" (Discover feed), "googleNews" (news.google.com and the app). discover/googleNews support a reduced dimension set — an unsupported combination returns the API\'s 400 verbatim.'),
|
|
20
|
+
filters: z
|
|
21
|
+
.array(z.object({
|
|
22
|
+
dimension: z
|
|
23
|
+
.enum(["query", "page", "country", "device", "searchAppearance"])
|
|
24
|
+
.describe("Which dimension this filter tests (need not be in the grouping dimensions)."),
|
|
25
|
+
operator: z
|
|
26
|
+
.enum(["equals", "notEquals", "contains", "notContains", "includingRegex", "excludingRegex"])
|
|
27
|
+
.describe("Comparison operator; the regex operators use RE2 syntax (an invalid regex returns a 400)."),
|
|
28
|
+
expression: z.string().describe("The value or RE2 pattern to match against."),
|
|
29
|
+
}))
|
|
30
|
+
.optional()
|
|
31
|
+
.describe("Row filters, ALL combined with AND — the API has no OR across filters (run separate queries instead)."),
|
|
32
|
+
aggregation_type: z
|
|
33
|
+
.enum(["auto", "byPage", "byProperty", "byNewsShowcasePanel"])
|
|
34
|
+
.optional()
|
|
35
|
+
.describe('How metrics are aggregated: "auto" (default) lets the API decide, "byPage"/"byProperty" force it, "byNewsShowcasePanel" is for News Showcase. Affects how clicks/impressions are counted, not which rows exist.'),
|
|
36
|
+
row_limit: z
|
|
37
|
+
.number()
|
|
38
|
+
.int()
|
|
39
|
+
.min(1)
|
|
40
|
+
.max(25000)
|
|
41
|
+
.optional()
|
|
42
|
+
.describe("Max rows to return (1..25000; API default 1000)."),
|
|
43
|
+
start_row: z
|
|
44
|
+
.number()
|
|
45
|
+
.int()
|
|
46
|
+
.min(0)
|
|
47
|
+
.optional()
|
|
48
|
+
.describe("0-based row offset for pagination (default 0). A response with no rows means the end."),
|
|
49
|
+
data_state: z
|
|
50
|
+
.enum(["final", "all", "hourly_all"])
|
|
51
|
+
.optional()
|
|
52
|
+
.describe('"final" (default) — only finalized data; "all" — include fresh data still subject to change; "hourly_all" — required when grouping by hour (recent data only).'),
|
|
53
|
+
},
|
|
54
|
+
}, async ({ site_url, start_date, end_date, dimensions, search_type, filters, aggregation_type, row_limit, start_row, data_state, }) => {
|
|
55
|
+
try {
|
|
56
|
+
return ok(await client.searchAnalytics({
|
|
57
|
+
siteUrl: site_url,
|
|
58
|
+
startDate: start_date,
|
|
59
|
+
endDate: end_date,
|
|
60
|
+
dimensions,
|
|
61
|
+
searchType: search_type,
|
|
62
|
+
filters,
|
|
63
|
+
aggregationType: aggregation_type,
|
|
64
|
+
rowLimit: row_limit,
|
|
65
|
+
startRow: start_row,
|
|
66
|
+
dataState: data_state,
|
|
67
|
+
}));
|
|
68
|
+
}
|
|
69
|
+
catch (e) {
|
|
70
|
+
return fail(e);
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
server.registerTool("get_top_queries", {
|
|
74
|
+
title: "Top search queries",
|
|
75
|
+
annotations: READ_ONLY,
|
|
76
|
+
description: "Convenience wrapper over search_analytics for the most common ask: the top search queries for a property, sorted by clicks descending (the API's default order). Each row has keys[0] = the query string plus clicks, impressions, ctr (a FRACTION 0..1) and position. Dates are calendar dates in Pacific Time, end_date inclusive; final data lags ~2-3 days. Anonymized long-tail queries are never returned. Same endpoint and quota as search_analytics — use search_analytics directly for other dimensions, pagination, fresh data or regex filters.",
|
|
77
|
+
inputSchema: {
|
|
78
|
+
site_url: siteUrlSchema(),
|
|
79
|
+
start_date: ymdDate().describe("First date of the range, YYYY-MM-DD, Pacific Time."),
|
|
80
|
+
end_date: ymdDate().describe("Last date of the range, YYYY-MM-DD, Pacific Time, inclusive."),
|
|
81
|
+
limit: z
|
|
82
|
+
.number()
|
|
83
|
+
.int()
|
|
84
|
+
.min(1)
|
|
85
|
+
.max(25000)
|
|
86
|
+
.optional()
|
|
87
|
+
.describe("How many top queries to return (1..25000; default 100)."),
|
|
88
|
+
page_filter: z
|
|
89
|
+
.string()
|
|
90
|
+
.optional()
|
|
91
|
+
.describe('Only count traffic to pages whose URL CONTAINS this substring, e.g. "/blog/".'),
|
|
92
|
+
country: z
|
|
93
|
+
.string()
|
|
94
|
+
.optional()
|
|
95
|
+
.describe('Only count traffic from this country — ISO 3166-1 alpha-3 code, e.g. "usa".'),
|
|
96
|
+
device: z
|
|
97
|
+
.enum(["DESKTOP", "MOBILE", "TABLET"])
|
|
98
|
+
.optional()
|
|
99
|
+
.describe("Only count traffic from this device class."),
|
|
100
|
+
},
|
|
101
|
+
}, async ({ site_url, start_date, end_date, limit, page_filter, country, device }) => {
|
|
102
|
+
try {
|
|
103
|
+
const filters = [];
|
|
104
|
+
if (page_filter)
|
|
105
|
+
filters.push({ dimension: "page", operator: "contains", expression: page_filter });
|
|
106
|
+
if (country)
|
|
107
|
+
filters.push({ dimension: "country", operator: "equals", expression: country });
|
|
108
|
+
if (device)
|
|
109
|
+
filters.push({ dimension: "device", operator: "equals", expression: device });
|
|
110
|
+
return ok(await client.searchAnalytics({
|
|
111
|
+
siteUrl: site_url,
|
|
112
|
+
startDate: start_date,
|
|
113
|
+
endDate: end_date,
|
|
114
|
+
dimensions: ["query"],
|
|
115
|
+
filters: filters.length > 0 ? filters : undefined,
|
|
116
|
+
rowLimit: limit ?? 100,
|
|
117
|
+
}));
|
|
118
|
+
}
|
|
119
|
+
catch (e) {
|
|
120
|
+
return fail(e);
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { fail, ok, READ_ONLY, siteUrlSchema } from "./util.js";
|
|
3
|
+
export function registerInspectionTools(server, client) {
|
|
4
|
+
server.registerTool("inspect_url", {
|
|
5
|
+
title: "Inspect a URL's index status",
|
|
6
|
+
annotations: READ_ONLY,
|
|
7
|
+
description: "Inspects a URL's status in the Google index (URL Inspection API). Returns { inspectionResult } with: inspectionResultLink (the Search Console UI page for this inspection); indexStatusResult — verdict (PASS/PARTIAL/FAIL/NEUTRAL), human-readable coverageState (e.g. \"Submitted and indexed\"), robotsTxtState (ALLOWED/DISALLOWED), indexingState, lastCrawlTime, pageFetchState (SUCCESSFUL/SOFT_404/NOT_FOUND/SERVER_ERROR/...), googleCanonical vs userCanonical, sitemap[], referringUrls[], crawledAs (DESKTOP/MOBILE); plus ampResult and richResultsResult (with per-item issues and severities) when applicable. Only the status of the version already in the Google index is returned — this is NOT a live test. mobileUsabilityResult may still appear in responses but the product is retired — ignore it. QUOTA WARNING: only 2,000 inspections per property per DAY (and 600/minute) — throttle any batch inspection and expect 429/403 rateLimitExceeded beyond that.",
|
|
8
|
+
inputSchema: {
|
|
9
|
+
inspection_url: z
|
|
10
|
+
.string()
|
|
11
|
+
.min(1)
|
|
12
|
+
.describe("The fully-qualified URL to inspect. It must belong to the property given in site_url."),
|
|
13
|
+
site_url: siteUrlSchema(),
|
|
14
|
+
language_code: z
|
|
15
|
+
.string()
|
|
16
|
+
.optional()
|
|
17
|
+
.describe('IETF BCP-47 language for the human-readable issue messages, e.g. "en-US" (the default).'),
|
|
18
|
+
},
|
|
19
|
+
}, async ({ inspection_url, site_url, language_code }) => {
|
|
20
|
+
try {
|
|
21
|
+
return ok(await client.inspectUrl({
|
|
22
|
+
inspectionUrl: inspection_url,
|
|
23
|
+
siteUrl: site_url,
|
|
24
|
+
languageCode: language_code,
|
|
25
|
+
}));
|
|
26
|
+
}
|
|
27
|
+
catch (e) {
|
|
28
|
+
return fail(e);
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { fail, ok, RAW } from "./util.js";
|
|
3
|
+
export function registerRawTool(server, client) {
|
|
4
|
+
server.registerTool("raw_request", {
|
|
5
|
+
title: "Raw Search Console API call",
|
|
6
|
+
// Arbitrary method/path incl. DELETE — annotate for the worst case a call
|
|
7
|
+
// can do, not the average.
|
|
8
|
+
annotations: RAW,
|
|
9
|
+
description: 'Escape hatch to call any Google Search Console API path directly, for requests the typed tools don\'t cover. Two surfaces share the host: "webmasters/v3/..." (sites, sitemaps, searchAnalytics) and "v1/..." (urlInspection). siteUrl and feedpath are PATH SEGMENTS and must be URL-encoded (encodeURIComponent), e.g. "webmasters/v3/sites/sc-domain%3Aexample.com/sitemaps". The path may carry a query string. The Bearer token is added automatically; the method defaults to GET. Note: sites.add and sitemaps.submit are PUT with no body and return an empty response on success.',
|
|
10
|
+
inputSchema: {
|
|
11
|
+
path: z
|
|
12
|
+
.string()
|
|
13
|
+
.min(1)
|
|
14
|
+
.describe('API path relative to https://searchconsole.googleapis.com, e.g. "webmasters/v3/sites" or "v1/urlInspection/index:inspect".'),
|
|
15
|
+
method: z
|
|
16
|
+
.enum(["GET", "POST", "PUT", "DELETE"])
|
|
17
|
+
.optional()
|
|
18
|
+
.describe("HTTP method (the Search Console API uses only these four). Defaults to GET."),
|
|
19
|
+
body: z.record(z.any()).optional().describe("JSON request body (POST only; PUT endpoints here take no body)."),
|
|
20
|
+
},
|
|
21
|
+
}, async ({ path, method, body }) => {
|
|
22
|
+
try {
|
|
23
|
+
const m = (method ?? "GET");
|
|
24
|
+
return ok((await client.request(m, path, body)) ?? { ok: true });
|
|
25
|
+
}
|
|
26
|
+
catch (e) {
|
|
27
|
+
return fail(e);
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { DESTRUCTIVE, fail, feedpathSchema, ok, READ_ONLY, siteUrlSchema, WRITE } from "./util.js";
|
|
3
|
+
export function registerSitemapTools(server, client) {
|
|
4
|
+
server.registerTool("list_sitemaps", {
|
|
5
|
+
title: "List sitemaps",
|
|
6
|
+
annotations: READ_ONLY,
|
|
7
|
+
description: "Lists the sitemaps submitted for a property (or, with sitemap_index, the children of a sitemap index file). Returns { sitemap: [WmxSitemap] } with per-sitemap path, lastSubmitted, lastDownloaded, isPending, isSitemapsIndex, type (sitemap/rssFeed/atomFeed/patternSitemap/urlList/notSitemap), warnings and errors counts, and contents[] with per-content-type submitted counts. The contents[].indexed field is deprecated and returns nothing useful — never present it as indexed pages.",
|
|
8
|
+
inputSchema: {
|
|
9
|
+
site_url: siteUrlSchema(),
|
|
10
|
+
sitemap_index: z
|
|
11
|
+
.string()
|
|
12
|
+
.optional()
|
|
13
|
+
.describe("URL of a sitemap index file — lists its child sitemaps instead of the property's own list."),
|
|
14
|
+
},
|
|
15
|
+
}, async ({ site_url, sitemap_index }) => {
|
|
16
|
+
try {
|
|
17
|
+
return ok(await client.listSitemaps(site_url, sitemap_index));
|
|
18
|
+
}
|
|
19
|
+
catch (e) {
|
|
20
|
+
return fail(e);
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
server.registerTool("get_sitemap", {
|
|
24
|
+
title: "Get one sitemap",
|
|
25
|
+
annotations: READ_ONLY,
|
|
26
|
+
description: "Returns one submitted sitemap's details (the same WmxSitemap shape as list_sitemaps): errors/warnings counts, isPending, lastSubmitted/lastDownloaded, and per-content-type submitted counts. Useful to check processing status after submit_sitemap.",
|
|
27
|
+
inputSchema: { site_url: siteUrlSchema(), feedpath: feedpathSchema() },
|
|
28
|
+
}, async ({ site_url, feedpath }) => {
|
|
29
|
+
try {
|
|
30
|
+
return ok(await client.getSitemap(site_url, feedpath));
|
|
31
|
+
}
|
|
32
|
+
catch (e) {
|
|
33
|
+
return fail(e);
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
server.registerTool("submit_sitemap", {
|
|
37
|
+
title: "Submit a sitemap",
|
|
38
|
+
annotations: WRITE,
|
|
39
|
+
description: "Submits (or resubmits) a sitemap for the property. The feedpath must be the sitemap's full URL on the property. Success is an EMPTY API response (surfaced as { ok: true, submitted }); processing is asynchronous — check errors/warnings later with get_sitemap. Requires the full webmasters OAuth scope (readonly is not enough).",
|
|
40
|
+
inputSchema: { site_url: siteUrlSchema(), feedpath: feedpathSchema() },
|
|
41
|
+
}, async ({ site_url, feedpath }) => {
|
|
42
|
+
try {
|
|
43
|
+
return ok(await client.submitSitemap(site_url, feedpath));
|
|
44
|
+
}
|
|
45
|
+
catch (e) {
|
|
46
|
+
return fail(e);
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
server.registerTool("delete_sitemap", {
|
|
50
|
+
title: "Delete a sitemap",
|
|
51
|
+
annotations: DESTRUCTIVE,
|
|
52
|
+
description: "Removes a sitemap from Search Console. This does not delete the file from the site, and Google may still discover it via robots.txt — it only removes the submission. Success is an empty API response (surfaced as { ok: true, deleted }). Requires the full webmasters OAuth scope.",
|
|
53
|
+
inputSchema: { site_url: siteUrlSchema(), feedpath: feedpathSchema() },
|
|
54
|
+
}, async ({ site_url, feedpath }) => {
|
|
55
|
+
try {
|
|
56
|
+
return ok(await client.deleteSitemap(site_url, feedpath));
|
|
57
|
+
}
|
|
58
|
+
catch (e) {
|
|
59
|
+
return fail(e);
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { DESTRUCTIVE, fail, ok, READ_ONLY, siteUrlSchema, WRITE } from "./util.js";
|
|
2
|
+
export function registerSiteTools(server, client) {
|
|
3
|
+
server.registerTool("list_sites", {
|
|
4
|
+
title: "List Search Console properties",
|
|
5
|
+
annotations: READ_ONLY,
|
|
6
|
+
description: 'Lists every Search Console property the authenticated account can access. Returns { siteEntry: [{ siteUrl, permissionLevel }] } where siteUrl is either a URL-prefix property ("https://example.com/") or a domain property ("sc-domain:example.com"), and permissionLevel is siteOwner, siteFullUser, siteRestrictedUser or siteUnverifiedUser. Call this FIRST: every other tool needs the siteUrl exactly as returned here — a near-match (missing trailing slash, wrong scheme, www vs non-www) is a different property and returns 403/404.',
|
|
7
|
+
inputSchema: {},
|
|
8
|
+
}, async () => {
|
|
9
|
+
try {
|
|
10
|
+
return ok(await client.listSites());
|
|
11
|
+
}
|
|
12
|
+
catch (e) {
|
|
13
|
+
return fail(e);
|
|
14
|
+
}
|
|
15
|
+
});
|
|
16
|
+
server.registerTool("get_site", {
|
|
17
|
+
title: "Get one property",
|
|
18
|
+
annotations: READ_ONLY,
|
|
19
|
+
description: "Returns one property's entry: { siteUrl, permissionLevel }. A 404 means the value does not match any registered property — check the exact format (trailing slash, scheme, sc-domain: prefix) against list_sites output.",
|
|
20
|
+
inputSchema: { site_url: siteUrlSchema() },
|
|
21
|
+
}, async ({ site_url }) => {
|
|
22
|
+
try {
|
|
23
|
+
return ok(await client.getSite(site_url));
|
|
24
|
+
}
|
|
25
|
+
catch (e) {
|
|
26
|
+
return fail(e);
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
server.registerTool("add_site", {
|
|
30
|
+
title: "Add a property",
|
|
31
|
+
annotations: WRITE,
|
|
32
|
+
description: 'Adds a property to the account\'s Search Console set. The property starts UNVERIFIED (permissionLevel siteUnverifiedUser) and most data calls will return 403 until it is verified — verification happens through the Search Console UI or the separate Site Verification API, not through this API. Success is an empty API response (surfaced as { ok: true, added }). Requires the full webmasters OAuth scope (the readonly scope cannot mutate).',
|
|
33
|
+
inputSchema: { site_url: siteUrlSchema() },
|
|
34
|
+
}, async ({ site_url }) => {
|
|
35
|
+
try {
|
|
36
|
+
return ok(await client.addSite(site_url));
|
|
37
|
+
}
|
|
38
|
+
catch (e) {
|
|
39
|
+
return fail(e);
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
server.registerTool("delete_site", {
|
|
43
|
+
title: "Remove a property",
|
|
44
|
+
annotations: DESTRUCTIVE,
|
|
45
|
+
description: "Removes (unlinks) a property from the account's Search Console set. No data is deleted and other owners keep their access — this only removes the property from THIS account's list; it can be re-added later. Success is an empty API response (surfaced as { ok: true, removed }). Requires the full webmasters OAuth scope.",
|
|
46
|
+
inputSchema: { site_url: siteUrlSchema() },
|
|
47
|
+
}, async ({ site_url }) => {
|
|
48
|
+
try {
|
|
49
|
+
return ok(await client.deleteSite(site_url));
|
|
50
|
+
}
|
|
51
|
+
catch (e) {
|
|
52
|
+
return fail(e);
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/**
|
|
3
|
+
* Schema factories, not shared consts: reusing one zod object across two fields
|
|
4
|
+
* makes zod-to-json-schema dedupe them into a `$ref`, which some tool-schema
|
|
5
|
+
* consumers (OpenAI Apps review) don't dereference and flag as `any`. A fresh
|
|
6
|
+
* object per field keeps each one inlined with its type + pattern.
|
|
7
|
+
*/
|
|
8
|
+
/** The property identifier — the #1 user error in this API, so spell out both formats. */
|
|
9
|
+
export const siteUrlSchema = () => z
|
|
10
|
+
.string()
|
|
11
|
+
.min(1)
|
|
12
|
+
.describe('The property EXACTLY as registered in Search Console. Two formats: URL-prefix — a full URL with scheme and trailing slash, e.g. "https://example.com/" (http/https and www/non-www are different properties), or domain property — "sc-domain:example.com" (no scheme, no slash). A mismatched value returns 403/404; list_sites shows the exact registered values.');
|
|
13
|
+
/** A sitemap URL — a full URL, sent URL-encoded as a path segment by the client. */
|
|
14
|
+
export const feedpathSchema = () => z.string().min(1).describe('The full sitemap URL, e.g. "https://example.com/sitemap.xml".');
|
|
15
|
+
/** A YYYY-MM-DD date — Search Analytics dates are calendar dates in Pacific Time. */
|
|
16
|
+
export const ymdDate = () => z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Must be a YYYY-MM-DD date");
|
|
17
|
+
/** Wraps a value as a compact-JSON tool result (compact: the consumer is an LLM). */
|
|
18
|
+
export function ok(data) {
|
|
19
|
+
const text = typeof data === "string" ? data : JSON.stringify(data);
|
|
20
|
+
return { content: [{ type: "text", text: text ?? "null" }] };
|
|
21
|
+
}
|
|
22
|
+
export function fail(err) {
|
|
23
|
+
let message = err instanceof Error ? err.message : String(err);
|
|
24
|
+
// Surface the underlying cause (e.g. the network error behind a timeout) — no
|
|
25
|
+
// secrets live in cause, and it makes failures far easier to diagnose.
|
|
26
|
+
if (err instanceof Error && err.cause instanceof Error)
|
|
27
|
+
message += ` (${err.cause.message})`;
|
|
28
|
+
return { content: [{ type: "text", text: `Error: ${message}` }], isError: true };
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* MCP tool annotations — hints the consuming client can use to gate or label a
|
|
32
|
+
* tool. All four hints are set explicitly on every tool: some clients (OpenAI
|
|
33
|
+
* Apps review) require readOnlyHint, destructiveHint and openWorldHint on each.
|
|
34
|
+
*
|
|
35
|
+
* The Search Console API is mostly reads plus a few idempotent mutations, so
|
|
36
|
+
* each tool picks one of four presets: READ_ONLY (pure reads — most tools),
|
|
37
|
+
* WRITE (add_site / submit_sitemap: PUT with no body, replaying the same call
|
|
38
|
+
* converges), DESTRUCTIVE (delete_site / delete_sitemap: removes state, but a
|
|
39
|
+
* replay of the same call is a no-op, hence idempotent) and RAW (raw_request:
|
|
40
|
+
* arbitrary method/path — annotated for the worst case, not the average).
|
|
41
|
+
*/
|
|
42
|
+
export const READ_ONLY = {
|
|
43
|
+
readOnlyHint: true,
|
|
44
|
+
destructiveHint: false,
|
|
45
|
+
idempotentHint: true,
|
|
46
|
+
openWorldHint: true,
|
|
47
|
+
};
|
|
48
|
+
export const WRITE = {
|
|
49
|
+
readOnlyHint: false,
|
|
50
|
+
destructiveHint: false,
|
|
51
|
+
idempotentHint: true,
|
|
52
|
+
openWorldHint: true,
|
|
53
|
+
};
|
|
54
|
+
export const DESTRUCTIVE = {
|
|
55
|
+
readOnlyHint: false,
|
|
56
|
+
destructiveHint: true,
|
|
57
|
+
idempotentHint: true,
|
|
58
|
+
openWorldHint: true,
|
|
59
|
+
};
|
|
60
|
+
export const RAW = {
|
|
61
|
+
readOnlyHint: false,
|
|
62
|
+
destructiveHint: true,
|
|
63
|
+
idempotentHint: false,
|
|
64
|
+
openWorldHint: true,
|
|
65
|
+
};
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The server talks to the Google Search Console API
|
|
3
|
+
* (https://searchconsole.googleapis.com), which serves two surfaces on one
|
|
4
|
+
* host: webmasters/v3 (sites, sitemaps, searchanalytics) and v1
|
|
5
|
+
* (urlInspection). Auth is Google OAuth 2.0: a Bearer access token, minted on
|
|
6
|
+
* demand from a refresh token via https://oauth2.googleapis.com/token (or a
|
|
7
|
+
* static short-lived access token, mostly for testing). An API key is never
|
|
8
|
+
* enough — every method operates on the caller's verified properties.
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* Google APIs report failures as a non-2xx HTTP status with a JSON envelope —
|
|
12
|
+
* for this API `{ error: { code, message, errors: [{ reason, ... }] } }`; the
|
|
13
|
+
* OAuth token endpoint uses `{ error, error_description }`. The parsed body is
|
|
14
|
+
* kept alongside the status and a short readable message is derived, surfacing
|
|
15
|
+
* the first machine-readable `reason` (e.g. quotaExceeded, forbidden).
|
|
16
|
+
*/
|
|
17
|
+
export class GoogleSearchConsoleError extends Error {
|
|
18
|
+
status;
|
|
19
|
+
body;
|
|
20
|
+
constructor(status, body) {
|
|
21
|
+
super(`HTTP ${status}: ${formatErrorBody(body)}`);
|
|
22
|
+
this.name = "GoogleSearchConsoleError";
|
|
23
|
+
this.status = status;
|
|
24
|
+
this.body = body;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** Turns a parsed Google API error body into a short, readable message. */
|
|
28
|
+
function formatErrorBody(body) {
|
|
29
|
+
if (body == null)
|
|
30
|
+
return "(no body)";
|
|
31
|
+
if (typeof body === "string")
|
|
32
|
+
return body.slice(0, 500);
|
|
33
|
+
if (typeof body !== "object")
|
|
34
|
+
return String(body);
|
|
35
|
+
const obj = body;
|
|
36
|
+
// OAuth token endpoint style: { error: "invalid_grant", error_description: "..." }
|
|
37
|
+
if (typeof obj.error === "string") {
|
|
38
|
+
const description = typeof obj.error_description === "string" ? `: ${obj.error_description}` : "";
|
|
39
|
+
return `${obj.error}${description}`.slice(0, 500);
|
|
40
|
+
}
|
|
41
|
+
// Google API envelope: { error: { code, message, errors: [{ reason, ... }], status? } }
|
|
42
|
+
const err = (typeof obj.error === "object" && obj.error !== null ? obj.error : obj);
|
|
43
|
+
if (typeof err.message === "string") {
|
|
44
|
+
const first = Array.isArray(err.errors) ? err.errors[0] : undefined;
|
|
45
|
+
const reason = typeof first?.reason === "string" ? first.reason : typeof err.status === "string" ? err.status : undefined;
|
|
46
|
+
const tag = reason ? `[${reason}] ` : "";
|
|
47
|
+
return `${tag}${err.message}`.slice(0, 500);
|
|
48
|
+
}
|
|
49
|
+
return JSON.stringify(obj).slice(0, 500);
|
|
50
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "mcp-google-search-console",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "MCP server for the Google Search Console API — search analytics, sitemaps, URL inspection and site management. For Claude, Cursor, Codex and other AI clients.",
|
|
5
|
+
"mcpName": "io.github.A1-x-Tech/mcp-google-search-console",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"mcp-google-search-console": "dist/index.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist",
|
|
12
|
+
"test"
|
|
13
|
+
],
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=20"
|
|
16
|
+
},
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "rm -rf dist && tsc",
|
|
19
|
+
"start": "node dist/index.js",
|
|
20
|
+
"dev": "tsx watch src/index.ts",
|
|
21
|
+
"typecheck": "tsc -p tsconfig.check.json",
|
|
22
|
+
"smoke": "node --import tsx src/smoke.ts",
|
|
23
|
+
"test": "npm run test:src && npm run test:dist",
|
|
24
|
+
"test:src": "node --import tsx --test $(find src -name '*.test.ts')",
|
|
25
|
+
"test:dist": "npm run build && node --test test/dist-smoke.test.js",
|
|
26
|
+
"prepare": "npm run build",
|
|
27
|
+
"prepublishOnly": "npm run typecheck && npm test"
|
|
28
|
+
},
|
|
29
|
+
"keywords": [
|
|
30
|
+
"mcp",
|
|
31
|
+
"model-context-protocol",
|
|
32
|
+
"google",
|
|
33
|
+
"search-console",
|
|
34
|
+
"gsc",
|
|
35
|
+
"seo",
|
|
36
|
+
"search-analytics",
|
|
37
|
+
"url-inspection",
|
|
38
|
+
"sitemaps",
|
|
39
|
+
"claude",
|
|
40
|
+
"cursor",
|
|
41
|
+
"codex"
|
|
42
|
+
],
|
|
43
|
+
"license": "MIT",
|
|
44
|
+
"author": "gistrec <gistrec@gmail.com>",
|
|
45
|
+
"repository": {
|
|
46
|
+
"type": "git",
|
|
47
|
+
"url": "git+https://github.com/A1-x-Tech/mcp-google-search-console.git"
|
|
48
|
+
},
|
|
49
|
+
"homepage": "https://github.com/A1-x-Tech/mcp-google-search-console#readme",
|
|
50
|
+
"bugs": {
|
|
51
|
+
"url": "https://github.com/A1-x-Tech/mcp-google-search-console/issues"
|
|
52
|
+
},
|
|
53
|
+
"dependencies": {
|
|
54
|
+
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
55
|
+
"zod": "^3.25.0"
|
|
56
|
+
},
|
|
57
|
+
"devDependencies": {
|
|
58
|
+
"@types/node": "^25.9.3",
|
|
59
|
+
"tsx": "^4.22.4",
|
|
60
|
+
"typescript": "^5.7.0"
|
|
61
|
+
}
|
|
62
|
+
}
|