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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 A1 x Tech
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,246 @@
1
+ # Google Search Console MCP
2
+
3
+ [![npm](https://img.shields.io/npm/v/mcp-google-search-console)](https://www.npmjs.com/package/mcp-google-search-console)
4
+ [![CI](https://github.com/A1-x-Tech/mcp-google-search-console/actions/workflows/ci.yml/badge.svg)](https://github.com/A1-x-Tech/mcp-google-search-console/actions/workflows/ci.yml)
5
+ [![Glama](https://glama.ai/mcp/servers/A1-x-Tech/mcp-google-search-console/badges/score.svg)](https://glama.ai/mcp/servers/A1-x-Tech/mcp-google-search-console)
6
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
7
+
8
+ MCP server for the **Google Search Console API**: search performance analytics
9
+ (clicks, impressions, CTR, position), sitemap management, URL index inspection
10
+ and property management — from Claude, Cursor, Codex and other AI clients, in
11
+ natural language.
12
+
13
+ Ask your assistant "which queries brought the most clicks last month?", "is this
14
+ page indexed?", or "resubmit the sitemap" — it drives the Search Console API for
15
+ you, from a quick indexing check to a full performance analysis.
16
+
17
+ ## Quick start
18
+
19
+ 1. [Get OAuth credentials](#getting-credentials) for the Search Console API.
20
+ 2. Add the server — for example, in Claude Code ([other clients](#installation)):
21
+
22
+ ```bash
23
+ claude mcp add google-search-console \
24
+ -e GOOGLE_SEARCH_CONSOLE_CLIENT_ID=your_client_id \
25
+ -e GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET=your_client_secret \
26
+ -e GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN=your_refresh_token \
27
+ -- npx -y mcp-google-search-console
28
+ ```
29
+
30
+ 3. Ask the assistant: *"Show me the top 20 search queries for example.com over
31
+ the last 28 days, with clicks and CTR."*
32
+
33
+ ## Tools
34
+
35
+ | Tool | Description |
36
+ |---|---|
37
+ | `list_sites` | All Search Console properties the account can access, with permission levels. |
38
+ | `get_site` | One property's entry (siteUrl + permissionLevel). |
39
+ | `add_site` | Add a property (stays unverified until verified in Search Console). |
40
+ | `delete_site` | Unlink a property from the account (no data is deleted). |
41
+ | `search_analytics` | Performance query: clicks/impressions/CTR/position by date, query, page, country, device, search appearance or hour; filters, search type, pagination, fresh-data mode. |
42
+ | `get_top_queries` | Shortcut for the most common ask: top queries by clicks, optionally filtered by page substring, country or device. |
43
+ | `list_sitemaps` | Submitted sitemaps (or children of a sitemap index), with errors/warnings. |
44
+ | `get_sitemap` | One sitemap's status and per-content-type counts. |
45
+ | `submit_sitemap` | Submit or resubmit a sitemap. |
46
+ | `delete_sitemap` | Remove a sitemap from Search Console. |
47
+ | `inspect_url` | Google-index status of a URL: verdict, coverage, crawl info, canonicals, rich results. |
48
+ | `raw_request` | Escape hatch: any Search Console API path (webmasters/v3 or v1). |
49
+
50
+ Plus resilience built in: automatic OAuth token refresh (including on 401),
51
+ retries with backoff on 429 (and on 5xx/network errors for reads only —
52
+ mutations are never replayed), a request timeout, and an SSRF guard so the
53
+ token can't leak to a foreign host.
54
+
55
+ ## Example prompts
56
+
57
+ - "Which pages lost the most clicks this month compared to the previous one?"
58
+ - "Is https://example.com/pricing indexed? If not, why?"
59
+ - "List queries containing 'mcp' where we rank below position 10."
60
+ - "Do any of our sitemaps have errors? Resubmit the ones that do."
61
+
62
+ ## Two property formats (the #1 pitfall)
63
+
64
+ The `site_url` must match the property **exactly** as registered in Search Console:
65
+
66
+ - **URL-prefix property** — full URL with scheme and trailing slash:
67
+ `https://example.com/`. Note `http://example.com/`, `https://example.com/`
68
+ and `https://www.example.com/` are three **different** properties.
69
+ - **Domain property** — `sc-domain:example.com` (no scheme, no slash).
70
+
71
+ A near-match returns 403/404. `list_sites` shows the exact registered values —
72
+ the assistant will usually call it first.
73
+
74
+ ## Limitations (the API's, not the server's)
75
+
76
+ - **Dates are in Pacific Time** and `end_date` is inclusive; final analytics
77
+ data lags ~2–3 days (pass `data_state: "all"` for fresh, still-changing rows).
78
+ - **Filters are AND-only** — no OR across filters; regex operators use RE2 syntax.
79
+ - **URL inspection quota is small**: 2,000 inspections per property per day
80
+ (600/minute) — don't batch-inspect entire sites.
81
+ - **Search analytics**: max 25,000 rows per request (paginate with `start_row`);
82
+ anonymized long-tail queries are never returned.
83
+ - **Verification is out of scope**: `add_site` registers a property, but
84
+ verification happens in the Search Console UI or the Site Verification API.
85
+
86
+ ## Installation
87
+
88
+ Requires Node.js 20+ (runs via `npx`, no separate install).
89
+
90
+ <details open>
91
+ <summary><b>Claude Code</b></summary>
92
+
93
+ ```bash
94
+ claude mcp add google-search-console \
95
+ -e GOOGLE_SEARCH_CONSOLE_CLIENT_ID=your_client_id \
96
+ -e GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET=your_client_secret \
97
+ -e GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN=your_refresh_token \
98
+ -- npx -y mcp-google-search-console
99
+ ```
100
+
101
+ </details>
102
+
103
+ <details>
104
+ <summary><b>Claude Desktop</b></summary>
105
+
106
+ `claude_desktop_config.json` — macOS `~/Library/Application Support/Claude/`, Windows `%APPDATA%\Claude\`
107
+
108
+ ```json
109
+ {
110
+ "mcpServers": {
111
+ "google-search-console": {
112
+ "command": "npx",
113
+ "args": ["-y", "mcp-google-search-console"],
114
+ "env": {
115
+ "GOOGLE_SEARCH_CONSOLE_CLIENT_ID": "your_client_id",
116
+ "GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET": "your_client_secret",
117
+ "GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN": "your_refresh_token"
118
+ }
119
+ }
120
+ }
121
+ }
122
+ ```
123
+
124
+ </details>
125
+
126
+ <details>
127
+ <summary><b>Cursor</b></summary>
128
+
129
+ `~/.cursor/mcp.json` (or `.cursor/mcp.json` in the project)
130
+
131
+ ```json
132
+ {
133
+ "mcpServers": {
134
+ "google-search-console": {
135
+ "command": "npx",
136
+ "args": ["-y", "mcp-google-search-console"],
137
+ "env": {
138
+ "GOOGLE_SEARCH_CONSOLE_CLIENT_ID": "your_client_id",
139
+ "GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET": "your_client_secret",
140
+ "GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN": "your_refresh_token"
141
+ }
142
+ }
143
+ }
144
+ }
145
+ ```
146
+
147
+ </details>
148
+
149
+ <details>
150
+ <summary><b>VS Code</b></summary>
151
+
152
+ `.vscode/mcp.json` — note the `servers` key (not `mcpServers`)
153
+
154
+ ```json
155
+ {
156
+ "servers": {
157
+ "google-search-console": {
158
+ "type": "stdio",
159
+ "command": "npx",
160
+ "args": ["-y", "mcp-google-search-console"],
161
+ "env": {
162
+ "GOOGLE_SEARCH_CONSOLE_CLIENT_ID": "your_client_id",
163
+ "GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET": "your_client_secret",
164
+ "GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN": "your_refresh_token"
165
+ }
166
+ }
167
+ }
168
+ }
169
+ ```
170
+
171
+ </details>
172
+
173
+ ## Getting credentials
174
+
175
+ The Search Console API has no API-key access — every call needs OAuth 2.0 (the
176
+ data belongs to your account). One-time setup, ~10 minutes:
177
+
178
+ 1. **Create a Google Cloud project** (or reuse one) at
179
+ [console.cloud.google.com](https://console.cloud.google.com/), then enable
180
+ the **Google Search Console API**: *APIs & Services → Library → Google
181
+ Search Console API → Enable*.
182
+ 2. **Configure the OAuth consent screen** (*APIs & Services → OAuth consent
183
+ screen*): choose *External*, fill in the app name and your email, and add
184
+ your Google account under **Test users** (in Testing mode only listed users
185
+ can authorize — no app verification needed).
186
+ 3. **Create an OAuth client** (*APIs & Services → Credentials → Create
187
+ credentials → OAuth client ID*), application type **Desktop app**. Save the
188
+ **client ID** and **client secret**.
189
+ 4. **Mint a refresh token.** The easiest way is the
190
+ [OAuth 2.0 Playground](https://developers.google.com/oauthplayground):
191
+ - Click the gear icon → check **Use your own OAuth credentials** → paste
192
+ your client ID and secret (add
193
+ `https://developers.google.com/oauthplayground` as an authorized redirect
194
+ URI to the OAuth client first).
195
+ - In *Step 1*, enter the scope `https://www.googleapis.com/auth/webmasters`
196
+ and click **Authorize APIs**, signing in with the test-user account that
197
+ owns your Search Console properties.
198
+ - In *Step 2*, click **Exchange authorization code for tokens** and copy the
199
+ **refresh token**.
200
+ 5. Put the three values into `GOOGLE_SEARCH_CONSOLE_CLIENT_ID`,
201
+ `GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET` and
202
+ `GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN`. The server exchanges the refresh
203
+ token for short-lived access tokens automatically.
204
+
205
+ Scope notes: `https://www.googleapis.com/auth/webmasters` covers everything
206
+ including sitemap submission and property management. If you only need reads
207
+ (analytics, inspection, listings), the narrower
208
+ `https://www.googleapis.com/auth/webmasters.readonly` works — but `add_site`,
209
+ `delete_site`, `submit_sitemap` and `delete_sitemap` will then return 403.
210
+ While the consent screen stays in Testing mode, refresh tokens expire after
211
+ 7 days — publish the app (or keep it Internal in a Workspace domain) for
212
+ long-lived tokens.
213
+
214
+ ⚠️ The credentials are stored **in plain text** in your client's config — treat
215
+ them like a password. The refresh token grants access to your Search Console
216
+ data until revoked at
217
+ [myaccount.google.com/permissions](https://myaccount.google.com/permissions).
218
+
219
+ ## Configuration
220
+
221
+ | Variable | Required | Default | Description |
222
+ |---|---|---|---|
223
+ | `GOOGLE_SEARCH_CONSOLE_CLIENT_ID` | yes* | — | OAuth2 client id (refresh flow). |
224
+ | `GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET` | yes* | — | OAuth2 client secret (refresh flow). |
225
+ | `GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN` | yes* | — | OAuth2 refresh token (refresh flow). |
226
+ | `GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN` | yes* | — | Alternative: a static access token (~1 h lifetime), mostly for testing. |
227
+ | `GOOGLE_SEARCH_CONSOLE_API_BASE` | no | `https://searchconsole.googleapis.com` | API root override. |
228
+ | `GOOGLE_SEARCH_CONSOLE_TIMEOUT_MS` | no | `60000` | Per-request timeout, ms. |
229
+ | `GOOGLE_SEARCH_CONSOLE_MAX_RETRIES` | no | `3` | Retries on transient errors. |
230
+
231
+ \* Either the three refresh-flow variables together, **or** `GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN`.
232
+
233
+ ## Documentation
234
+
235
+ - [All tools](https://github.com/A1-x-Tech/mcp-google-search-console/blob/main/docs/TOOLS.md) — full reference with parameters and notes.
236
+ - [Development](https://github.com/A1-x-Tech/mcp-google-search-console/blob/main/docs/DEVELOPMENT.md) — build, tests, smoke check, telemetry.
237
+ - [Publishing](https://github.com/A1-x-Tech/mcp-google-search-console/blob/main/docs/PUBLISHING.md) — releasing and MCP-catalog listing.
238
+
239
+ ## Support
240
+
241
+ Questions, ideas, issues — Telegram [@gistrec](http://t.me/gistrec) or
242
+ [GitHub issues](https://github.com/A1-x-Tech/mcp-google-search-console/issues).
243
+
244
+ ## License
245
+
246
+ MIT — see [LICENSE](./LICENSE).
package/dist/client.js ADDED
@@ -0,0 +1,290 @@
1
+ import { GoogleSearchConsoleError } from "./types.js";
2
+ /** Google's OAuth2 token endpoint — refresh tokens are exchanged here. */
3
+ const TOKEN_URL = "https://oauth2.googleapis.com/token";
4
+ /**
5
+ * Encodes a property (siteUrl) or sitemap URL (feedpath) as a single path
6
+ * segment. Both are full URLs (or "sc-domain:example.com") embedded in the
7
+ * path, so every reserved character — including "/" and ":" — must be encoded
8
+ * or the API's routing breaks.
9
+ */
10
+ function seg(value) {
11
+ return encodeURIComponent(value);
12
+ }
13
+ export class GoogleSearchConsoleClient {
14
+ config;
15
+ base;
16
+ timeoutMs;
17
+ maxRetries;
18
+ retryBaseMs;
19
+ /** Cached access token from the refresh flow, with its expiry. */
20
+ cachedToken;
21
+ /** In-flight refresh, deduping concurrent token requests. */
22
+ refreshInFlight;
23
+ constructor(config) {
24
+ this.config = config;
25
+ this.base = config.apiBase.endsWith("/") ? config.apiBase : config.apiBase + "/";
26
+ this.timeoutMs = config.timeoutMs ?? 60_000;
27
+ this.maxRetries = config.maxRetries ?? 3;
28
+ this.retryBaseMs = config.retryBaseMs ?? 500;
29
+ }
30
+ canRefresh() {
31
+ return Boolean(this.config.refreshToken && this.config.clientId && this.config.clientSecret);
32
+ }
33
+ /**
34
+ * Returns a valid Bearer token. With the refresh triple configured, mints an
35
+ * access token from the refresh token and caches it until shortly before it
36
+ * expires (concurrent callers share one in-flight refresh); otherwise the
37
+ * static GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN is used as-is.
38
+ */
39
+ async accessToken(forceRefresh = false) {
40
+ if (!this.canRefresh()) {
41
+ // loadConfig guarantees accessToken is set when the refresh triple is absent.
42
+ return this.config.accessToken;
43
+ }
44
+ if (!forceRefresh && this.cachedToken && Date.now() < this.cachedToken.expiresAt) {
45
+ return this.cachedToken.value;
46
+ }
47
+ if (!this.refreshInFlight) {
48
+ this.refreshInFlight = this.refreshAccessToken().finally(() => {
49
+ this.refreshInFlight = undefined;
50
+ });
51
+ }
52
+ return this.refreshInFlight;
53
+ }
54
+ /** Exchanges the refresh token for a fresh access token at Google's token endpoint. */
55
+ async refreshAccessToken() {
56
+ const body = new URLSearchParams({
57
+ client_id: this.config.clientId,
58
+ client_secret: this.config.clientSecret,
59
+ refresh_token: this.config.refreshToken,
60
+ grant_type: "refresh_token",
61
+ }).toString();
62
+ const { res, text } = await this.fetchWithTimeout(TOKEN_URL, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body }, "oauth2 token refresh");
63
+ let data;
64
+ try {
65
+ data = JSON.parse(text);
66
+ }
67
+ catch {
68
+ data = text;
69
+ }
70
+ if (!res.ok)
71
+ throw new GoogleSearchConsoleError(res.status, data);
72
+ const token = data.access_token;
73
+ if (typeof token !== "string" || !token) {
74
+ throw new Error("OAuth2 token endpoint returned no access_token.");
75
+ }
76
+ const expiresIn = Number(data.expires_in);
77
+ const ttl = Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : 3600;
78
+ // Refresh 60s ahead of the real expiry so requests never race a dying token.
79
+ this.cachedToken = { value: token, expiresAt: Date.now() + Math.max(ttl - 60, 30) * 1000 };
80
+ return token;
81
+ }
82
+ /** Verifies the OAuth credentials by minting a fresh access token (refresh flow only). */
83
+ async authCheck() {
84
+ if (!this.canRefresh()) {
85
+ throw new Error("authCheck needs the refresh flow (GOOGLE_SEARCH_CONSOLE_CLIENT_ID / _CLIENT_SECRET / _REFRESH_TOKEN); with a static GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN list the sites instead.");
86
+ }
87
+ await this.accessToken(true);
88
+ return { ok: true, auth: "refresh_token" };
89
+ }
90
+ /** Backoff before a retry: honors Retry-After when present, else exponential (capped at 30s). */
91
+ backoffMs(attempt, res) {
92
+ const retryAfter = res ? Number(res.headers.get("Retry-After")) : NaN;
93
+ if (Number.isFinite(retryAfter) && retryAfter > 0)
94
+ return Math.min(retryAfter, 30) * 1000;
95
+ return Math.min(this.retryBaseMs * 2 ** attempt, 30_000);
96
+ }
97
+ /**
98
+ * fetch with an AbortController timeout. Reads the response body inside the
99
+ * guarded zone so the timeout also covers a slow or drip-feeding body, not
100
+ * just the initial headers, and returns the text alongside the response.
101
+ */
102
+ async fetchWithTimeout(url, init, label) {
103
+ const controller = new AbortController();
104
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
105
+ try {
106
+ const res = await fetch(url, { ...init, signal: controller.signal });
107
+ const text = await res.text();
108
+ return { res, text };
109
+ }
110
+ catch (err) {
111
+ if (err instanceof Error && err.name === "AbortError") {
112
+ throw new Error(`Request to "${label}" timed out after ${this.timeoutMs}ms`);
113
+ }
114
+ throw err;
115
+ }
116
+ finally {
117
+ clearTimeout(timer);
118
+ }
119
+ }
120
+ /**
121
+ * Low-level request to a Search Console API path (e.g. "webmasters/v3/sites"
122
+ * or "v1/urlInspection/index:inspect"). Auth is a Bearer token (refreshed
123
+ * transparently; a 401 forces one re-mint + replay). 429 is always retried
124
+ * with backoff; 5xx and network errors/timeouts are retried only for GET —
125
+ * PUT/DELETE here are idempotent by API contract, but a blanket write-replay
126
+ * gate is the line's convention and costs nothing. Successful mutations
127
+ * (sites.add/delete, sitemaps.submit/delete) return an EMPTY body — request()
128
+ * then resolves to undefined; callers wrap it. Any other non-2xx throws a
129
+ * {@link GoogleSearchConsoleError}.
130
+ */
131
+ async request(method, path, body, query) {
132
+ // Guard method !== "GET" keeps undici from crashing on a GET-with-body.
133
+ const hasBody = body !== undefined && method !== "GET";
134
+ // Resolve the path against the API base, then reject anything that escaped
135
+ // to a foreign origin (an absolute "https://evil/x" or a "\\evil/x" slipped
136
+ // through raw_request) so the Bearer token can never leak to another host.
137
+ const url = new URL(path.replace(/^\//, ""), this.base);
138
+ if (url.origin !== new URL(this.base).origin) {
139
+ throw new Error(`raw_request path must be a relative API path (resolved to foreign origin ${url.origin})`);
140
+ }
141
+ if (query) {
142
+ for (const [key, value] of Object.entries(query)) {
143
+ if (value !== undefined)
144
+ url.searchParams.set(key, String(value));
145
+ }
146
+ }
147
+ const target = url.toString();
148
+ // Only reads are replayed on ambiguous failures (see the retry gate below).
149
+ const idempotent = method === "GET";
150
+ let refreshedOn401 = false;
151
+ for (let attempt = 0;; attempt++) {
152
+ const token = await this.accessToken();
153
+ const headers = { Authorization: `Bearer ${token}` };
154
+ if (hasBody)
155
+ headers["Content-Type"] = "application/json";
156
+ let res;
157
+ let text;
158
+ try {
159
+ ({ res, text } = await this.fetchWithTimeout(target, { method, headers, body: hasBody ? JSON.stringify(body) : undefined }, path));
160
+ }
161
+ catch (err) {
162
+ // Network error or timeout: the request may or may not have reached the
163
+ // API, so only reads are retried; writes rethrow immediately.
164
+ if (idempotent && attempt < this.maxRetries) {
165
+ await delay(this.backoffMs(attempt));
166
+ continue;
167
+ }
168
+ throw err;
169
+ }
170
+ // An expired/revoked access token: re-mint once and replay. The request
171
+ // never executed, so this is safe for writes too.
172
+ if (res.status === 401 && this.canRefresh() && !refreshedOn401) {
173
+ refreshedOn401 = true;
174
+ await this.accessToken(true);
175
+ continue;
176
+ }
177
+ // 429 means the request was rejected before executing — safe to retry for
178
+ // any method. 5xx is ambiguous, so it is gated to idempotent requests.
179
+ // 403 quotaExceeded (daily limits) is NOT transient and falls through.
180
+ const transient = res.status === 429 || (idempotent && res.status >= 500 && res.status < 600);
181
+ if (transient && attempt < this.maxRetries) {
182
+ await delay(this.backoffMs(attempt, res));
183
+ continue;
184
+ }
185
+ let data = undefined;
186
+ if (text) {
187
+ try {
188
+ data = JSON.parse(text);
189
+ }
190
+ catch {
191
+ data = text;
192
+ }
193
+ }
194
+ if (!res.ok)
195
+ throw new GoogleSearchConsoleError(res.status, data);
196
+ return data;
197
+ }
198
+ }
199
+ // ---- Sites ----
200
+ /** All properties the authenticated account can access, with permission levels. */
201
+ async listSites() {
202
+ return this.request("GET", "webmasters/v3/sites");
203
+ }
204
+ /** One property's entry ({ siteUrl, permissionLevel }). */
205
+ async getSite(siteUrl) {
206
+ return this.request("GET", `webmasters/v3/sites/${seg(siteUrl)}`);
207
+ }
208
+ /** Adds a property to the account's set (stays unverified). Empty API response. */
209
+ async addSite(siteUrl) {
210
+ return (await this.request("PUT", `webmasters/v3/sites/${seg(siteUrl)}`)) ?? { ok: true, added: siteUrl };
211
+ }
212
+ /** Unlinks a property from the account (no data is deleted). Empty API response. */
213
+ async deleteSite(siteUrl) {
214
+ return (await this.request("DELETE", `webmasters/v3/sites/${seg(siteUrl)}`)) ?? { ok: true, removed: siteUrl };
215
+ }
216
+ // ---- Sitemaps ----
217
+ /** Submitted sitemaps for a property, or children of a sitemap index. */
218
+ async listSitemaps(siteUrl, sitemapIndex) {
219
+ return this.request("GET", `webmasters/v3/sites/${seg(siteUrl)}/sitemaps`, undefined, {
220
+ sitemapIndex,
221
+ });
222
+ }
223
+ /** One submitted sitemap's details (WmxSitemap). */
224
+ async getSitemap(siteUrl, feedpath) {
225
+ return this.request("GET", `webmasters/v3/sites/${seg(siteUrl)}/sitemaps/${seg(feedpath)}`);
226
+ }
227
+ /** Submits (or resubmits) a sitemap. PUT with no request body; empty API response. */
228
+ async submitSitemap(siteUrl, feedpath) {
229
+ return ((await this.request("PUT", `webmasters/v3/sites/${seg(siteUrl)}/sitemaps/${seg(feedpath)}`)) ?? {
230
+ ok: true,
231
+ submitted: feedpath,
232
+ siteUrl,
233
+ });
234
+ }
235
+ /** Removes a sitemap from Search Console. Empty API response. */
236
+ async deleteSitemap(siteUrl, feedpath) {
237
+ return ((await this.request("DELETE", `webmasters/v3/sites/${seg(siteUrl)}/sitemaps/${seg(feedpath)}`)) ?? {
238
+ ok: true,
239
+ deleted: feedpath,
240
+ siteUrl,
241
+ });
242
+ }
243
+ // ---- Search Analytics ----
244
+ /**
245
+ * Performance query: clicks/impressions/ctr/position grouped by dimensions.
246
+ * The tool vocabulary already matches the wire format, so the body is a
247
+ * straight compact() of the params; the only structural mapping is wrapping
248
+ * flat filters into the single AND dimensionFilterGroups group.
249
+ */
250
+ async searchAnalytics(p) {
251
+ return this.request("POST", `webmasters/v3/sites/${seg(p.siteUrl)}/searchAnalytics/query`, compact({
252
+ startDate: p.startDate,
253
+ endDate: p.endDate,
254
+ dimensions: p.dimensions,
255
+ type: p.searchType,
256
+ dimensionFilterGroups: p.filters && p.filters.length > 0
257
+ ? [
258
+ {
259
+ groupType: "and",
260
+ filters: p.filters.map((f) => ({
261
+ dimension: f.dimension,
262
+ operator: f.operator,
263
+ expression: f.expression,
264
+ })),
265
+ },
266
+ ]
267
+ : undefined,
268
+ aggregationType: p.aggregationType,
269
+ rowLimit: p.rowLimit,
270
+ startRow: p.startRow,
271
+ dataState: p.dataState,
272
+ }));
273
+ }
274
+ // ---- URL Inspection ----
275
+ /** Google-index status of one URL (v1 surface; POST with a JSON body, not path params). */
276
+ async inspectUrl(p) {
277
+ return this.request("POST", "v1/urlInspection/index:inspect", compact({
278
+ inspectionUrl: p.inspectionUrl,
279
+ siteUrl: p.siteUrl,
280
+ languageCode: p.languageCode,
281
+ }));
282
+ }
283
+ }
284
+ /** Drops keys whose value is `undefined` so they are not sent to the API. */
285
+ function compact(obj) {
286
+ return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined));
287
+ }
288
+ function delay(ms) {
289
+ return new Promise((resolve) => setTimeout(resolve, ms));
290
+ }
package/dist/config.js ADDED
@@ -0,0 +1,54 @@
1
+ /** Default Google Search Console API host (serves both webmasters/v3 and v1). */
2
+ const DEFAULT_BASE = "https://searchconsole.googleapis.com";
3
+ /**
4
+ * A missing or malformed environment variable. Thrown instead of exiting on the
5
+ * spot so index.ts can report the drop-off before the process dies; `reason` is
6
+ * the machine-readable code that ships with that ping (never a variable's value).
7
+ */
8
+ export class ConfigError extends Error {
9
+ reason;
10
+ constructor(message, reason) {
11
+ super(message);
12
+ this.name = "ConfigError";
13
+ this.reason = reason;
14
+ }
15
+ }
16
+ function die(message, reason) {
17
+ throw new ConfigError(message, reason);
18
+ }
19
+ /**
20
+ * Builds the client config from environment variables, throwing ConfigError if
21
+ * the credentials are missing or incomplete.
22
+ *
23
+ * GOOGLE_SEARCH_CONSOLE_CLIENT_ID OAuth2 client id (refresh flow, recommended)
24
+ * GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET OAuth2 client secret (refresh flow)
25
+ * GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN OAuth2 refresh token (refresh flow)
26
+ * GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN static access token (alternative; expires in ~1h)
27
+ * GOOGLE_SEARCH_CONSOLE_API_BASE API root override (default https://searchconsole.googleapis.com)
28
+ * GOOGLE_SEARCH_CONSOLE_TIMEOUT_MS per-request timeout (default 60000)
29
+ * GOOGLE_SEARCH_CONSOLE_MAX_RETRIES retries on transient errors (default 3)
30
+ */
31
+ export function loadConfig() {
32
+ const clientId = process.env.GOOGLE_SEARCH_CONSOLE_CLIENT_ID;
33
+ const clientSecret = process.env.GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET;
34
+ const refreshToken = process.env.GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN;
35
+ const accessToken = process.env.GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN;
36
+ const oauthProvided = [clientId, clientSecret, refreshToken].filter(Boolean).length;
37
+ if (oauthProvided > 0 && oauthProvided < 3) {
38
+ die("GOOGLE_SEARCH_CONSOLE_CLIENT_ID, GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET and GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN must be set together (OAuth2 refresh flow).", "incomplete_oauth_config");
39
+ }
40
+ if (oauthProvided === 0 && !accessToken) {
41
+ die("Google OAuth credentials are required: set GOOGLE_SEARCH_CONSOLE_CLIENT_ID + GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET + GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN (recommended), or GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN with a short-lived access token.", "missing_credentials");
42
+ }
43
+ const timeoutMs = Number(process.env.GOOGLE_SEARCH_CONSOLE_TIMEOUT_MS);
44
+ const maxRetries = Number(process.env.GOOGLE_SEARCH_CONSOLE_MAX_RETRIES);
45
+ return {
46
+ clientId,
47
+ clientSecret,
48
+ refreshToken,
49
+ accessToken,
50
+ apiBase: process.env.GOOGLE_SEARCH_CONSOLE_API_BASE || DEFAULT_BASE,
51
+ timeoutMs: Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 60_000,
52
+ maxRetries: Number.isFinite(maxRetries) && maxRetries >= 0 ? maxRetries : 3,
53
+ };
54
+ }
package/dist/index.js ADDED
@@ -0,0 +1,69 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
+ import { GoogleSearchConsoleClient } from "./client.js";
6
+ import { ConfigError, loadConfig } from "./config.js";
7
+ import { instrumentToolCalls, Telemetry } from "./telemetry.js";
8
+ import { registerSiteTools } from "./tools/sites.js";
9
+ import { registerSitemapTools } from "./tools/sitemaps.js";
10
+ import { registerAnalyticsTools } from "./tools/analytics.js";
11
+ import { registerInspectionTools } from "./tools/inspection.js";
12
+ import { registerRawTool } from "./tools/raw.js";
13
+ /** Reads the package version so the server reports its real version to MCP clients. */
14
+ function readVersion() {
15
+ try {
16
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
17
+ return typeof pkg.version === "string" ? pkg.version : "0.0.0";
18
+ }
19
+ catch {
20
+ return "0.0.0";
21
+ }
22
+ }
23
+ /**
24
+ * Loads the config, reporting the drop-off if it is missing. An unconfigured
25
+ * server dies before the MCP handshake, so this ping is the only trace such an
26
+ * install ever leaves — and it has to be awaited, or process.exit() below would
27
+ * kill the request in flight.
28
+ */
29
+ async function loadConfigOrExit(telemetry) {
30
+ try {
31
+ return loadConfig();
32
+ }
33
+ catch (err) {
34
+ if (!(err instanceof ConfigError))
35
+ throw err;
36
+ console.error(`Error: ${err.message}`);
37
+ await telemetry.sendBlocking("startup_failed", { reason: err.reason });
38
+ process.exit(1);
39
+ }
40
+ }
41
+ async function main() {
42
+ // Anonymous usage pings (ids/names/versions only, never data or arguments);
43
+ // opt out with ASKADS_TELEMETRY=0. Built before the config so missing
44
+ // credentials can be reported; wired to the server before tools register.
45
+ const telemetry = new Telemetry(readVersion());
46
+ const config = await loadConfigOrExit(telemetry);
47
+ const client = new GoogleSearchConsoleClient(config);
48
+ const server = new McpServer({
49
+ name: "mcp-google-search-console",
50
+ version: readVersion(),
51
+ });
52
+ instrumentToolCalls(server, telemetry);
53
+ server.server.oninitialized = () => {
54
+ telemetry.setClientInfo(server.server.getClientVersion());
55
+ telemetry.send("server_start");
56
+ };
57
+ registerSiteTools(server, client);
58
+ registerSitemapTools(server, client);
59
+ registerAnalyticsTools(server, client);
60
+ registerInspectionTools(server, client);
61
+ registerRawTool(server, client);
62
+ const transport = new StdioServerTransport();
63
+ await server.connect(transport);
64
+ console.error("mcp-google-search-console running on stdio");
65
+ }
66
+ main().catch((err) => {
67
+ console.error("Fatal error starting mcp-google-search-console:", err);
68
+ process.exit(1);
69
+ });