mcp-google-search-console 1.0.0 → 1.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/README.md +168 -182
- package/README.ru.md +230 -0
- package/dist/client.js +7 -2
- package/dist/config.js +41 -12
- package/dist/index.js +61 -12
- package/dist/telemetry.js +3 -3
- package/package.json +1 -1
- package/test/dist-smoke.test.js +49 -0
package/README.md
CHANGED
|
@@ -1,246 +1,232 @@
|
|
|
1
|
-
# Google Search Console MCP
|
|
1
|
+
# <img src="./assets/a1-logo.svg" alt="A1" width="40"> Google Search Console MCP
|
|
2
|
+
|
|
3
|
+
**English** | [Русский](./README.ru.md)
|
|
2
4
|
|
|
3
5
|
[](https://www.npmjs.com/package/mcp-google-search-console)
|
|
4
6
|
[](https://github.com/A1-x-Tech/mcp-google-search-console/actions/workflows/ci.yml)
|
|
5
7
|
[](https://glama.ai/mcp/servers/A1-x-Tech/mcp-google-search-console)
|
|
6
8
|
[](./LICENSE)
|
|
7
9
|
|
|
8
|
-
MCP
|
|
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.
|
|
10
|
+
**A1 Google Search Console MCP** connects an AI app to Google Search Console. Investigate search performance, check whether a URL is indexed, inspect sitemaps and deliberately submit or remove a sitemap when needed.
|
|
12
11
|
|
|
13
|
-
|
|
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.
|
|
12
|
+
It works with the properties your Google account can access. The important detail is that it uses the exact Search Console property value — a domain property and a URL-prefix property are different objects.
|
|
16
13
|
|
|
17
|
-
|
|
14
|
+
- **12 tools.** Seven tools read properties, search data, sitemaps and index status; two add a property or submit a sitemap; three can remove data or call an arbitrary API method.
|
|
15
|
+
- **Exact property IDs.** `https://example.com/`, `https://www.example.com/` and `sc-domain:example.com` are distinct. `list_sites` shows the value to use.
|
|
16
|
+
- **Search data with context.** Query clicks, impressions, CTR and position by date, page, query, country, device or search appearance.
|
|
17
|
+
- **Indexing, not publishing.** URL inspection explains Google’s current status; it does not force a page into the index.
|
|
18
18
|
|
|
19
|
-
|
|
20
|
-
2. Add the server — for example, in Claude Code ([other clients](#installation)):
|
|
19
|
+
Start with a read-only question:
|
|
21
20
|
|
|
22
|
-
|
|
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@latest
|
|
28
|
-
```
|
|
21
|
+
> Show the top 20 search queries for my property over the last 28 days, with clicks and CTR.
|
|
29
22
|
|
|
30
|
-
|
|
31
|
-
the last 28 days, with clicks and CTR."*
|
|
23
|
+
[Connect the server](#quick-start) · [Explore use cases](#what-you-can-ask-it-to-do) · [Open technical documentation](#technical-documentation)
|
|
32
24
|
|
|
33
|
-
|
|
25
|
+
---
|
|
34
26
|
|
|
35
|
-
|
|
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). |
|
|
27
|
+
## See it work in a minute
|
|
49
28
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
29
|
+
> **You:** Is `https://example.com/pricing` indexed? If not, why?
|
|
30
|
+
>
|
|
31
|
+
> **Assistant:** Inspects the URL and shows the index verdict, coverage, crawl information and canonical URLs. Nothing changes.
|
|
32
|
+
>
|
|
33
|
+
> **You:** Check my submitted sitemaps and prepare a resubmission for the one with errors.
|
|
34
|
+
>
|
|
35
|
+
> **Assistant:** Shows the sitemap, its warnings and errors, then asks for confirmation before submitting it again.
|
|
36
|
+
>
|
|
37
|
+
> **You:** Confirm.
|
|
38
|
+
>
|
|
39
|
+
> **Assistant:** Resubmits the selected sitemap. It does not change page content or guarantee indexing.
|
|
54
40
|
|
|
55
|
-
##
|
|
41
|
+
## Contents
|
|
56
42
|
|
|
57
|
-
-
|
|
58
|
-
-
|
|
59
|
-
-
|
|
60
|
-
-
|
|
43
|
+
- [Quick start](#quick-start)
|
|
44
|
+
- [What you can ask it to do](#what-you-can-ask-it-to-do)
|
|
45
|
+
- [How Search Console properties work](#how-search-console-properties-work)
|
|
46
|
+
- [What can change](#what-can-change)
|
|
47
|
+
- [Getting access](#getting-access)
|
|
48
|
+
- [Configuration](#configuration)
|
|
49
|
+
- [Data, limits and background work](#data-limits-and-background-work)
|
|
50
|
+
- [Technical documentation](#technical-documentation)
|
|
51
|
+
- [Support](#support)
|
|
61
52
|
|
|
62
|
-
##
|
|
53
|
+
## Quick start
|
|
63
54
|
|
|
64
|
-
|
|
55
|
+
You need Node.js 20+, a Google account with access to a Search Console property and OAuth credentials from Google Cloud.
|
|
65
56
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
- **Domain property** — `sc-domain:example.com` (no scheme, no slash).
|
|
57
|
+
1. [Prepare OAuth access](#getting-access).
|
|
58
|
+
2. Add the server to your AI app.
|
|
59
|
+
3. Start with the read-only question above.
|
|
70
60
|
|
|
71
|
-
|
|
72
|
-
the assistant will usually call it first.
|
|
61
|
+
<details open><summary><strong>Codex</strong></summary>
|
|
73
62
|
|
|
74
|
-
|
|
63
|
+
<br>
|
|
75
64
|
|
|
76
|
-
|
|
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.
|
|
65
|
+
**In the app:** open **Settings → Plugins → MCP servers**, choose **Add server**, then add `npx -y mcp-google-search-console@latest` with `GOOGLE_SEARCH_CONSOLE_CLIENT_ID`, `GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET` and `GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN`.
|
|
85
66
|
|
|
86
|
-
|
|
67
|
+
```bash
|
|
68
|
+
codex mcp add google-search-console \
|
|
69
|
+
--env GOOGLE_SEARCH_CONSOLE_CLIENT_ID=your_client_id \
|
|
70
|
+
--env GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET=your_client_secret \
|
|
71
|
+
--env GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN=your_refresh_token \
|
|
72
|
+
-- npx -y mcp-google-search-console@latest
|
|
73
|
+
codex mcp list
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
[Codex MCP documentation](https://learn.chatgpt.com/docs/extend/mcp?surface=cli)
|
|
77
|
+
|
|
78
|
+
</details>
|
|
87
79
|
|
|
88
|
-
|
|
80
|
+
<details><summary><strong>Claude Code</strong></summary>
|
|
89
81
|
|
|
90
|
-
<
|
|
91
|
-
<summary><b>Claude Code</b></summary>
|
|
82
|
+
<br>
|
|
92
83
|
|
|
93
84
|
```bash
|
|
94
|
-
claude mcp add
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
85
|
+
claude mcp add \
|
|
86
|
+
--env GOOGLE_SEARCH_CONSOLE_CLIENT_ID=your_client_id \
|
|
87
|
+
--env GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET=your_client_secret \
|
|
88
|
+
--env GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN=your_refresh_token \
|
|
89
|
+
--transport stdio --scope user google-search-console \
|
|
98
90
|
-- npx -y mcp-google-search-console@latest
|
|
91
|
+
claude mcp list
|
|
99
92
|
```
|
|
100
93
|
|
|
94
|
+
[Claude Code MCP documentation](https://code.claude.com/docs/en/mcp)
|
|
95
|
+
|
|
101
96
|
</details>
|
|
102
97
|
|
|
103
|
-
<details>
|
|
104
|
-
|
|
98
|
+
<details><summary><strong>Claude Desktop</strong></summary>
|
|
99
|
+
|
|
100
|
+
<br>
|
|
105
101
|
|
|
106
|
-
|
|
102
|
+
Open **Settings → Developer → Edit Config** and add:
|
|
107
103
|
|
|
108
104
|
```json
|
|
109
|
-
{
|
|
110
|
-
"mcpServers": {
|
|
111
|
-
"google-search-console": {
|
|
112
|
-
"command": "npx",
|
|
113
|
-
"args": ["-y", "mcp-google-search-console@latest"],
|
|
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
|
-
}
|
|
105
|
+
{"mcpServers":{"google-search-console":{"command":"npx","args":["-y","mcp-google-search-console@latest"],"env":{"GOOGLE_SEARCH_CONSOLE_CLIENT_ID":"your_client_id","GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET":"your_client_secret","GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN":"your_refresh_token"}}}}
|
|
122
106
|
```
|
|
123
107
|
|
|
108
|
+
If **Edit Config** is unavailable, edit `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS or `%APPDATA%\Claude\claude_desktop_config.json` on Windows.
|
|
109
|
+
|
|
110
|
+
[Claude Desktop MCP documentation](https://support.claude.com/en/articles/10949351-getting-started-with-local-mcp-servers-on-claude-desktop)
|
|
111
|
+
|
|
124
112
|
</details>
|
|
125
113
|
|
|
126
|
-
<details>
|
|
127
|
-
|
|
114
|
+
<details><summary><strong>Cursor</strong></summary>
|
|
115
|
+
|
|
116
|
+
<br>
|
|
128
117
|
|
|
129
|
-
`~/.cursor/mcp.json`
|
|
118
|
+
Add to `~/.cursor/mcp.json` on macOS/Linux or `%USERPROFILE%\.cursor\mcp.json` on Windows:
|
|
130
119
|
|
|
131
120
|
```json
|
|
132
|
-
{
|
|
133
|
-
"mcpServers": {
|
|
134
|
-
"google-search-console": {
|
|
135
|
-
"command": "npx",
|
|
136
|
-
"args": ["-y", "mcp-google-search-console@latest"],
|
|
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
|
-
}
|
|
121
|
+
{"mcpServers":{"google-search-console":{"type":"stdio","command":"npx","args":["-y","mcp-google-search-console@latest"],"env":{"GOOGLE_SEARCH_CONSOLE_CLIENT_ID":"your_client_id","GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET":"your_client_secret","GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN":"your_refresh_token"}}}}
|
|
145
122
|
```
|
|
146
123
|
|
|
124
|
+
[Cursor MCP documentation](https://cursor.com/docs/mcp)
|
|
125
|
+
|
|
147
126
|
</details>
|
|
148
127
|
|
|
149
|
-
<details>
|
|
150
|
-
|
|
128
|
+
<details><summary><strong>VS Code</strong></summary>
|
|
129
|
+
|
|
130
|
+
<br>
|
|
151
131
|
|
|
152
|
-
|
|
132
|
+
Run **MCP: Open User Configuration** and add:
|
|
153
133
|
|
|
154
134
|
```json
|
|
155
|
-
{
|
|
156
|
-
"servers": {
|
|
157
|
-
"google-search-console": {
|
|
158
|
-
"type": "stdio",
|
|
159
|
-
"command": "npx",
|
|
160
|
-
"args": ["-y", "mcp-google-search-console@latest"],
|
|
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
|
-
}
|
|
135
|
+
{"servers":{"google-search-console":{"type":"stdio","command":"npx","args":["-y","mcp-google-search-console@latest"],"env":{"GOOGLE_SEARCH_CONSOLE_CLIENT_ID":"${input:gsc_client_id}","GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET":"${input:gsc_client_secret}","GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN":"${input:gsc_refresh_token}"}}},"inputs":[{"type":"promptString","id":"gsc_client_id","description":"Google OAuth client ID"},{"type":"promptString","id":"gsc_client_secret","description":"Google OAuth client secret","password":true},{"type":"promptString","id":"gsc_refresh_token","description":"Google OAuth refresh token","password":true}]}
|
|
169
136
|
```
|
|
170
137
|
|
|
138
|
+
Check it with **MCP: List Servers**. [VS Code MCP documentation](https://code.visualstudio.com/docs/agent-customization/mcp-servers)
|
|
139
|
+
|
|
171
140
|
</details>
|
|
172
141
|
|
|
173
|
-
##
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
142
|
+
## What you can ask it to do
|
|
143
|
+
|
|
144
|
+
### Find search opportunities
|
|
145
|
+
|
|
146
|
+
- Which queries and pages brought the most clicks this month?
|
|
147
|
+
- Which pages lost clicks compared with the previous period?
|
|
148
|
+
- Show queries containing `mcp` where average position is below 10.
|
|
149
|
+
|
|
150
|
+
### Check index status and sitemaps
|
|
151
|
+
|
|
152
|
+
- Is this URL indexed? Show coverage, crawl and canonical information.
|
|
153
|
+
- Which submitted sitemaps have errors or warnings?
|
|
154
|
+
- Resubmit this sitemap after showing its current status.
|
|
155
|
+
|
|
156
|
+
### Manage properties carefully
|
|
157
|
+
|
|
158
|
+
- List the Search Console properties I can access.
|
|
159
|
+
- Add this exact property value; I will verify ownership separately.
|
|
160
|
+
- Remove this property from my account after confirmation.
|
|
161
|
+
|
|
162
|
+
## How Search Console properties work
|
|
163
|
+
|
|
164
|
+
A URL-prefix property must include its protocol and trailing slash, for example `https://example.com/`. A domain property is written as `sc-domain:example.com`. A near-match causes 403 or 404, so use the exact value returned by `list_sites`.
|
|
165
|
+
|
|
166
|
+
`add_site` only registers a property. Verification remains in the Search Console UI or Site Verification API. Search data uses Pacific Time; `end_date` is inclusive and final analytics data typically lags by two to three days. `data_state: "all"` can include fresher, still-changing rows.
|
|
167
|
+
|
|
168
|
+
## What can change
|
|
169
|
+
|
|
170
|
+
| Operation | What happens | Confirmation boundary |
|
|
171
|
+
|---|---|---|
|
|
172
|
+
| List properties, analytics, sitemaps and URL status | Reads Search Console data | No change |
|
|
173
|
+
| Add a property | Adds a property entry; does not verify it | Changes account access |
|
|
174
|
+
| Submit or resubmit a sitemap | Requests processing of a sitemap | Changes Search Console state |
|
|
175
|
+
| Delete a property | Unlinks the property from the account; Google data is not deleted | Destructive |
|
|
176
|
+
| Delete a sitemap | Removes a submitted sitemap | Destructive |
|
|
177
|
+
| Raw API request | May call a write or delete endpoint | Potentially destructive |
|
|
178
|
+
|
|
179
|
+
The AI client controls confirmation prompts. The server marks reads, writes and destructive calls so the client can distinguish an inspection from a real change.
|
|
180
|
+
|
|
181
|
+
## Getting access
|
|
182
|
+
|
|
183
|
+
Search Console data requires Google OAuth 2.0; an API key is not enough.
|
|
184
|
+
|
|
185
|
+
1. Create or select a Google Cloud project and enable **Google Search Console API**.
|
|
186
|
+
2. Configure the OAuth consent screen and create a **Desktop app** OAuth client.
|
|
187
|
+
3. Use the [OAuth 2.0 Playground](https://developers.google.com/oauthplayground) with **Use your own OAuth credentials** to authorize the Google account that can access the properties and obtain a refresh token.
|
|
188
|
+
4. Use `https://www.googleapis.com/auth/webmasters` to include sitemaps and property changes. Use `https://www.googleapis.com/auth/webmasters.readonly` only if you intentionally need read-only access.
|
|
189
|
+
|
|
190
|
+
Testing-mode refresh tokens can expire after seven days. Publish the OAuth app, or use an Internal Workspace app, for long-lived access. Treat the client secret and refresh token as passwords.
|
|
218
191
|
|
|
219
192
|
## Configuration
|
|
220
193
|
|
|
221
|
-
| Variable | Required |
|
|
222
|
-
|
|
223
|
-
| `GOOGLE_SEARCH_CONSOLE_CLIENT_ID` |
|
|
224
|
-
| `GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET` |
|
|
225
|
-
| `GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN` |
|
|
226
|
-
| `GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN` |
|
|
227
|
-
| `GOOGLE_SEARCH_CONSOLE_API_BASE` |
|
|
228
|
-
| `GOOGLE_SEARCH_CONSOLE_TIMEOUT_MS` |
|
|
229
|
-
| `GOOGLE_SEARCH_CONSOLE_MAX_RETRIES` |
|
|
194
|
+
| Variable | Required | Description |
|
|
195
|
+
|---|---|---|
|
|
196
|
+
| `GOOGLE_SEARCH_CONSOLE_CLIENT_ID` | Yes* | OAuth client ID. |
|
|
197
|
+
| `GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET` | Yes* | OAuth client secret. |
|
|
198
|
+
| `GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN` | Yes* | OAuth refresh token. |
|
|
199
|
+
| `GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN` | Yes* | Short-lived alternative to the OAuth trio. |
|
|
200
|
+
| `GOOGLE_SEARCH_CONSOLE_API_BASE` | No | API base URL override. |
|
|
201
|
+
| `GOOGLE_SEARCH_CONSOLE_TIMEOUT_MS` | No | Per-request timeout; default `60000` ms. |
|
|
202
|
+
| `GOOGLE_SEARCH_CONSOLE_MAX_RETRIES` | No | Temporary-error retries; default `3`. |
|
|
203
|
+
|
|
204
|
+
\* Provide either the OAuth trio or an access token.
|
|
230
205
|
|
|
231
|
-
|
|
206
|
+
## Data, limits and background work
|
|
232
207
|
|
|
233
|
-
|
|
208
|
+
- **Privacy.** The local server calls Google and sends anonymous telemetry with an installation ID, versions and tool names — never OAuth tokens, property data, tool arguments or prompts. Set `ASKADS_TELEMETRY=0` to opt out.
|
|
209
|
+
- **API limits.** URL inspection allows 2,000 inspections per property per day and 600 per minute. Analytics returns at most 25,000 rows per request; long-tail anonymized queries are never returned. Use pagination and do not inspect whole sites URL by URL.
|
|
210
|
+
- **No background monitoring.** The server works only while called. If your AI app supports scheduled tasks, it can periodically check a sitemap or an important URL.
|
|
234
211
|
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
- [
|
|
212
|
+
## Technical documentation
|
|
213
|
+
|
|
214
|
+
- [MCP capability catalog](./docs/capabilities/index.md) — task-oriented pages for every tool.
|
|
215
|
+
- [All tools and inputs](./docs/TOOLS.md)
|
|
216
|
+
- [Development documentation](./docs/DEVELOPMENT.md)
|
|
217
|
+
- [Publishing documentation](./docs/PUBLISHING.md)
|
|
218
|
+
- [Google Search Console API](https://developers.google.com/webmaster-tools)
|
|
238
219
|
|
|
239
220
|
## Support
|
|
240
221
|
|
|
241
|
-
|
|
242
|
-
|
|
222
|
+
Found a bug or need a scenario? [Create an issue](https://github.com/A1-x-Tech/mcp-google-search-console/issues) or write in [Telegram](https://t.me/a1_mcp).
|
|
223
|
+
|
|
224
|
+
<br>
|
|
243
225
|
|
|
244
|
-
|
|
226
|
+
<p align="center">
|
|
227
|
+
<img src="https://github.com/ztemerbekov/a1-yandex-kit-skills/raw/main/assets/images/mona-hifive-yandex-kit-warm.gif" alt="Две Моны дают пять" width="256">
|
|
228
|
+
</p>
|
|
245
229
|
|
|
246
|
-
|
|
230
|
+
<p align="center">
|
|
231
|
+
You made it to the end!
|
|
232
|
+
</p>
|
package/README.ru.md
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
# <img src="./assets/a1-logo.svg" alt="A1" width="40"> Google Search Console MCP
|
|
2
|
+
|
|
3
|
+
[English](./README.md) | **Русский**
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/mcp-google-search-console)
|
|
6
|
+
[](https://github.com/A1-x-Tech/mcp-google-search-console/actions/workflows/ci.yml)
|
|
7
|
+
[](https://glama.ai/mcp/servers/A1-x-Tech/mcp-google-search-console)
|
|
8
|
+
[](./LICENSE)
|
|
9
|
+
|
|
10
|
+
**A1 Google Search Console MCP** подключает AI-приложение к Google Search Console. Он помогает исследовать поисковую эффективность, проверить индексацию URL, посмотреть sitemap и осознанно отправить или удалить sitemap.
|
|
11
|
+
|
|
12
|
+
Сервер работает со свойствами, к которым есть доступ у вашего Google-аккаунта. Важная особенность: он использует точное значение свойства Search Console — domain property и URL-prefix property являются разными объектами.
|
|
13
|
+
|
|
14
|
+
- **12 инструментов.** Семь инструментов читают свойства, поисковые данные, sitemap и статус индексации; два добавляют свойство или отправляют sitemap; три могут удалить данные или вызвать произвольный метод API.
|
|
15
|
+
- **Точные ID свойств.** `https://example.com/`, `https://www.example.com/` и `sc-domain:example.com` различаются. `list_sites` показывает значение, которое нужно использовать.
|
|
16
|
+
- **Поисковые данные с контекстом.** Можно получить клики, показы, CTR и позицию по дате, странице, запросу, стране, устройству или search appearance.
|
|
17
|
+
- **Индексация, а не публикация.** Проверка URL показывает текущий статус Google, но не заставляет страницу попасть в индекс.
|
|
18
|
+
|
|
19
|
+
Начните с запроса, который только читает данные:
|
|
20
|
+
|
|
21
|
+
> Покажи 20 самых популярных поисковых запросов для моего свойства за последние 28 дней, с кликами и CTR.
|
|
22
|
+
|
|
23
|
+
[Подключить сервер](#быстрый-старт) · [Посмотреть сценарии](#что-можно-поручить) · [Открыть техническую документацию](#техническая-документация)
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## Увидеть работу за минуту
|
|
28
|
+
|
|
29
|
+
> **Вы:** Проиндексирован ли `https://example.com/pricing`? Если нет, почему?
|
|
30
|
+
>
|
|
31
|
+
> **Ассистент:** Проверяет URL и показывает вердикт индексации, покрытие, данные обхода и canonical URLs. Ничего не меняется.
|
|
32
|
+
>
|
|
33
|
+
> **Вы:** Проверь мои sitemap и подготовь повторную отправку того, где есть ошибки.
|
|
34
|
+
>
|
|
35
|
+
> **Ассистент:** Показывает sitemap, его предупреждения и ошибки, затем запрашивает подтверждение перед повторной отправкой.
|
|
36
|
+
>
|
|
37
|
+
> **Вы:** Подтверждаю.
|
|
38
|
+
>
|
|
39
|
+
> **Ассистент:** Повторно отправляет выбранный sitemap. Он не меняет содержимое страницы и не гарантирует индексацию.
|
|
40
|
+
|
|
41
|
+
## Содержание
|
|
42
|
+
|
|
43
|
+
- [Быстрый старт](#быстрый-старт)
|
|
44
|
+
- [Что можно поручить](#что-можно-поручить)
|
|
45
|
+
- [Как устроены свойства Search Console](#как-устроены-свойства-search-console)
|
|
46
|
+
- [Что может измениться](#что-может-измениться)
|
|
47
|
+
- [Как получить доступ](#как-получить-доступ)
|
|
48
|
+
- [Конфигурация](#конфигурация)
|
|
49
|
+
- [Данные, лимиты и работа в фоне](#данные-лимиты-и-работа-в-фоне)
|
|
50
|
+
- [Техническая документация](#техническая-документация)
|
|
51
|
+
- [Поддержка](#поддержка)
|
|
52
|
+
|
|
53
|
+
## Быстрый старт
|
|
54
|
+
|
|
55
|
+
Нужны Node.js 20+, Google-аккаунт с доступом к свойству Search Console и OAuth-данные Google Cloud.
|
|
56
|
+
|
|
57
|
+
1. [Подготовьте OAuth-доступ](#как-получить-доступ).
|
|
58
|
+
2. Добавьте сервер в AI-приложение.
|
|
59
|
+
3. Начните с запроса, который только читает данные.
|
|
60
|
+
|
|
61
|
+
<details open><summary><strong>Codex</strong></summary>
|
|
62
|
+
|
|
63
|
+
<br>
|
|
64
|
+
|
|
65
|
+
**В приложении:** откройте **Settings → Plugins → MCP servers**, выберите **Add server**, затем добавьте `npx -y mcp-google-search-console@latest` с `GOOGLE_SEARCH_CONSOLE_CLIENT_ID`, `GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET` и `GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN`.
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
codex mcp add google-search-console \
|
|
69
|
+
--env GOOGLE_SEARCH_CONSOLE_CLIENT_ID=your_client_id \
|
|
70
|
+
--env GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET=your_client_secret \
|
|
71
|
+
--env GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN=your_refresh_token \
|
|
72
|
+
-- npx -y mcp-google-search-console@latest
|
|
73
|
+
codex mcp list
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
[Документация Codex MCP](https://learn.chatgpt.com/docs/extend/mcp?surface=cli)
|
|
77
|
+
|
|
78
|
+
</details>
|
|
79
|
+
|
|
80
|
+
<details><summary><strong>Claude Code</strong></summary>
|
|
81
|
+
|
|
82
|
+
<br>
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
claude mcp add \
|
|
86
|
+
--env GOOGLE_SEARCH_CONSOLE_CLIENT_ID=your_client_id \
|
|
87
|
+
--env GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET=your_client_secret \
|
|
88
|
+
--env GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN=your_refresh_token \
|
|
89
|
+
--transport stdio --scope user google-search-console \
|
|
90
|
+
-- npx -y mcp-google-search-console@latest
|
|
91
|
+
claude mcp list
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
[Документация Claude Code MCP](https://code.claude.com/docs/en/mcp)
|
|
95
|
+
|
|
96
|
+
</details>
|
|
97
|
+
|
|
98
|
+
<details><summary><strong>Claude Desktop</strong></summary>
|
|
99
|
+
|
|
100
|
+
<br>
|
|
101
|
+
|
|
102
|
+
Откройте **Settings → Developer → Edit Config** и добавьте:
|
|
103
|
+
|
|
104
|
+
```json
|
|
105
|
+
{"mcpServers":{"google-search-console":{"command":"npx","args":["-y","mcp-google-search-console@latest"],"env":{"GOOGLE_SEARCH_CONSOLE_CLIENT_ID":"your_client_id","GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET":"your_client_secret","GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN":"your_refresh_token"}}}}
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Если **Edit Config** недоступна, отредактируйте `~/Library/Application Support/Claude/claude_desktop_config.json` на macOS или `%APPDATA%\Claude\claude_desktop_config.json` на Windows. [Документация Claude Desktop MCP](https://support.claude.com/en/articles/10949351-getting-started-with-local-mcp-servers-on-claude-desktop)
|
|
109
|
+
|
|
110
|
+
</details>
|
|
111
|
+
|
|
112
|
+
<details><summary><strong>Cursor</strong></summary>
|
|
113
|
+
|
|
114
|
+
<br>
|
|
115
|
+
|
|
116
|
+
Добавьте в `~/.cursor/mcp.json` на macOS/Linux или `%USERPROFILE%\.cursor\mcp.json` на Windows:
|
|
117
|
+
|
|
118
|
+
```json
|
|
119
|
+
{"mcpServers":{"google-search-console":{"type":"stdio","command":"npx","args":["-y","mcp-google-search-console@latest"],"env":{"GOOGLE_SEARCH_CONSOLE_CLIENT_ID":"your_client_id","GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET":"your_client_secret","GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN":"your_refresh_token"}}}}
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
[Документация Cursor MCP](https://cursor.com/docs/mcp)
|
|
123
|
+
|
|
124
|
+
</details>
|
|
125
|
+
|
|
126
|
+
<details><summary><strong>VS Code</strong></summary>
|
|
127
|
+
|
|
128
|
+
<br>
|
|
129
|
+
|
|
130
|
+
Запустите **MCP: Open User Configuration** и добавьте:
|
|
131
|
+
|
|
132
|
+
```json
|
|
133
|
+
{"servers":{"google-search-console":{"type":"stdio","command":"npx","args":["-y","mcp-google-search-console@latest"],"env":{"GOOGLE_SEARCH_CONSOLE_CLIENT_ID":"${input:gsc_client_id}","GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET":"${input:gsc_client_secret}","GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN":"${input:gsc_refresh_token}"}}},"inputs":[{"type":"promptString","id":"gsc_client_id","description":"Google OAuth client ID"},{"type":"promptString","id":"gsc_client_secret","description":"Google OAuth client secret","password":true},{"type":"promptString","id":"gsc_refresh_token","description":"Google OAuth refresh token","password":true}]}
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
Проверьте сервер командой **MCP: List Servers**. [Документация VS Code MCP](https://code.visualstudio.com/docs/agent-customization/mcp-servers)
|
|
137
|
+
|
|
138
|
+
</details>
|
|
139
|
+
|
|
140
|
+
## Что можно поручить
|
|
141
|
+
|
|
142
|
+
### Найти поисковые возможности
|
|
143
|
+
|
|
144
|
+
- Какие запросы и страницы принесли больше всего кликов в этом месяце?
|
|
145
|
+
- Какие страницы потеряли клики по сравнению с прошлым периодом?
|
|
146
|
+
- Покажи запросы с `mcp`, где средняя позиция ниже 10.
|
|
147
|
+
|
|
148
|
+
### Проверить индексацию и sitemap
|
|
149
|
+
|
|
150
|
+
- Проиндексирован ли этот URL? Покажи покрытие, обход и canonical information.
|
|
151
|
+
- В каких отправленных sitemap есть ошибки или предупреждения?
|
|
152
|
+
- Повторно отправь этот sitemap, сначала показав его текущий статус.
|
|
153
|
+
|
|
154
|
+
### Аккуратно управлять свойствами
|
|
155
|
+
|
|
156
|
+
- Покажи свойства Search Console, к которым у меня есть доступ.
|
|
157
|
+
- Добавь это точное значение свойства; подтверждение владения я пройду отдельно.
|
|
158
|
+
- Удали это свойство из аккаунта после подтверждения.
|
|
159
|
+
|
|
160
|
+
## Как устроены свойства Search Console
|
|
161
|
+
|
|
162
|
+
URL-prefix property должен содержать протокол и завершающий слеш: например, `https://example.com/`. Domain property записывается как `sc-domain:example.com`. Почти совпадающее значение вернёт 403 или 404, поэтому используйте точное значение от `list_sites`.
|
|
163
|
+
|
|
164
|
+
`add_site` только регистрирует свойство. Подтверждение владения остаётся в интерфейсе Search Console или Site Verification API. Поисковые данные используют тихоокеанское время; `end_date` включительно, а финальные данные обычно отстают на два–три дня. `data_state: "all"` может включить более свежие, но меняющиеся строки.
|
|
165
|
+
|
|
166
|
+
## Что может измениться
|
|
167
|
+
|
|
168
|
+
| Операция | Что происходит | Граница подтверждения |
|
|
169
|
+
|---|---|---|
|
|
170
|
+
| Просмотр свойств, аналитики, sitemap и статуса URL | Читает данные Search Console | Ничего не меняет |
|
|
171
|
+
| Добавление свойства | Добавляет запись свойства, но не подтверждает его | Меняет доступ аккаунта |
|
|
172
|
+
| Отправка или повторная отправка sitemap | Запрашивает обработку sitemap | Меняет состояние Search Console |
|
|
173
|
+
| Удаление свойства | Отвязывает свойство от аккаунта; данные Google не удаляются | Разрушительно |
|
|
174
|
+
| Удаление sitemap | Удаляет отправленный sitemap | Разрушительно |
|
|
175
|
+
| Технический запрос API | Может вызвать endpoint записи или удаления | Потенциально разрушительно |
|
|
176
|
+
|
|
177
|
+
Как AI-приложение спрашивает подтверждение, определяет само приложение. Сервер помечает чтение, запись и удаление, чтобы оно отличило проверку от изменения.
|
|
178
|
+
|
|
179
|
+
## Как получить доступ
|
|
180
|
+
|
|
181
|
+
Для данных Search Console нужен Google OAuth 2.0: API-ключа недостаточно.
|
|
182
|
+
|
|
183
|
+
1. Создайте или выберите проект Google Cloud и включите **Google Search Console API**.
|
|
184
|
+
2. Настройте OAuth consent screen и создайте OAuth-клиент типа **Desktop app**.
|
|
185
|
+
3. Через [OAuth 2.0 Playground](https://developers.google.com/oauthplayground) с включённым **Use your own OAuth credentials** авторизуйте Google-аккаунт с доступом к свойствам и получите refresh token.
|
|
186
|
+
4. Используйте `https://www.googleapis.com/auth/webmasters` для sitemap и изменения свойств. `https://www.googleapis.com/auth/webmasters.readonly` подходит, только если нужен намеренно read-only доступ.
|
|
187
|
+
|
|
188
|
+
Refresh token OAuth-приложения в режиме Testing может истечь через семь дней. Для долгого доступа опубликуйте приложение или используйте Internal-приложение Workspace. Храните client secret и refresh token как пароли.
|
|
189
|
+
|
|
190
|
+
## Конфигурация
|
|
191
|
+
|
|
192
|
+
| Переменная | Обязательна | Описание |
|
|
193
|
+
|---|---|---|
|
|
194
|
+
| `GOOGLE_SEARCH_CONSOLE_CLIENT_ID` | Да* | OAuth client ID. |
|
|
195
|
+
| `GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET` | Да* | OAuth client secret. |
|
|
196
|
+
| `GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN` | Да* | OAuth refresh token. |
|
|
197
|
+
| `GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN` | Да* | Короткоживущая альтернатива OAuth-тройке. |
|
|
198
|
+
| `GOOGLE_SEARCH_CONSOLE_API_BASE` | Нет | Переопределяет базовый URL API. |
|
|
199
|
+
| `GOOGLE_SEARCH_CONSOLE_TIMEOUT_MS` | Нет | Тайм-аут запроса; по умолчанию `60000` мс. |
|
|
200
|
+
| `GOOGLE_SEARCH_CONSOLE_MAX_RETRIES` | Нет | Повторы временных ошибок; по умолчанию `3`. |
|
|
201
|
+
|
|
202
|
+
\* Передайте OAuth-тройку или access token.
|
|
203
|
+
|
|
204
|
+
## Данные, лимиты и работа в фоне
|
|
205
|
+
|
|
206
|
+
- **Приватность.** Локальный сервер вызывает Google и отправляет анонимную телеметрию с ID установки, версиями и именами инструментов — но не OAuth-токены, данные свойств, аргументы или промпты. Чтобы отключить её, задайте `ASKADS_TELEMETRY=0`.
|
|
207
|
+
- **Лимиты API.** URL inspection разрешает 2 000 проверок на свойство в сутки и 600 в минуту. Analytics возвращает максимум 25 000 строк за вызов; анонимизированные long-tail запросы никогда не возвращаются. Используйте пагинацию и не проверяйте сайт URL за URL.
|
|
208
|
+
- **Постоянного наблюдения нет.** Сервер работает только при вызове. Если AI-приложение поддерживает задания по расписанию, оно может периодически проверять sitemap или важный URL.
|
|
209
|
+
|
|
210
|
+
## Техническая документация
|
|
211
|
+
|
|
212
|
+
- [Каталог MCP-возможностей](./docs/capabilities/index.md) — страницы по пользовательским задачам для каждого инструмента.
|
|
213
|
+
- [Все инструменты и параметры](./docs/TOOLS.md)
|
|
214
|
+
- [Документация по разработке](./docs/DEVELOPMENT.md)
|
|
215
|
+
- [Документация по публикации](./docs/PUBLISHING.md)
|
|
216
|
+
- [Google Search Console API](https://developers.google.com/webmaster-tools)
|
|
217
|
+
|
|
218
|
+
## Поддержка
|
|
219
|
+
|
|
220
|
+
Нашли ошибку или не хватает сценария? [Создайте issue](https://github.com/A1-x-Tech/mcp-google-search-console/issues) или напишите в [Telegram](https://t.me/a1_mcp).
|
|
221
|
+
|
|
222
|
+
<br>
|
|
223
|
+
|
|
224
|
+
<p align="center">
|
|
225
|
+
<img src="https://github.com/ztemerbekov/a1-yandex-kit-skills/raw/main/assets/images/mona-hifive-yandex-kit-warm.gif" alt="Две Моны дают пять" width="256">
|
|
226
|
+
</p>
|
|
227
|
+
|
|
228
|
+
<p align="center">
|
|
229
|
+
Вы дочитали до конца!
|
|
230
|
+
</p>
|
package/dist/client.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { GoogleSearchConsoleError } from "./types.js";
|
|
2
|
+
import { CredentialsError } from "./config.js";
|
|
2
3
|
/** Google's OAuth2 token endpoint — refresh tokens are exchanged here. */
|
|
3
4
|
const TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
4
5
|
/**
|
|
@@ -34,11 +35,15 @@ export class GoogleSearchConsoleClient {
|
|
|
34
35
|
* Returns a valid Bearer token. With the refresh triple configured, mints an
|
|
35
36
|
* access token from the refresh token and caches it until shortly before it
|
|
36
37
|
* expires (concurrent callers share one in-flight refresh); otherwise the
|
|
37
|
-
* static GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN is used as-is.
|
|
38
|
+
* static GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN is used as-is. With neither
|
|
39
|
+
* configured, throws {@link CredentialsError} BEFORE any fetch — a missing
|
|
40
|
+
* setup must never enter the retry/backoff loop or trigger the 401 re-mint,
|
|
41
|
+
* because no amount of retrying mints credentials.
|
|
38
42
|
*/
|
|
39
43
|
async accessToken(forceRefresh = false) {
|
|
40
44
|
if (!this.canRefresh()) {
|
|
41
|
-
|
|
45
|
+
if (!this.config.accessToken)
|
|
46
|
+
throw new CredentialsError();
|
|
42
47
|
return this.config.accessToken;
|
|
43
48
|
}
|
|
44
49
|
if (!forceRefresh && this.cachedToken && Date.now() < this.cachedToken.expiresAt) {
|
package/dist/config.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
/** Default Google Search Console API host (serves both webmasters/v3 and v1). */
|
|
2
|
-
const DEFAULT_BASE = "https://searchconsole.googleapis.com";
|
|
2
|
+
export const DEFAULT_BASE = "https://searchconsole.googleapis.com";
|
|
3
3
|
/**
|
|
4
|
-
* A
|
|
5
|
-
*
|
|
6
|
-
* the machine-readable code that ships with that ping
|
|
4
|
+
* A malformed environment variable. Thrown instead of exiting on the spot so
|
|
5
|
+
* index.ts can catch it, report the drop-off and start degraded instead of
|
|
6
|
+
* dying; `reason` is the machine-readable code that ships with that ping
|
|
7
|
+
* (never a variable's value).
|
|
7
8
|
*/
|
|
8
9
|
export class ConfigError extends Error {
|
|
9
10
|
reason;
|
|
@@ -13,12 +14,43 @@ export class ConfigError extends Error {
|
|
|
13
14
|
this.reason = reason;
|
|
14
15
|
}
|
|
15
16
|
}
|
|
16
|
-
|
|
17
|
-
|
|
17
|
+
/**
|
|
18
|
+
* What a tool call without credentials reads. The first sentence is the
|
|
19
|
+
* historical startup error, verbatim — the rest exists because credentials come
|
|
20
|
+
* only from the environment, so the fix is an operator action plus a restart,
|
|
21
|
+
* never a retry.
|
|
22
|
+
*/
|
|
23
|
+
export const MISSING_CREDENTIALS_MESSAGE = "Google OAuth credentials are required: set GOOGLE_SEARCH_CONSOLE_CLIENT_ID + " +
|
|
24
|
+
"GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET + GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN (recommended), or " +
|
|
25
|
+
"GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN with a short-lived access token. " +
|
|
26
|
+
"This is not a network failure and retrying will not help: the operator must set these " +
|
|
27
|
+
"environment variables in the MCP client's server config and restart the server — they are " +
|
|
28
|
+
"read only at startup.";
|
|
29
|
+
/**
|
|
30
|
+
* Raised when a tool call needs credentials and none were configured. The
|
|
31
|
+
* message is the whole point of the class: it is the only text the calling
|
|
32
|
+
* model reads about the missing setup, so it names the fix (which variables,
|
|
33
|
+
* and that a restart is needed) instead of the failure.
|
|
34
|
+
*/
|
|
35
|
+
export class CredentialsError extends Error {
|
|
36
|
+
constructor(message = MISSING_CREDENTIALS_MESSAGE) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.name = "CredentialsError";
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** True when the config carries usable credentials (the full refresh triple or a static token). */
|
|
42
|
+
export function hasCredentials(config) {
|
|
43
|
+
return Boolean(config.accessToken || (config.clientId && config.clientSecret && config.refreshToken));
|
|
18
44
|
}
|
|
19
45
|
/**
|
|
20
|
-
* Builds the client config from environment variables
|
|
21
|
-
*
|
|
46
|
+
* Builds the client config from environment variables.
|
|
47
|
+
*
|
|
48
|
+
* Missing credentials are NOT an error here: the server starts anyway and the
|
|
49
|
+
* client raises {@link CredentialsError} on the first tool call, so an
|
|
50
|
+
* unconfigured install completes the MCP handshake and carries the fix into
|
|
51
|
+
* the session instead of dying before it with nothing to read. A malformed
|
|
52
|
+
* setup — the refresh triple set only partially — still throws, because
|
|
53
|
+
* guessing what the user meant is worse.
|
|
22
54
|
*
|
|
23
55
|
* GOOGLE_SEARCH_CONSOLE_CLIENT_ID OAuth2 client id (refresh flow, recommended)
|
|
24
56
|
* GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET OAuth2 client secret (refresh flow)
|
|
@@ -35,10 +67,7 @@ export function loadConfig() {
|
|
|
35
67
|
const accessToken = process.env.GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN;
|
|
36
68
|
const oauthProvided = [clientId, clientSecret, refreshToken].filter(Boolean).length;
|
|
37
69
|
if (oauthProvided > 0 && oauthProvided < 3) {
|
|
38
|
-
|
|
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");
|
|
70
|
+
throw new ConfigError("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");
|
|
42
71
|
}
|
|
43
72
|
const timeoutMs = Number(process.env.GOOGLE_SEARCH_CONSOLE_TIMEOUT_MS);
|
|
44
73
|
const maxRetries = Number(process.env.GOOGLE_SEARCH_CONSOLE_MAX_RETRIES);
|
package/dist/index.js
CHANGED
|
@@ -3,13 +3,42 @@ import { readFileSync } from "node:fs";
|
|
|
3
3
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4
4
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
5
5
|
import { GoogleSearchConsoleClient } from "./client.js";
|
|
6
|
-
import { ConfigError, loadConfig } from "./config.js";
|
|
6
|
+
import { ConfigError, DEFAULT_BASE, hasCredentials, loadConfig } from "./config.js";
|
|
7
7
|
import { instrumentToolCalls, Telemetry } from "./telemetry.js";
|
|
8
8
|
import { registerSiteTools } from "./tools/sites.js";
|
|
9
9
|
import { registerSitemapTools } from "./tools/sitemaps.js";
|
|
10
10
|
import { registerAnalyticsTools } from "./tools/analytics.js";
|
|
11
11
|
import { registerInspectionTools } from "./tools/inspection.js";
|
|
12
12
|
import { registerRawTool } from "./tools/raw.js";
|
|
13
|
+
/**
|
|
14
|
+
* Prepended to every session as the `instructions` of the MCP initialize result
|
|
15
|
+
* — the only prose the calling model sees before it picks a tool. It carries
|
|
16
|
+
* what the tool list cannot: which product this is, what the API refuses to do,
|
|
17
|
+
* what a call costs, and how its errors decode.
|
|
18
|
+
*/
|
|
19
|
+
const INSTRUCTIONS = "Google Search Console reports how a property performs in organic Google Search and how its URLs " +
|
|
20
|
+
"stand in the index — not Google Analytics (on-site traffic), not Google Ads. Nothing here can " +
|
|
21
|
+
"request (re)indexing; a sitemap submission is the only nudge, and writes are limited to " +
|
|
22
|
+
"linking/unlinking a property and submitting/removing sitemaps. Batch work is where it bites: " +
|
|
23
|
+
"2,000 URL inspections per property a day and 200 sites/sitemaps calls a minute — never sweep a " +
|
|
24
|
+
"whole site; 429s and read-side 5xx are already retried inside the server, so a returned error is " +
|
|
25
|
+
"final. Take property ids verbatim from list_sites: a 403/404 is usually a near-miss id (scheme, " +
|
|
26
|
+
"www, trailing slash, sc-domain:), not a permissions problem; a 403 on a write points at a " +
|
|
27
|
+
"readonly token; auth failing on every call means a dead refresh token (they expire after 7 days " +
|
|
28
|
+
"while the OAuth consent screen is in Testing). Empty rows[] on the first page usually means the " +
|
|
29
|
+
"dates fall in the 2-3 day finalization lag or you queried a sibling property, not zero traffic. " +
|
|
30
|
+
"Confirm with the user before delete_site or delete_sitemap.";
|
|
31
|
+
/**
|
|
32
|
+
* Prepended to INSTRUCTIONS when no credentials are configured. The model reads
|
|
33
|
+
* this before it picks a tool, so an unconfigured session opens with the fix
|
|
34
|
+
* rather than with a failed call. There is no in-chat login here: credentials
|
|
35
|
+
* come only from the environment, so the fix is an operator action + restart.
|
|
36
|
+
*/
|
|
37
|
+
const UNCONFIGURED_PREFIX = "ATTENTION: Google Search Console is not connected yet — no credentials are configured, so " +
|
|
38
|
+
"every tool call will fail. The operator must set GOOGLE_SEARCH_CONSOLE_CLIENT_ID + " +
|
|
39
|
+
"GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET + GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN (recommended), or " +
|
|
40
|
+
"GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN with a short-lived access token, in the MCP client's " +
|
|
41
|
+
"server config and restart this server — the variables are read only at startup. ";
|
|
13
42
|
/** Reads the package version so the server reports its real version to MCP clients. */
|
|
14
43
|
function readVersion() {
|
|
15
44
|
try {
|
|
@@ -21,21 +50,27 @@ function readVersion() {
|
|
|
21
50
|
}
|
|
22
51
|
}
|
|
23
52
|
/**
|
|
24
|
-
* Loads the config
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
53
|
+
* Loads the config without dying on a bad value. A server that exits here never
|
|
54
|
+
* completes the MCP handshake, so the user sees a dead server and no reason.
|
|
55
|
+
* Instead the problem is carried into the session, where the model can read it
|
|
56
|
+
* and relay it: the config degrades to "no credentials" and every tool call
|
|
57
|
+
* fails with the actionable message.
|
|
28
58
|
*/
|
|
29
|
-
|
|
59
|
+
function loadConfigOrDegraded(telemetry) {
|
|
30
60
|
try {
|
|
31
|
-
return loadConfig();
|
|
61
|
+
return { config: loadConfig() };
|
|
32
62
|
}
|
|
33
63
|
catch (err) {
|
|
34
64
|
if (!(err instanceof ConfigError))
|
|
35
65
|
throw err;
|
|
36
66
|
console.error(`Error: ${err.message}`);
|
|
37
|
-
|
|
38
|
-
|
|
67
|
+
// Fire-and-forget now that the process survives: the historical
|
|
68
|
+
// `startup_failed` funnel stays comparable, but nothing blocks startup.
|
|
69
|
+
telemetry.send("startup_failed", { reason: err.reason });
|
|
70
|
+
return {
|
|
71
|
+
config: { apiBase: process.env.GOOGLE_SEARCH_CONSOLE_API_BASE || DEFAULT_BASE },
|
|
72
|
+
problem: err,
|
|
73
|
+
};
|
|
39
74
|
}
|
|
40
75
|
}
|
|
41
76
|
async function main() {
|
|
@@ -43,16 +78,30 @@ async function main() {
|
|
|
43
78
|
// opt out with ASKADS_TELEMETRY=0. Built before the config so missing
|
|
44
79
|
// credentials can be reported; wired to the server before tools register.
|
|
45
80
|
const telemetry = new Telemetry(readVersion());
|
|
46
|
-
const config =
|
|
81
|
+
const { config, problem } = loadConfigOrDegraded(telemetry);
|
|
47
82
|
const client = new GoogleSearchConsoleClient(config);
|
|
83
|
+
// Decided once, at startup: credentials come only from the environment, so
|
|
84
|
+
// "restart after setting the variables" is the accurate advice to give.
|
|
85
|
+
const connected = hasCredentials(config);
|
|
86
|
+
// `instructions` rides in the options argument (not serverInfo) — that is what
|
|
87
|
+
// the SDK copies into the initialize result.
|
|
48
88
|
const server = new McpServer({
|
|
49
89
|
name: "mcp-google-search-console",
|
|
50
90
|
version: readVersion(),
|
|
91
|
+
}, {
|
|
92
|
+
instructions: connected
|
|
93
|
+
? INSTRUCTIONS
|
|
94
|
+
: UNCONFIGURED_PREFIX + (problem ? `Configuration problem: ${problem.message} ` : "") + INSTRUCTIONS,
|
|
51
95
|
});
|
|
52
96
|
instrumentToolCalls(server, telemetry);
|
|
53
97
|
server.server.oninitialized = () => {
|
|
54
98
|
telemetry.setClientInfo(server.server.getClientVersion());
|
|
55
|
-
|
|
99
|
+
// Split on purpose: `server_start` keeps meaning "a usable install started",
|
|
100
|
+
// so the unconfigured case gets its own event instead of inflating that number.
|
|
101
|
+
if (connected)
|
|
102
|
+
telemetry.send("server_start");
|
|
103
|
+
else
|
|
104
|
+
telemetry.send("unconfigured_start", { reason: problem?.reason ?? "missing_credentials" });
|
|
56
105
|
};
|
|
57
106
|
registerSiteTools(server, client);
|
|
58
107
|
registerSitemapTools(server, client);
|
|
@@ -61,7 +110,7 @@ async function main() {
|
|
|
61
110
|
registerRawTool(server, client);
|
|
62
111
|
const transport = new StdioServerTransport();
|
|
63
112
|
await server.connect(transport);
|
|
64
|
-
console.error(
|
|
113
|
+
console.error(`mcp-google-search-console running on stdio${connected ? "" : " (no credentials — set the environment variables and restart)"}`);
|
|
65
114
|
}
|
|
66
115
|
main().catch((err) => {
|
|
67
116
|
console.error("Fatal error starting mcp-google-search-console:", err);
|
package/dist/telemetry.js
CHANGED
|
@@ -69,9 +69,9 @@ export class Telemetry {
|
|
|
69
69
|
void this.post(event, fields);
|
|
70
70
|
}
|
|
71
71
|
/**
|
|
72
|
-
* The same ping, awaited. Only for
|
|
73
|
-
*
|
|
74
|
-
*
|
|
72
|
+
* The same ping, awaited. Only for a caller that exits right after — a
|
|
73
|
+
* fire-and-forget request would die in flight with the process. No startup
|
|
74
|
+
* path needs it anymore (a config problem degrades instead of exiting).
|
|
75
75
|
*/
|
|
76
76
|
async sendBlocking(event, fields = {}) {
|
|
77
77
|
await this.post(event, fields);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mcp-google-search-console",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
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
5
|
"mcpName": "io.github.A1-x-Tech/mcp-google-search-console",
|
|
6
6
|
"type": "module",
|
package/test/dist-smoke.test.js
CHANGED
|
@@ -114,6 +114,12 @@ test("dist binary completes a real MCP handshake over stdio and lists every tool
|
|
|
114
114
|
assert.equal(server?.name, "mcp-google-search-console");
|
|
115
115
|
assert.match(String(server?.version), /^\d+\.\d+\.\d+$/);
|
|
116
116
|
|
|
117
|
+
// The initialize result must carry the instructions block — the only prose
|
|
118
|
+
// the calling model reads before it picks a tool.
|
|
119
|
+
const instructions = client.getInstructions() ?? "";
|
|
120
|
+
assert.ok(instructions.length > 200, `initialize must carry instructions (got ${instructions.length} chars)`);
|
|
121
|
+
assert.match(instructions, /list_sites/);
|
|
122
|
+
|
|
117
123
|
const { tools } = await client.listTools();
|
|
118
124
|
assert.deepEqual(tools.map((t) => t.name).sort(), ALL_TOOLS);
|
|
119
125
|
|
|
@@ -127,3 +133,46 @@ test("dist binary completes a real MCP handshake over stdio and lists every tool
|
|
|
127
133
|
await client.close();
|
|
128
134
|
}
|
|
129
135
|
});
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The degraded-start contract: without any credentials the binary used to
|
|
139
|
+
* exit(1) before the handshake, leaving the client a dead server and no reason.
|
|
140
|
+
* It must now start, list every tool, open the instructions with the fix, and
|
|
141
|
+
* answer a tool call with the actionable error — offline: the CredentialsError
|
|
142
|
+
* fires before any fetch, so this test never touches the network.
|
|
143
|
+
*/
|
|
144
|
+
test("dist binary starts without credentials: handshake, tool list, actionable call error", async () => {
|
|
145
|
+
const env = Object.fromEntries(
|
|
146
|
+
Object.entries(process.env).filter(
|
|
147
|
+
([key, value]) => value !== undefined && !key.startsWith("GOOGLE_SEARCH_CONSOLE_"),
|
|
148
|
+
),
|
|
149
|
+
);
|
|
150
|
+
env.ASKADS_TELEMETRY = "0"; // keep the suite offline
|
|
151
|
+
const transport = new StdioClientTransport({
|
|
152
|
+
command: process.execPath,
|
|
153
|
+
args: [fileURLToPath(new URL("../dist/index.js", import.meta.url))],
|
|
154
|
+
env,
|
|
155
|
+
stderr: "pipe",
|
|
156
|
+
});
|
|
157
|
+
const client = new Client({ name: "dist-smoke-unconfigured", version: "0.0.0" });
|
|
158
|
+
await client.connect(transport);
|
|
159
|
+
try {
|
|
160
|
+
// The model must read the fix before it picks a tool.
|
|
161
|
+
const instructions = client.getInstructions() ?? "";
|
|
162
|
+
assert.match(instructions, /not connected/);
|
|
163
|
+
assert.match(instructions, /GOOGLE_SEARCH_CONSOLE_CLIENT_ID/);
|
|
164
|
+
assert.match(instructions, /restart/);
|
|
165
|
+
|
|
166
|
+
const { tools } = await client.listTools();
|
|
167
|
+
assert.deepEqual(tools.map((t) => t.name).sort(), ALL_TOOLS);
|
|
168
|
+
|
|
169
|
+
// A tool call fails with the exact message instead of killing the server.
|
|
170
|
+
const result = await client.callTool({ name: "list_sites", arguments: {} });
|
|
171
|
+
assert.equal(result.isError, true);
|
|
172
|
+
const text = result.content.map((c) => c.text ?? "").join(" ");
|
|
173
|
+
assert.match(text, /Google OAuth credentials are required: set GOOGLE_SEARCH_CONSOLE_CLIENT_ID/);
|
|
174
|
+
assert.match(text, /restart the server/);
|
|
175
|
+
} finally {
|
|
176
|
+
await client.close();
|
|
177
|
+
}
|
|
178
|
+
});
|