mcp-google-search-console 1.1.0 → 1.3.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 +41 -22
- package/README.ru.md +42 -21
- package/dist/client.js +57 -6
- package/dist/index.js +8 -8
- package/dist/telemetry.js +217 -8
- package/dist/tools/auth.js +113 -0
- package/dist/tools/util.js +5 -0
- package/package.json +2 -1
- package/test/dist-smoke.test.js +37 -4
package/README.md
CHANGED
|
@@ -3,15 +3,16 @@
|
|
|
3
3
|
**English** | [Русский](./README.ru.md)
|
|
4
4
|
|
|
5
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
6
|
[](https://glama.ai/mcp/servers/A1-x-Tech/mcp-google-search-console)
|
|
7
|
+
[](https://github.com/A1-x-Tech/mcp-google-search-console/actions/workflows/ci.yml)
|
|
8
8
|
[](./LICENSE)
|
|
9
9
|
|
|
10
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.
|
|
11
11
|
|
|
12
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.
|
|
13
13
|
|
|
14
|
-
- **
|
|
14
|
+
- **18 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
|
+
- **Connects from the conversation.** Say "connect Google Search Console": the server walks you through the OAuth client, catches Google's redirect on `127.0.0.1` with PKCE and keeps the tokens itself — no config files, no restart.
|
|
15
16
|
- **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
17
|
- **Search data with context.** Query clicks, impressions, CTR and position by date, page, query, country, device or search appearance.
|
|
17
18
|
- **Indexing, not publishing.** URL inspection explains Google’s current status; it does not force a page into the index.
|
|
@@ -52,23 +53,26 @@ Start with a read-only question:
|
|
|
52
53
|
|
|
53
54
|
## Quick start
|
|
54
55
|
|
|
55
|
-
You need Node.js 20
|
|
56
|
+
You need Node.js 20+ and a Google account. Credentials are not required at install time — the server connects from the conversation.
|
|
56
57
|
|
|
57
|
-
1.
|
|
58
|
-
2.
|
|
58
|
+
1. Add the server to your AI app.
|
|
59
|
+
2. Say "connect Google Search Console": the assistant walks you through [creating the OAuth client and approving access](#getting-access) without editing config files.
|
|
59
60
|
3. Start with the read-only question above.
|
|
60
61
|
|
|
61
62
|
<details open><summary><strong>Codex</strong></summary>
|
|
62
63
|
|
|
63
64
|
<br>
|
|
64
65
|
|
|
66
|
+
<<<<<<< Updated upstream
|
|
67
|
+
**In the app:** open **Settings → MCP servers**, select **Add server**, choose **STDIO**, enter the command `npx -y mcp-google-search-console@latest` and environment variables `GOOGLE_SEARCH_CONSOLE_CLIENT_ID`, `GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET`, `GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN`, then select **Save** and **Restart**.
|
|
68
|
+
||||||| Stash base
|
|
65
69
|
**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`.
|
|
70
|
+
=======
|
|
71
|
+
**In the app:** open **Settings → Plugins → MCP servers**, choose **Add server**, then add `npx -y mcp-google-search-console@latest`.
|
|
72
|
+
>>>>>>> Stashed changes
|
|
66
73
|
|
|
67
74
|
```bash
|
|
68
75
|
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
76
|
-- npx -y mcp-google-search-console@latest
|
|
73
77
|
codex mcp list
|
|
74
78
|
```
|
|
@@ -83,9 +87,6 @@ codex mcp list
|
|
|
83
87
|
|
|
84
88
|
```bash
|
|
85
89
|
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
90
|
--transport stdio --scope user google-search-console \
|
|
90
91
|
-- npx -y mcp-google-search-console@latest
|
|
91
92
|
claude mcp list
|
|
@@ -99,13 +100,15 @@ claude mcp list
|
|
|
99
100
|
|
|
100
101
|
<br>
|
|
101
102
|
|
|
102
|
-
|
|
103
|
+
The current official path is **Settings → Extensions**. For a custom desktop extension, open **Advanced settings → Extension Developer → Install Extension…**, select a `.mcpb` file and follow the prompts.
|
|
104
|
+
|
|
105
|
+
This repository currently publishes an npm stdio package and does not contain a `.mcpb` bundle. For Claude Desktop builds that still support local configuration, use the following JSON stdio configuration as a fallback:
|
|
103
106
|
|
|
104
107
|
```json
|
|
105
|
-
{"mcpServers":{"google-search-console":{"command":"npx","args":["-y","mcp-google-search-console@latest"]
|
|
108
|
+
{"mcpServers":{"google-search-console":{"command":"npx","args":["-y","mcp-google-search-console@latest"]}}}
|
|
106
109
|
```
|
|
107
110
|
|
|
108
|
-
|
|
111
|
+
In those builds, save it to `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS or `%APPDATA%\Claude\claude_desktop_config.json` on Windows.
|
|
109
112
|
|
|
110
113
|
[Claude Desktop MCP documentation](https://support.claude.com/en/articles/10949351-getting-started-with-local-mcp-servers-on-claude-desktop)
|
|
111
114
|
|
|
@@ -118,7 +121,7 @@ If **Edit Config** is unavailable, edit `~/Library/Application Support/Claude/cl
|
|
|
118
121
|
Add to `~/.cursor/mcp.json` on macOS/Linux or `%USERPROFILE%\.cursor\mcp.json` on Windows:
|
|
119
122
|
|
|
120
123
|
```json
|
|
121
|
-
{"mcpServers":{"google-search-console":{"type":"stdio","command":"npx","args":["-y","mcp-google-search-console@latest"]
|
|
124
|
+
{"mcpServers":{"google-search-console":{"type":"stdio","command":"npx","args":["-y","mcp-google-search-console@latest"]}}}
|
|
122
125
|
```
|
|
123
126
|
|
|
124
127
|
[Cursor MCP documentation](https://cursor.com/docs/mcp)
|
|
@@ -132,7 +135,7 @@ Add to `~/.cursor/mcp.json` on macOS/Linux or `%USERPROFILE%\.cursor\mcp.json` o
|
|
|
132
135
|
Run **MCP: Open User Configuration** and add:
|
|
133
136
|
|
|
134
137
|
```json
|
|
135
|
-
{"servers":{"google-search-console":{"type":"stdio","command":"npx","args":["-y","mcp-google-search-console@latest"]
|
|
138
|
+
{"servers":{"google-search-console":{"type":"stdio","command":"npx","args":["-y","mcp-google-search-console@latest"]}}}
|
|
136
139
|
```
|
|
137
140
|
|
|
138
141
|
Check it with **MCP: List Servers**. [VS Code MCP documentation](https://code.visualstudio.com/docs/agent-customization/mcp-servers)
|
|
@@ -180,7 +183,20 @@ The AI client controls confirmation prompts. The server marks reads, writes and
|
|
|
180
183
|
|
|
181
184
|
## Getting access
|
|
182
185
|
|
|
183
|
-
Search Console
|
|
186
|
+
Google Search Console requires OAuth 2.0; an API key is not enough. There are two ways in, and the first one needs no configuration files.
|
|
187
|
+
|
|
188
|
+
### Connect from the chat (recommended)
|
|
189
|
+
|
|
190
|
+
Say "connect Google Search Console" and the assistant runs the flow with you:
|
|
191
|
+
|
|
192
|
+
1. `setup_instructions` prints the checklist: create or select a Google Cloud project, enable **Google Search Console API**, configure the consent screen and create a **Desktop app** OAuth client.
|
|
193
|
+
2. Download that client's JSON ("Download JSON") and give the assistant its **path** — `set_client` stores it owner-only. The secret never goes through the conversation.
|
|
194
|
+
3. `start_login` returns a Google consent link. Open it **on this machine** and approve; the code comes back to a one-shot listener on `127.0.0.1` (PKCE), never through the chat.
|
|
195
|
+
4. `finish_login` exchanges the code and saves the tokens to `~/.config/mcp-google-search-console/credentials.json` (mode 0600) and verifies them with a real Google Search Console API call — so an API that is still switched off is caught right there.
|
|
196
|
+
|
|
197
|
+
The tokens are re-read on every call, so the connection works immediately — no restart of the AI app. `auth_status` shows what is connected, `logout` revokes and deletes it.
|
|
198
|
+
|
|
199
|
+
### Environment variables (CI, unattended installs)
|
|
184
200
|
|
|
185
201
|
1. Create or select a Google Cloud project and enable **Google Search Console API**.
|
|
186
202
|
2. Configure the OAuth consent screen and create a **Desktop app** OAuth client.
|
|
@@ -191,12 +207,15 @@ Testing-mode refresh tokens can expire after seven days. Publish the OAuth app,
|
|
|
191
207
|
|
|
192
208
|
## Configuration
|
|
193
209
|
|
|
210
|
+
Every variable is optional — with none of them the server connects [from the chat](#connect-from-the-chat-recommended).
|
|
211
|
+
|
|
194
212
|
| Variable | Required | Description |
|
|
195
213
|
|---|---|---|
|
|
196
|
-
| `GOOGLE_SEARCH_CONSOLE_CLIENT_ID` |
|
|
197
|
-
| `GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET` |
|
|
198
|
-
| `GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN` |
|
|
199
|
-
| `GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN` |
|
|
214
|
+
| `GOOGLE_SEARCH_CONSOLE_CLIENT_ID` | No* | OAuth client ID. |
|
|
215
|
+
| `GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET` | No* | OAuth client secret. |
|
|
216
|
+
| `GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN` | No* | OAuth refresh token. |
|
|
217
|
+
| `GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN` | No* | Short-lived alternative to the OAuth trio. |
|
|
218
|
+
| `GOOGLE_SEARCH_CONSOLE_OAUTH_PORT` | No | Fixed loopback port for the in-chat login; useful over SSH port forwarding. |
|
|
200
219
|
| `GOOGLE_SEARCH_CONSOLE_API_BASE` | No | API base URL override. |
|
|
201
220
|
| `GOOGLE_SEARCH_CONSOLE_TIMEOUT_MS` | No | Per-request timeout; default `60000` ms. |
|
|
202
221
|
| `GOOGLE_SEARCH_CONSOLE_MAX_RETRIES` | No | Temporary-error retries; default `3`. |
|
|
@@ -205,7 +224,7 @@ Testing-mode refresh tokens can expire after seven days. Publish the OAuth app,
|
|
|
205
224
|
|
|
206
225
|
## Data, limits and background work
|
|
207
226
|
|
|
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.
|
|
227
|
+
- **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. For each tool call it also sends the outcome and, on failure, an excerpt of the error text with e-mails, addresses, tokens, numbers of 4+ digits and quoted text replaced by `#`; a value from your request can appear in it if the error text contains it. Set `ASKADS_TELEMETRY=0` to opt out.
|
|
209
228
|
- **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
229
|
- **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.
|
|
211
230
|
|
package/README.ru.md
CHANGED
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
|
|
12
12
|
Сервер работает со свойствами, к которым есть доступ у вашего Google-аккаунта. Важная особенность: он использует точное значение свойства Search Console — domain property и URL-prefix property являются разными объектами.
|
|
13
13
|
|
|
14
|
-
- **
|
|
14
|
+
- **18 инструментов.** Семь инструментов читают свойства, поисковые данные, sitemap и статус индексации; два добавляют свойство или отправляют sitemap; три могут удалить данные или вызвать произвольный метод API.
|
|
15
|
+
- **Подключение из диалога.** Скажите «подключи Google Search Console»: сервер проведёт через создание OAuth-клиента, поймает редирект Google на `127.0.0.1` с PKCE и сам сохранит токены — без конфигов и перезапуска.
|
|
15
16
|
- **Точные ID свойств.** `https://example.com/`, `https://www.example.com/` и `sc-domain:example.com` различаются. `list_sites` показывает значение, которое нужно использовать.
|
|
16
17
|
- **Поисковые данные с контекстом.** Можно получить клики, показы, CTR и позицию по дате, странице, запросу, стране, устройству или search appearance.
|
|
17
18
|
- **Индексация, а не публикация.** Проверка URL показывает текущий статус Google, но не заставляет страницу попасть в индекс.
|
|
@@ -52,23 +53,26 @@
|
|
|
52
53
|
|
|
53
54
|
## Быстрый старт
|
|
54
55
|
|
|
55
|
-
Нужны Node.js 20
|
|
56
|
+
Нужны Node.js 20+ и Google-аккаунт. Учётные данные при установке не нужны: сервер подключается прямо в диалоге.
|
|
56
57
|
|
|
57
|
-
1.
|
|
58
|
-
2.
|
|
58
|
+
1. Добавьте сервер в AI-приложение.
|
|
59
|
+
2. Скажите «подключи Google Search Console» — ассистент проведёт [создание OAuth-клиента и выдачу доступа](#как-получить-доступ), не трогая конфиги.
|
|
59
60
|
3. Начните с запроса, который только читает данные.
|
|
60
61
|
|
|
61
62
|
<details open><summary><strong>Codex</strong></summary>
|
|
62
63
|
|
|
63
64
|
<br>
|
|
64
65
|
|
|
66
|
+
<<<<<<< Updated upstream
|
|
67
|
+
**В приложении:** откройте **Settings → MCP servers**, нажмите **Add server**, выберите **STDIO**, укажите команду `npx -y mcp-google-search-console@latest` и переменные окружения `GOOGLE_SEARCH_CONSOLE_CLIENT_ID`, `GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET`, `GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN`, затем нажмите **Save**, потом **Restart**.
|
|
68
|
+
||||||| Stash base
|
|
65
69
|
**В приложении:** откройте **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`.
|
|
70
|
+
=======
|
|
71
|
+
**В приложении:** откройте **Settings → Plugins → MCP servers**, выберите **Add server**, затем добавьте `npx -y mcp-google-search-console@latest`.
|
|
72
|
+
>>>>>>> Stashed changes
|
|
66
73
|
|
|
67
74
|
```bash
|
|
68
75
|
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
76
|
-- npx -y mcp-google-search-console@latest
|
|
73
77
|
codex mcp list
|
|
74
78
|
```
|
|
@@ -83,9 +87,6 @@ codex mcp list
|
|
|
83
87
|
|
|
84
88
|
```bash
|
|
85
89
|
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
90
|
--transport stdio --scope user google-search-console \
|
|
90
91
|
-- npx -y mcp-google-search-console@latest
|
|
91
92
|
claude mcp list
|
|
@@ -99,13 +100,17 @@ claude mcp list
|
|
|
99
100
|
|
|
100
101
|
<br>
|
|
101
102
|
|
|
102
|
-
|
|
103
|
+
Актуальный официальный путь — **Settings → Extensions**. Для пользовательского desktop extension откройте **Advanced settings → Extension Developer → Install Extension…**, выберите файл `.mcpb` и следуйте подсказкам.
|
|
104
|
+
|
|
105
|
+
Этот репозиторий сейчас публикует npm-пакет со stdio и пока не содержит `.mcpb`. Поэтому используйте приведённый ниже JSON stdio-конфиг как fallback только в сборках Claude Desktop, где ещё поддерживается локальная конфигурация:
|
|
103
106
|
|
|
104
107
|
```json
|
|
105
|
-
{"mcpServers":{"google-search-console":{"command":"npx","args":["-y","mcp-google-search-console@latest"]
|
|
108
|
+
{"mcpServers":{"google-search-console":{"command":"npx","args":["-y","mcp-google-search-console@latest"]}}}
|
|
106
109
|
```
|
|
107
110
|
|
|
108
|
-
|
|
111
|
+
В таких сборках сохраните его в `~/Library/Application Support/Claude/claude_desktop_config.json` на macOS или `%APPDATA%\Claude\claude_desktop_config.json` на Windows.
|
|
112
|
+
|
|
113
|
+
[Документация Claude Desktop MCP](https://support.claude.com/en/articles/10949351-getting-started-with-local-mcp-servers-on-claude-desktop)
|
|
109
114
|
|
|
110
115
|
</details>
|
|
111
116
|
|
|
@@ -116,7 +121,7 @@ claude mcp list
|
|
|
116
121
|
Добавьте в `~/.cursor/mcp.json` на macOS/Linux или `%USERPROFILE%\.cursor\mcp.json` на Windows:
|
|
117
122
|
|
|
118
123
|
```json
|
|
119
|
-
{"mcpServers":{"google-search-console":{"type":"stdio","command":"npx","args":["-y","mcp-google-search-console@latest"]
|
|
124
|
+
{"mcpServers":{"google-search-console":{"type":"stdio","command":"npx","args":["-y","mcp-google-search-console@latest"]}}}
|
|
120
125
|
```
|
|
121
126
|
|
|
122
127
|
[Документация Cursor MCP](https://cursor.com/docs/mcp)
|
|
@@ -130,7 +135,7 @@ claude mcp list
|
|
|
130
135
|
Запустите **MCP: Open User Configuration** и добавьте:
|
|
131
136
|
|
|
132
137
|
```json
|
|
133
|
-
{"servers":{"google-search-console":{"type":"stdio","command":"npx","args":["-y","mcp-google-search-console@latest"]
|
|
138
|
+
{"servers":{"google-search-console":{"type":"stdio","command":"npx","args":["-y","mcp-google-search-console@latest"]}}}
|
|
134
139
|
```
|
|
135
140
|
|
|
136
141
|
Проверьте сервер командой **MCP: List Servers**. [Документация VS Code MCP](https://code.visualstudio.com/docs/agent-customization/mcp-servers)
|
|
@@ -178,7 +183,20 @@ URL-prefix property должен содержать протокол и заве
|
|
|
178
183
|
|
|
179
184
|
## Как получить доступ
|
|
180
185
|
|
|
181
|
-
|
|
186
|
+
Google Search Console требует OAuth 2.0: одного API-ключа недостаточно. Путей два, и первый не требует править конфигурационные файлы.
|
|
187
|
+
|
|
188
|
+
### Подключение из диалога (рекомендуемый путь)
|
|
189
|
+
|
|
190
|
+
Скажите «подключи Google Search Console», и ассистент пройдёт флоу вместе с вами:
|
|
191
|
+
|
|
192
|
+
1. `setup_instructions` выдаёт чек-лист: создать или выбрать проект Google Cloud, включить **Google Search Console API**, настроить consent screen и создать OAuth-клиент типа **Desktop app**.
|
|
193
|
+
2. Скачайте JSON этого клиента («Download JSON») и передайте ассистенту **путь** к файлу — `set_client` сохранит его с правами только для владельца. Секрет через переписку не проходит.
|
|
194
|
+
3. `start_login` возвращает ссылку на согласие Google. Откройте её **на этой же машине** и подтвердите доступ: код возвращается на одноразовый слушатель `127.0.0.1` (PKCE), а не в чат.
|
|
195
|
+
4. `finish_login` меняет код на токены и кладёт их в `~/.config/mcp-google-search-console/credentials.json` (права 0600) и проверяет их реальным вызовом Google Search Console API — так невключённый API ловится сразу.
|
|
196
|
+
|
|
197
|
+
Токены перечитываются на каждый вызов, поэтому подключение действует немедленно — перезапускать AI-приложение не нужно. `auth_status` показывает состояние, `logout` отзывает токен и удаляет его.
|
|
198
|
+
|
|
199
|
+
### Переменные окружения (CI и автоматические установки)
|
|
182
200
|
|
|
183
201
|
1. Создайте или выберите проект Google Cloud и включите **Google Search Console API**.
|
|
184
202
|
2. Настройте OAuth consent screen и создайте OAuth-клиент типа **Desktop app**.
|
|
@@ -189,12 +207,15 @@ Refresh token OAuth-приложения в режиме Testing может ис
|
|
|
189
207
|
|
|
190
208
|
## Конфигурация
|
|
191
209
|
|
|
210
|
+
Все переменные необязательные — без единой из них сервер подключается [из диалога](#подключение-из-диалога-рекомендуемый-путь).
|
|
211
|
+
|
|
192
212
|
| Переменная | Обязательна | Описание |
|
|
193
213
|
|---|---|---|
|
|
194
|
-
| `GOOGLE_SEARCH_CONSOLE_CLIENT_ID` |
|
|
195
|
-
| `GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET` |
|
|
196
|
-
| `GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN` |
|
|
197
|
-
| `GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN` |
|
|
214
|
+
| `GOOGLE_SEARCH_CONSOLE_CLIENT_ID` | Нет* | OAuth client ID. |
|
|
215
|
+
| `GOOGLE_SEARCH_CONSOLE_CLIENT_SECRET` | Нет* | OAuth client secret. |
|
|
216
|
+
| `GOOGLE_SEARCH_CONSOLE_REFRESH_TOKEN` | Нет* | OAuth refresh token. |
|
|
217
|
+
| `GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN` | Нет* | Короткоживущая альтернатива OAuth-тройке. |
|
|
218
|
+
| `GOOGLE_SEARCH_CONSOLE_OAUTH_PORT` | Нет | Фиксированный порт loopback-слушателя для входа из диалога; нужен при пробросе портов по SSH. |
|
|
198
219
|
| `GOOGLE_SEARCH_CONSOLE_API_BASE` | Нет | Переопределяет базовый URL API. |
|
|
199
220
|
| `GOOGLE_SEARCH_CONSOLE_TIMEOUT_MS` | Нет | Тайм-аут запроса; по умолчанию `60000` мс. |
|
|
200
221
|
| `GOOGLE_SEARCH_CONSOLE_MAX_RETRIES` | Нет | Повторы временных ошибок; по умолчанию `3`. |
|
|
@@ -203,7 +224,7 @@ Refresh token OAuth-приложения в режиме Testing может ис
|
|
|
203
224
|
|
|
204
225
|
## Данные, лимиты и работа в фоне
|
|
205
226
|
|
|
206
|
-
- **Приватность.** Локальный сервер вызывает Google и отправляет анонимную телеметрию с ID установки, версиями и именами инструментов — но не OAuth-токены, данные свойств, аргументы или промпты. Чтобы отключить её, задайте `ASKADS_TELEMETRY=0`.
|
|
227
|
+
- **Приватность.** Локальный сервер вызывает Google и отправляет анонимную телеметрию с ID установки, версиями и именами инструментов — но не OAuth-токены, данные свойств, аргументы или промпты. При вызове инструмента сервер также отправляет его исход, а при ошибке - фрагмент её текста: код и сообщение, в которых e-mail, адреса, токены, числа от 4 цифр и текст в кавычках заменены на «#». Если в тексте ошибки есть значение из запроса, оно тоже может попасть во фрагмент. Чтобы отключить её, задайте `ASKADS_TELEMETRY=0`.
|
|
207
228
|
- **Лимиты API.** URL inspection разрешает 2 000 проверок на свойство в сутки и 600 в минуту. Analytics возвращает максимум 25 000 строк за вызов; анонимизированные long-tail запросы никогда не возвращаются. Используйте пагинацию и не проверяйте сайт URL за URL.
|
|
208
229
|
- **Постоянного наблюдения нет.** Сервер работает только при вызове. Если AI-приложение поддерживает задания по расписанию, оно может периодически проверять sitemap или важный URL.
|
|
209
230
|
|
package/dist/client.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { GoogleSearchConsoleError } from "./types.js";
|
|
2
|
-
import { CredentialsError } from "./config.js";
|
|
2
|
+
import { CredentialsError, DEFAULT_BASE } from "./config.js";
|
|
3
3
|
/** Google's OAuth2 token endpoint — refresh tokens are exchanged here. */
|
|
4
4
|
const TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
5
5
|
/**
|
|
@@ -13,6 +13,7 @@ function seg(value) {
|
|
|
13
13
|
}
|
|
14
14
|
export class GoogleSearchConsoleClient {
|
|
15
15
|
config;
|
|
16
|
+
tokenProvider;
|
|
16
17
|
base;
|
|
17
18
|
timeoutMs;
|
|
18
19
|
maxRetries;
|
|
@@ -21,8 +22,16 @@ export class GoogleSearchConsoleClient {
|
|
|
21
22
|
cachedToken;
|
|
22
23
|
/** In-flight refresh, deduping concurrent token requests. */
|
|
23
24
|
refreshInFlight;
|
|
24
|
-
constructor(config
|
|
25
|
+
constructor(config,
|
|
26
|
+
/**
|
|
27
|
+
* Fallback token source (the in-chat login of @a1-x-tech/mcp-google-auth).
|
|
28
|
+
* Consulted only when the env-derived config carries no credentials —
|
|
29
|
+
* env wins (component invariant 3), so existing refresh-triple and
|
|
30
|
+
* access-token installs behave exactly as before.
|
|
31
|
+
*/
|
|
32
|
+
tokenProvider) {
|
|
25
33
|
this.config = config;
|
|
34
|
+
this.tokenProvider = tokenProvider;
|
|
26
35
|
this.base = config.apiBase.endsWith("/") ? config.apiBase : config.apiBase + "/";
|
|
27
36
|
this.timeoutMs = config.timeoutMs ?? 60_000;
|
|
28
37
|
this.maxRetries = config.maxRetries ?? 3;
|
|
@@ -31,6 +40,19 @@ export class GoogleSearchConsoleClient {
|
|
|
31
40
|
canRefresh() {
|
|
32
41
|
return Boolean(this.config.refreshToken && this.config.clientId && this.config.clientSecret);
|
|
33
42
|
}
|
|
43
|
+
/**
|
|
44
|
+
* Whether a 401 is worth one re-mint + replay: either the env config can mint
|
|
45
|
+
* from its refresh triple, or the provider holds a refresh token (env or
|
|
46
|
+
* stored login). A static env access token can never be re-minted, so a 401
|
|
47
|
+
* there is final — replaying it would just burn a second request.
|
|
48
|
+
*/
|
|
49
|
+
canReplayOn401() {
|
|
50
|
+
if (this.canRefresh())
|
|
51
|
+
return true;
|
|
52
|
+
if (this.config.accessToken)
|
|
53
|
+
return false;
|
|
54
|
+
return this.tokenProvider?.canRefresh() ?? false;
|
|
55
|
+
}
|
|
34
56
|
/**
|
|
35
57
|
* Returns a valid Bearer token. With the refresh triple configured, mints an
|
|
36
58
|
* access token from the refresh token and caches it until shortly before it
|
|
@@ -42,9 +64,13 @@ export class GoogleSearchConsoleClient {
|
|
|
42
64
|
*/
|
|
43
65
|
async accessToken(forceRefresh = false) {
|
|
44
66
|
if (!this.canRefresh()) {
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
67
|
+
// Env wins over the provider (component invariant 3): a static
|
|
68
|
+
// GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN keeps behaving exactly as before.
|
|
69
|
+
if (this.config.accessToken)
|
|
70
|
+
return this.config.accessToken;
|
|
71
|
+
if (this.tokenProvider)
|
|
72
|
+
return this.tokenProvider.getAccessToken(forceRefresh);
|
|
73
|
+
throw new CredentialsError();
|
|
48
74
|
}
|
|
49
75
|
if (!forceRefresh && this.cachedToken && Date.now() < this.cachedToken.expiresAt) {
|
|
50
76
|
return this.cachedToken.value;
|
|
@@ -174,7 +200,7 @@ export class GoogleSearchConsoleClient {
|
|
|
174
200
|
}
|
|
175
201
|
// An expired/revoked access token: re-mint once and replay. The request
|
|
176
202
|
// never executed, so this is safe for writes too.
|
|
177
|
-
if (res.status === 401 && this.
|
|
203
|
+
if (res.status === 401 && this.canReplayOn401() && !refreshedOn401) {
|
|
178
204
|
refreshedOn401 = true;
|
|
179
205
|
await this.accessToken(true);
|
|
180
206
|
continue;
|
|
@@ -293,3 +319,28 @@ function compact(obj) {
|
|
|
293
319
|
function delay(ms) {
|
|
294
320
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
295
321
|
}
|
|
322
|
+
/**
|
|
323
|
+
* One cheap Google Search Console read, used to verify a fresh in-chat login against the
|
|
324
|
+
* API the server actually talks to. Standalone (not a client method) because it
|
|
325
|
+
* runs with a token the client does not hold yet — the login is still being
|
|
326
|
+
* finished. Throws GoogleSearchConsoleError exactly like the client does, so the caller
|
|
327
|
+
* can recognize a disabled-API 403 and give the actionable advice.
|
|
328
|
+
*/
|
|
329
|
+
export async function probeApi(accessToken) {
|
|
330
|
+
const base = (process.env.GOOGLE_SEARCH_CONSOLE_API_BASE || DEFAULT_BASE).replace(/\/+$/, "");
|
|
331
|
+
const res = await fetch(`${base}/webmasters/v3/sites`, {
|
|
332
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
333
|
+
signal: AbortSignal.timeout(10_000),
|
|
334
|
+
});
|
|
335
|
+
const text = await res.text();
|
|
336
|
+
if (res.ok)
|
|
337
|
+
return;
|
|
338
|
+
let data;
|
|
339
|
+
try {
|
|
340
|
+
data = JSON.parse(text);
|
|
341
|
+
}
|
|
342
|
+
catch {
|
|
343
|
+
data = text;
|
|
344
|
+
}
|
|
345
|
+
throw new GoogleSearchConsoleError(res.status, data);
|
|
346
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -10,6 +10,7 @@ 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
|
+
import { authUnconfiguredPrefix, hasAuthToken, registerAuthTools } from "./tools/auth.js";
|
|
13
14
|
/**
|
|
14
15
|
* Prepended to every session as the `instructions` of the MCP initialize result
|
|
15
16
|
* — the only prose the calling model sees before it picks a tool. It carries
|
|
@@ -34,11 +35,6 @@ const INSTRUCTIONS = "Google Search Console reports how a property performs in o
|
|
|
34
35
|
* rather than with a failed call. There is no in-chat login here: credentials
|
|
35
36
|
* come only from the environment, so the fix is an operator action + restart.
|
|
36
37
|
*/
|
|
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. ";
|
|
42
38
|
/** Reads the package version so the server reports its real version to MCP clients. */
|
|
43
39
|
function readVersion() {
|
|
44
40
|
try {
|
|
@@ -79,10 +75,9 @@ async function main() {
|
|
|
79
75
|
// credentials can be reported; wired to the server before tools register.
|
|
80
76
|
const telemetry = new Telemetry(readVersion());
|
|
81
77
|
const { config, problem } = loadConfigOrDegraded(telemetry);
|
|
82
|
-
const client = new GoogleSearchConsoleClient(config);
|
|
83
78
|
// Decided once, at startup: credentials come only from the environment, so
|
|
84
79
|
// "restart after setting the variables" is the accurate advice to give.
|
|
85
|
-
const connected = hasCredentials(config);
|
|
80
|
+
const connected = hasCredentials(config) || hasAuthToken();
|
|
86
81
|
// `instructions` rides in the options argument (not serverInfo) — that is what
|
|
87
82
|
// the SDK copies into the initialize result.
|
|
88
83
|
const server = new McpServer({
|
|
@@ -91,7 +86,7 @@ async function main() {
|
|
|
91
86
|
}, {
|
|
92
87
|
instructions: connected
|
|
93
88
|
? INSTRUCTIONS
|
|
94
|
-
:
|
|
89
|
+
: authUnconfiguredPrefix() + (problem ? `Configuration problem: ${problem.message} ` : "") + INSTRUCTIONS,
|
|
95
90
|
});
|
|
96
91
|
instrumentToolCalls(server, telemetry);
|
|
97
92
|
server.server.oninitialized = () => {
|
|
@@ -103,6 +98,11 @@ async function main() {
|
|
|
103
98
|
else
|
|
104
99
|
telemetry.send("unconfigured_start", { reason: problem?.reason ?? "missing_credentials" });
|
|
105
100
|
};
|
|
101
|
+
// The auth tools come first so their TokenProvider exists before the client:
|
|
102
|
+
// the client falls back to it whenever the environment carries no
|
|
103
|
+
// credentials (env always wins — component invariant 3).
|
|
104
|
+
const tokenProvider = registerAuthTools(server);
|
|
105
|
+
const client = new GoogleSearchConsoleClient(config, tokenProvider);
|
|
106
106
|
registerSiteTools(server, client);
|
|
107
107
|
registerSitemapTools(server, client);
|
|
108
108
|
registerAnalyticsTools(server, client);
|
package/dist/telemetry.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Anonymous usage telemetry — fire-and-forget pings to usage.gistrec.cloud.
|
|
3
3
|
*
|
|
4
4
|
* Privacy contract (mirrored by the receiver): only an anonymous random
|
|
5
|
-
* instance id, event/tool names, a fixed-vocabulary failure reason and
|
|
5
|
+
* instance id, event/tool names, a fixed-vocabulary failure reason or tool outcome and
|
|
6
6
|
* environment versions ever leave the machine. The OAuth credentials, Search
|
|
7
7
|
* Console data, tool arguments, prompts and the names or values of environment
|
|
8
8
|
* variables are never read, serialized or sent. Sends are capped at 2 s and
|
|
@@ -64,6 +64,10 @@ export class Telemetry {
|
|
|
64
64
|
setClientInfo(info) {
|
|
65
65
|
this.clientInfo = info;
|
|
66
66
|
}
|
|
67
|
+
/** Whether pings go out at all (ASKADS_TELEMETRY opt-out). */
|
|
68
|
+
isEnabled() {
|
|
69
|
+
return this.enabled;
|
|
70
|
+
}
|
|
67
71
|
/** Fire-and-forget: the server's own work never waits on a ping. */
|
|
68
72
|
send(event, fields = {}) {
|
|
69
73
|
void this.post(event, fields);
|
|
@@ -87,7 +91,8 @@ export class Telemetry {
|
|
|
87
91
|
client_name: this.clientInfo?.name,
|
|
88
92
|
client_version: this.clientInfo?.version,
|
|
89
93
|
tool: fields.tool,
|
|
90
|
-
reason: fields.reason,
|
|
94
|
+
reason: wireReason(event, fields.reason),
|
|
95
|
+
error_detail: event === "tool_call" ? fields.error_detail : undefined,
|
|
91
96
|
node_version: process.version,
|
|
92
97
|
os: process.platform,
|
|
93
98
|
});
|
|
@@ -104,17 +109,221 @@ export class Telemetry {
|
|
|
104
109
|
}
|
|
105
110
|
}
|
|
106
111
|
}
|
|
112
|
+
/** How a tool call ended; only these constants leave the machine. */
|
|
113
|
+
export const TOOL_OUTCOMES = [
|
|
114
|
+
"ok",
|
|
115
|
+
"error_auth",
|
|
116
|
+
"error_permission",
|
|
117
|
+
"error_not_found",
|
|
118
|
+
"error_rate_limit",
|
|
119
|
+
"error_invalid_request",
|
|
120
|
+
"error_upstream",
|
|
121
|
+
"error_timeout",
|
|
122
|
+
"error_network",
|
|
123
|
+
"error_internal",
|
|
124
|
+
"error_other",
|
|
125
|
+
];
|
|
126
|
+
/** Drops a tool_call reason that is not in TOOL_OUTCOMES. */
|
|
127
|
+
function wireReason(event, reason) {
|
|
128
|
+
if (event !== "tool_call" || reason === undefined)
|
|
129
|
+
return reason;
|
|
130
|
+
return TOOL_OUTCOMES.includes(reason) ? reason : undefined;
|
|
131
|
+
}
|
|
132
|
+
// First match wins. Direct answers "no access to this client" with auth code 53, so that
|
|
133
|
+
// permission line goes before auth.
|
|
134
|
+
const OUTCOME_PATTERNS = [
|
|
135
|
+
["error_timeout", /timed?[ _-]?out|таймаут|ETIMEDOUT|AbortError|не был готов|not ready/i],
|
|
136
|
+
["error_network", /ECONNRESET|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|EPIPE|fetch failed|socket hang up/i],
|
|
137
|
+
["error_rate_limit", /\b429\b|rate[ _-]?limit|too many requests|quota|квот|лимит|\[(?:56|152|506|9000)\]/i],
|
|
138
|
+
["error_permission", /нет доступа к кабинету|не подключ[её]н к аккаунту/i],
|
|
139
|
+
[
|
|
140
|
+
"error_auth",
|
|
141
|
+
/\b401\b|unauthori[sz]ed|unauthenticated|invalid[ _-]?(?:token|grant|credentials)|token (?:expired|revoked)|login required|AuthRequired|авториз|не подключ|\[53\]/i,
|
|
142
|
+
],
|
|
143
|
+
["error_permission", /\b403\b|forbidden|access[ _-]?denied|permission|insufficient[ _-]?scope|нет доступа|\[(?:54|3228)\]/i],
|
|
144
|
+
["error_not_found", /\b404\b|not[ _-]?found|не найден|не существует|\[8800\]/i],
|
|
145
|
+
["error_upstream", /\b5\d\d\b|\b204\b|unavailable|недоступ|internal server error|bad gateway|\[(?:52|1000|1001|1002)\]/i],
|
|
146
|
+
["error_invalid_request", /\b400\b|\b422\b|bad request|invalid|syntax|некоррект|неверн|недопустим|required|обязател|expected|must (?:be|contain|have)|\[(?:4000|4001|4003|5000|8000)\]/i],
|
|
147
|
+
];
|
|
148
|
+
// An API code at the head of the message wins over the text, which may quote field names
|
|
149
|
+
// ("ForbiddenPlatform" in a [8000] list of allowed values). 53 is absent: the text tells a
|
|
150
|
+
// dead token from no access to a client.
|
|
151
|
+
const CODE_OUTCOMES = new Map([
|
|
152
|
+
...["56", "152", "506", "9000"].map((c) => [c, "error_rate_limit"]),
|
|
153
|
+
...["54", "3228"].map((c) => [c, "error_permission"]),
|
|
154
|
+
["8800", "error_not_found"],
|
|
155
|
+
...["52", "1000", "1001", "1002"].map((c) => [c, "error_upstream"]),
|
|
156
|
+
...["4000", "4001", "4003", "5000", "8000"].map((c) => [c, "error_invalid_request"]),
|
|
157
|
+
]);
|
|
158
|
+
const LEADING_CODE = /^[^[\n]{0,60}\[(\d{1,5})\]/;
|
|
159
|
+
// Inputs are cut before any regex runs: a long argument echoed in an error must not stall the call.
|
|
160
|
+
const TEXT_MAX = 4000;
|
|
161
|
+
function resultText(value) {
|
|
162
|
+
if (value instanceof Error)
|
|
163
|
+
return `${value.name} ${value.message}`.slice(0, TEXT_MAX);
|
|
164
|
+
const content = value?.content;
|
|
165
|
+
if (!Array.isArray(content))
|
|
166
|
+
return "";
|
|
167
|
+
return content
|
|
168
|
+
.map((part) => (part && typeof part === "object" && typeof part.text === "string" ? part.text : ""))
|
|
169
|
+
.join("\n")
|
|
170
|
+
.slice(0, TEXT_MAX);
|
|
171
|
+
}
|
|
172
|
+
/** `toolOutcome(result)` for a returned result, `toolOutcome(undefined, error)` for a thrown one. */
|
|
173
|
+
export function toolOutcome(result, ...thrown) {
|
|
174
|
+
const didThrow = thrown.length > 0;
|
|
175
|
+
if (!didThrow && !result?.isError)
|
|
176
|
+
return "ok";
|
|
177
|
+
const text = resultText(didThrow ? thrown[0] : result);
|
|
178
|
+
const byCode = CODE_OUTCOMES.get(LEADING_CODE.exec(text)?.[1] ?? "");
|
|
179
|
+
if (byCode)
|
|
180
|
+
return byCode;
|
|
181
|
+
for (const [outcome, pattern] of OUTCOME_PATTERNS)
|
|
182
|
+
if (pattern.test(text))
|
|
183
|
+
return outcome;
|
|
184
|
+
return didThrow ? "error_internal" : "error_other";
|
|
185
|
+
}
|
|
186
|
+
/** Error excerpt: allowlisted fragments of the error text, masked (port of the Ask Ads gateway's). */
|
|
187
|
+
export const DETAIL_MAX = 200;
|
|
188
|
+
const PICK = /\bHTTP (?<http>\d{3})\b(?::\s*(?<htext>[^{[]{1,200}))?|^(?:Ошибка: )?\[(?<bcode>\d{1,5})\]\s*(?<btext>[^;(]{1,200})|\[(?<tag>[A-Za-z][A-Za-z_]{2,})\]\s*(?<ttext>[^;(]{0,200})|\berror_code["']?\s*[:=]\s*["']?(?<code>\d{1,5})\b|\b(?<key>error_string|error_detail|error_type|message)["']?\s*[:=]\s*["']?(?<value>[^"'}\]]{1,80})|\b(?<net>ECONNRESET|ECONNREFUSED|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|timed out|fetch failed|socket hang up|connection closed)\b|(?<netru>превысил таймаут)/gi;
|
|
189
|
+
const SCRUB = /(?<key>(?:login|password|secret|token|api[_-]?key|authorization)\s*[:=]\s*["']?|(?:bearer|basic)\s+)(?<val>[^,;]+)|[^\s,;]*(?:@|:\/\/|%3A|\p{L}\.\p{L})[^\s,;]*|(?<key2>\b(?:token|secret|password|api[_-]?key|access_token|refresh_token|client_secret)\s+)(?!(?:expired|invalid|is|was|for|has|not|missing|required|revoked|provided|type)\b)\S+|\b(?:y0_|AQAA|AQVN|t1\.|sk-|vk1\.|vk_|ghp_|ya29\.)\S+|\b(?=[\w-]*\d)(?=[\w-]*[A-Za-z])[\w-]{20,}\b|\+?\d(?:[\s().-]*\d){3,}/giu;
|
|
190
|
+
const QUOTED = /(?<!\p{L})'[^'\n]+(?:'(?!\p{L})|$)|"[^"\n]+(?:"|$)|«[^»]+(?:»|$)/gu;
|
|
191
|
+
function scrub(value, quoted = true) {
|
|
192
|
+
return (quoted ? value.replace(QUOTED, "#") : value)
|
|
193
|
+
.replace(SCRUB, (...args) => {
|
|
194
|
+
const groups = args[args.length - 1];
|
|
195
|
+
return (groups.key ?? groups.key2 ?? "") + "#";
|
|
196
|
+
})
|
|
197
|
+
.replace(/^[ ;:,.]+|[ ;:,.]+$/g, "");
|
|
198
|
+
}
|
|
199
|
+
export function errorDetail(text) {
|
|
200
|
+
const flat = text.slice(0, 2000).split(/\s+/).filter(Boolean).join(" ");
|
|
201
|
+
const parts = [];
|
|
202
|
+
PICK.lastIndex = 0;
|
|
203
|
+
for (let m = PICK.exec(flat); m; m = PICK.exec(flat)) {
|
|
204
|
+
const g = m.groups ?? {};
|
|
205
|
+
let token;
|
|
206
|
+
if (g.http)
|
|
207
|
+
token = `HTTP ${g.http} ${scrub(g.htext ?? "")}`;
|
|
208
|
+
else if (g.bcode)
|
|
209
|
+
token = `code=${g.bcode} ${scrub(g.btext ?? "")}`;
|
|
210
|
+
else if (g.tag) {
|
|
211
|
+
// Tags are upper-case only; the rest of PICK is case-insensitive.
|
|
212
|
+
if (!/^[A-Z][A-Z_]{2,}$/.test(g.tag)) {
|
|
213
|
+
PICK.lastIndex = m.index + 1;
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
token = `${g.tag} ${scrub(g.ttext ?? "")}`;
|
|
217
|
+
}
|
|
218
|
+
else if (g.code)
|
|
219
|
+
token = `code=${g.code}`;
|
|
220
|
+
else if (g.key)
|
|
221
|
+
token = `${g.key.toLowerCase()}=${scrub(g.value ?? "")}`;
|
|
222
|
+
else
|
|
223
|
+
token = (g.net ?? g.netru ?? "").toLowerCase();
|
|
224
|
+
token = token.trim();
|
|
225
|
+
if (!parts.includes(token))
|
|
226
|
+
parts.push(token);
|
|
227
|
+
}
|
|
228
|
+
return parts.join("; ").slice(0, DETAIL_MAX);
|
|
229
|
+
}
|
|
230
|
+
/** Set by fail(), never serialized: our own refusal ("local"), a bug in our code ("internal") or a failed fetch ("network"). */
|
|
231
|
+
const FAILURE_ORIGIN = new WeakMap();
|
|
232
|
+
const JS_ERRORS = new Set(["TypeError", "ReferenceError", "RangeError", "SyntaxError", "EvalError", "URIError"]);
|
|
233
|
+
function jsBug(err) {
|
|
234
|
+
return err instanceof Error && JS_ERRORS.has(err.name) ? `${err.name}: ${err.message.split("\n")[0]}` : undefined;
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Node's fetch rejects a network failure as TypeError("fetch failed") with the socket/DNS/TLS error
|
|
238
|
+
* in `cause`. Only cause.code leaves the machine: cause.message names hosts and addresses.
|
|
239
|
+
*/
|
|
240
|
+
function fetchFailure(err) {
|
|
241
|
+
if (!(err instanceof Error) || err.name !== "TypeError" || err.message !== "fetch failed")
|
|
242
|
+
return undefined;
|
|
243
|
+
const cause = err.cause;
|
|
244
|
+
if (!cause || typeof cause !== "object")
|
|
245
|
+
return undefined;
|
|
246
|
+
const raw = cause.code;
|
|
247
|
+
const code = typeof raw === "string" && /^[A-Z][A-Z0-9_]{2,40}$/.test(raw) ? raw : "";
|
|
248
|
+
return {
|
|
249
|
+
reason: /TIMEOUT|TIMEDOUT/.test(code) ? "error_timeout" : "error_network",
|
|
250
|
+
text: code ? `fetch failed; ${code.toLowerCase()}` : "fetch failed",
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
export function noteFailure(result, err) {
|
|
254
|
+
try {
|
|
255
|
+
if (result && typeof result === "object") {
|
|
256
|
+
const net = fetchFailure(err);
|
|
257
|
+
if (typeof err === "string")
|
|
258
|
+
FAILURE_ORIGIN.set(result, { origin: "local", text: err });
|
|
259
|
+
else if (net)
|
|
260
|
+
FAILURE_ORIGIN.set(result, { origin: "network", ...net });
|
|
261
|
+
else {
|
|
262
|
+
const bug = jsBug(err);
|
|
263
|
+
if (bug)
|
|
264
|
+
FAILURE_ORIGIN.set(result, { origin: "internal", text: bug });
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
catch {
|
|
269
|
+
// never affects the result
|
|
270
|
+
}
|
|
271
|
+
return result;
|
|
272
|
+
}
|
|
273
|
+
/** A JS error quotes identifiers of our code, not user data, so its quotes are kept. */
|
|
274
|
+
function maskedOwnText(prefix, text, quoted = true) {
|
|
275
|
+
return (prefix + scrub(text.slice(0, 2 * DETAIL_MAX).split(/\s+/).filter(Boolean).join(" "), quoted)).slice(0, DETAIL_MAX);
|
|
276
|
+
}
|
|
277
|
+
/** Best effort: classifying or sending must never change what the tool returns or throws. */
|
|
278
|
+
function reportCall(telemetry, tool, value, thrown) {
|
|
279
|
+
if (!telemetry.isEnabled())
|
|
280
|
+
return;
|
|
281
|
+
try {
|
|
282
|
+
let reason = thrown ? toolOutcome(undefined, value) : toolOutcome(value);
|
|
283
|
+
let detail = "";
|
|
284
|
+
if (reason !== "ok") {
|
|
285
|
+
const noted = value && typeof value === "object" ? FAILURE_ORIGIN.get(value) : undefined;
|
|
286
|
+
const net = noted?.origin === "network" ? noted : thrown ? fetchFailure(value) : undefined;
|
|
287
|
+
const bug = noted?.origin === "internal" ? noted.text : thrown ? jsBug(value) : undefined;
|
|
288
|
+
if (net) {
|
|
289
|
+
reason = net.reason;
|
|
290
|
+
detail = net.text;
|
|
291
|
+
}
|
|
292
|
+
else if (bug) {
|
|
293
|
+
reason = "error_internal";
|
|
294
|
+
detail = maskedOwnText("internal: ", bug, false);
|
|
295
|
+
}
|
|
296
|
+
else if (noted?.origin === "local") {
|
|
297
|
+
reason = "error_invalid_request";
|
|
298
|
+
detail = maskedOwnText("local: ", noted.text);
|
|
299
|
+
}
|
|
300
|
+
else
|
|
301
|
+
detail = errorDetail(resultText(value));
|
|
302
|
+
}
|
|
303
|
+
telemetry.send("tool_call", { tool, reason, error_detail: detail || undefined });
|
|
304
|
+
}
|
|
305
|
+
catch {
|
|
306
|
+
// never affects the call
|
|
307
|
+
}
|
|
308
|
+
}
|
|
107
309
|
/**
|
|
108
|
-
*
|
|
109
|
-
*
|
|
110
|
-
* Only the tool *name* is recorded — arguments never reach telemetry.
|
|
310
|
+
* Counts every tool call by name and outcome. Wraps registerTool once, before the domain
|
|
311
|
+
* modules register their tools. Calls rejected by SDK input validation are not counted.
|
|
111
312
|
*/
|
|
112
313
|
export function instrumentToolCalls(server, telemetry) {
|
|
113
314
|
const original = server.registerTool.bind(server);
|
|
114
315
|
// registerTool's generic signature does not survive a wrapper; the runtime
|
|
115
316
|
// shape (name, config, callback) is stable per SDK contract.
|
|
116
|
-
server.registerTool = ((name, config, callback) => original(name, config, ((...args) => {
|
|
117
|
-
|
|
118
|
-
|
|
317
|
+
server.registerTool = ((name, config, callback) => original(name, config, (async (...args) => {
|
|
318
|
+
let result;
|
|
319
|
+
try {
|
|
320
|
+
result = await callback(...args);
|
|
321
|
+
}
|
|
322
|
+
catch (e) {
|
|
323
|
+
reportCall(telemetry, name, e, true);
|
|
324
|
+
throw e;
|
|
325
|
+
}
|
|
326
|
+
reportCall(telemetry, name, result, false);
|
|
327
|
+
return result;
|
|
119
328
|
})));
|
|
120
329
|
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { OAuthError, registerGoogleAuth, TokenProvider, unconfiguredPrefix, USERINFO_URL, } from "@a1-x-tech/mcp-google-auth";
|
|
2
|
+
import { probeApi } from "../client.js";
|
|
3
|
+
import { GoogleSearchConsoleError } from "../types.js";
|
|
4
|
+
/**
|
|
5
|
+
* The scopes an in-chat login requests (the per-task table lives in
|
|
6
|
+
* docs/TOOLS.md). The component always adds the identity scopes on top. The read-write `webmasters` scope is requested because the tool surface includes sitemap submission; `webmasters.readonly` would fail there.
|
|
7
|
+
*/
|
|
8
|
+
export const LOGIN_SCOPES = [
|
|
9
|
+
"https://www.googleapis.com/auth/webmasters",
|
|
10
|
+
];
|
|
11
|
+
/**
|
|
12
|
+
* True when a Google API error body says the API itself is switched off in the
|
|
13
|
+
* caller's Cloud project. Google reports this two ways at once and has been
|
|
14
|
+
* migrating between them: the legacy `error.errors[].reason` is
|
|
15
|
+
* `accessNotConfigured`, the newer `error.details[].reason` is
|
|
16
|
+
* `SERVICE_DISABLED`. Either spelling means the same fix, so both are matched.
|
|
17
|
+
*/
|
|
18
|
+
function isApiDisabled(body) {
|
|
19
|
+
if (typeof body !== "object" || body === null)
|
|
20
|
+
return false;
|
|
21
|
+
const error = body.error;
|
|
22
|
+
if (typeof error !== "object" || error === null)
|
|
23
|
+
return false;
|
|
24
|
+
const reasons = new Set();
|
|
25
|
+
for (const key of ["errors", "details"]) {
|
|
26
|
+
const list = error[key];
|
|
27
|
+
if (Array.isArray(list)) {
|
|
28
|
+
for (const entry of list) {
|
|
29
|
+
if (typeof entry === "object" && entry !== null) {
|
|
30
|
+
reasons.add(entry.reason);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return reasons.has("accessNotConfigured") || reasons.has("SERVICE_DISABLED");
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* `verifyIdentity` for the component: one cheap Google Search Console read, plus the
|
|
39
|
+
* translation the component cannot do itself. An API that is not enabled in the
|
|
40
|
+
* user's Cloud project answers the first call with HTTP 403 — the most likely
|
|
41
|
+
* failure right after a login — as a bare error reading "PERMISSION_DENIED",
|
|
42
|
+
* which sends the user to check permissions they cannot fix. Re-thrown as
|
|
43
|
+
* `OAuthError("accessNotConfigured")` it becomes the real advice: enable the
|
|
44
|
+
* API in the SAME project as the OAuth client.
|
|
45
|
+
*
|
|
46
|
+
* Checking the product API (rather than the component's default OIDC userinfo)
|
|
47
|
+
* is the point: OIDC answers even when Google Search Console API is switched off, so a
|
|
48
|
+
* login would look successful and the first real tool call would fail instead.
|
|
49
|
+
*/
|
|
50
|
+
async function verifyIdentity(accessToken) {
|
|
51
|
+
try {
|
|
52
|
+
await probeApi(accessToken);
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
if (error instanceof GoogleSearchConsoleError && error.status === 403 && isApiDisabled(error.body)) {
|
|
56
|
+
throw new OAuthError("accessNotConfigured", "Google Search Console API", error.status);
|
|
57
|
+
}
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
return { email: await accountEmail(accessToken) };
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* The account label shown after a login. Best-effort on purpose: the connection
|
|
64
|
+
* is already proven by the probe above, and failing the whole login over a
|
|
65
|
+
* cosmetic label would be wrong.
|
|
66
|
+
*/
|
|
67
|
+
async function accountEmail(accessToken) {
|
|
68
|
+
try {
|
|
69
|
+
const res = await fetch(USERINFO_URL, {
|
|
70
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
71
|
+
signal: AbortSignal.timeout(10_000),
|
|
72
|
+
});
|
|
73
|
+
if (!res.ok)
|
|
74
|
+
return undefined;
|
|
75
|
+
const data = await res.json();
|
|
76
|
+
const email = data.email;
|
|
77
|
+
return typeof email === "string" ? email : undefined;
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* The single source of the auth wiring: serverName "search-console" puts the stored
|
|
85
|
+
* login in ~/.config/mcp-google-search-console/credentials.json (the component
|
|
86
|
+
* prefixes "mcp-google-"), envPrefix keeps the provider reading the exact
|
|
87
|
+
* GOOGLE_SEARCH_CONSOLE_* variables config.ts documents — which is what preserves the
|
|
88
|
+
* env-beats-stored priority for existing installs.
|
|
89
|
+
*/
|
|
90
|
+
export const AUTH_OPTIONS = {
|
|
91
|
+
serverName: "search-console",
|
|
92
|
+
envPrefix: "GOOGLE_SEARCH_CONSOLE",
|
|
93
|
+
scopes: LOGIN_SCOPES,
|
|
94
|
+
verifyIdentity,
|
|
95
|
+
};
|
|
96
|
+
/**
|
|
97
|
+
* Registers the six onboarding tools (auth_status, setup_instructions,
|
|
98
|
+
* set_client, start_login, finish_login, logout) and returns the TokenProvider
|
|
99
|
+
* the client plugs in as its fallback token source — the same instance, so a
|
|
100
|
+
* login finished mid-session is visible to the very next API call without a
|
|
101
|
+
* restart.
|
|
102
|
+
*/
|
|
103
|
+
export function registerAuthTools(server) {
|
|
104
|
+
return registerGoogleAuth(server, AUTH_OPTIONS);
|
|
105
|
+
}
|
|
106
|
+
/** True when any token exists — env variables or a stored in-chat login. */
|
|
107
|
+
export function hasAuthToken() {
|
|
108
|
+
return new TokenProvider(AUTH_OPTIONS).hasToken();
|
|
109
|
+
}
|
|
110
|
+
/** The "NOT CONNECTED" prefix for the initialize instructions (names both fixes). */
|
|
111
|
+
export function authUnconfiguredPrefix() {
|
|
112
|
+
return unconfiguredPrefix(AUTH_OPTIONS);
|
|
113
|
+
}
|
package/dist/tools/util.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
import { noteFailure } from "../telemetry.js";
|
|
2
3
|
/**
|
|
3
4
|
* Schema factories, not shared consts: reusing one zod object across two fields
|
|
4
5
|
* makes zod-to-json-schema dedupe them into a `$ref`, which some tool-schema
|
|
@@ -19,7 +20,11 @@ export function ok(data) {
|
|
|
19
20
|
const text = typeof data === "string" ? data : JSON.stringify(data);
|
|
20
21
|
return { content: [{ type: "text", text: text ?? "null" }] };
|
|
21
22
|
}
|
|
23
|
+
/** The failed result; also notes, off the wire, whether it is our own refusal or a JS bug (telemetry). */
|
|
22
24
|
export function fail(err) {
|
|
25
|
+
return noteFailure(failText(err), err);
|
|
26
|
+
}
|
|
27
|
+
function failText(err) {
|
|
23
28
|
let message = err instanceof Error ? err.message : String(err);
|
|
24
29
|
// Surface the underlying cause (e.g. the network error behind a timeout) — no
|
|
25
30
|
// secrets live in cause, and it makes failures far easier to diagnose.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mcp-google-search-console",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.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",
|
|
@@ -51,6 +51,7 @@
|
|
|
51
51
|
"url": "https://github.com/A1-x-Tech/mcp-google-search-console/issues"
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
|
+
"@a1-x-tech/mcp-google-auth": "^0.1.0",
|
|
54
55
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
55
56
|
"zod": "^3.25.0"
|
|
56
57
|
},
|
package/test/dist-smoke.test.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
2
5
|
import test from "node:test";
|
|
3
6
|
import { fileURLToPath } from "node:url";
|
|
4
7
|
|
|
@@ -11,22 +14,47 @@ import { registerSitemapTools } from "../dist/tools/sitemaps.js";
|
|
|
11
14
|
import { registerAnalyticsTools } from "../dist/tools/analytics.js";
|
|
12
15
|
import { registerInspectionTools } from "../dist/tools/inspection.js";
|
|
13
16
|
import { registerRawTool } from "../dist/tools/raw.js";
|
|
17
|
+
import { registerAuthTools } from "../dist/tools/auth.js";
|
|
14
18
|
|
|
19
|
+
/**
|
|
20
|
+
* Sorted, because every assertion compares it against a sorted tool list. The
|
|
21
|
+
* six onboarding tools come from @a1-x-tech/mcp-google-auth, so this list is
|
|
22
|
+
* also the check that the component is wired into the published binary.
|
|
23
|
+
*/
|
|
15
24
|
const ALL_TOOLS = [
|
|
16
25
|
"add_site",
|
|
26
|
+
"auth_status",
|
|
17
27
|
"delete_site",
|
|
18
28
|
"delete_sitemap",
|
|
29
|
+
"finish_login",
|
|
19
30
|
"get_site",
|
|
20
31
|
"get_sitemap",
|
|
21
32
|
"get_top_queries",
|
|
22
33
|
"inspect_url",
|
|
23
34
|
"list_sitemaps",
|
|
24
35
|
"list_sites",
|
|
36
|
+
"logout",
|
|
25
37
|
"raw_request",
|
|
26
38
|
"search_analytics",
|
|
39
|
+
"set_client",
|
|
40
|
+
"setup_instructions",
|
|
41
|
+
"start_login",
|
|
27
42
|
"submit_sitemap",
|
|
28
43
|
];
|
|
29
44
|
|
|
45
|
+
/**
|
|
46
|
+
* A throwaway $XDG_CONFIG_HOME for the spawned server. The auth component
|
|
47
|
+
* re-reads $XDG_CONFIG_HOME/mcp-google-search-console/credentials.json per call, so
|
|
48
|
+
* without this a real login on the developer's machine would make the
|
|
49
|
+
* "unconfigured" case pass for the wrong reason.
|
|
50
|
+
*/
|
|
51
|
+
function isolatedConfigDir(t) {
|
|
52
|
+
const dir = mkdtempSync(join(tmpdir(), "mcp-search-console-dist-smoke-"));
|
|
53
|
+
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
|
54
|
+
return dir;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
|
|
30
58
|
test("dist client rejects foreign-origin paths before sending the Bearer token", async () => {
|
|
31
59
|
const original = globalThis.fetch;
|
|
32
60
|
let called = false;
|
|
@@ -87,6 +115,7 @@ test("dist registers the expected tools", () => {
|
|
|
87
115
|
};
|
|
88
116
|
const client = {};
|
|
89
117
|
|
|
118
|
+
registerAuthTools(server, client);
|
|
90
119
|
registerSiteTools(server, client);
|
|
91
120
|
registerSitemapTools(server, client);
|
|
92
121
|
registerAnalyticsTools(server, client);
|
|
@@ -96,13 +125,14 @@ test("dist registers the expected tools", () => {
|
|
|
96
125
|
assert.deepEqual(names.sort(), ALL_TOOLS);
|
|
97
126
|
});
|
|
98
127
|
|
|
99
|
-
test("dist binary completes a real MCP handshake over stdio and lists every tool", async () => {
|
|
128
|
+
test("dist binary completes a real MCP handshake over stdio and lists every tool", async (t) => {
|
|
100
129
|
const transport = new StdioClientTransport({
|
|
101
130
|
command: process.execPath,
|
|
102
131
|
args: [fileURLToPath(new URL("../dist/index.js", import.meta.url))],
|
|
103
132
|
env: {
|
|
104
133
|
...process.env,
|
|
105
134
|
GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN: "test-token",
|
|
135
|
+
XDG_CONFIG_HOME: isolatedConfigDir(t),
|
|
106
136
|
ASKADS_TELEMETRY: "0", // keep the suite offline
|
|
107
137
|
},
|
|
108
138
|
stderr: "pipe",
|
|
@@ -141,13 +171,14 @@ test("dist binary completes a real MCP handshake over stdio and lists every tool
|
|
|
141
171
|
* answer a tool call with the actionable error — offline: the CredentialsError
|
|
142
172
|
* fires before any fetch, so this test never touches the network.
|
|
143
173
|
*/
|
|
144
|
-
test("dist binary starts without credentials: handshake, tool list, actionable call error", async () => {
|
|
174
|
+
test("dist binary starts without credentials: handshake, tool list, actionable call error", async (t) => {
|
|
145
175
|
const env = Object.fromEntries(
|
|
146
176
|
Object.entries(process.env).filter(
|
|
147
177
|
([key, value]) => value !== undefined && !key.startsWith("GOOGLE_SEARCH_CONSOLE_"),
|
|
148
178
|
),
|
|
149
179
|
);
|
|
150
180
|
env.ASKADS_TELEMETRY = "0"; // keep the suite offline
|
|
181
|
+
env.XDG_CONFIG_HOME = isolatedConfigDir(t); // ignore any real login on this machine
|
|
151
182
|
const transport = new StdioClientTransport({
|
|
152
183
|
command: process.execPath,
|
|
153
184
|
args: [fileURLToPath(new URL("../dist/index.js", import.meta.url))],
|
|
@@ -159,7 +190,8 @@ test("dist binary starts without credentials: handshake, tool list, actionable c
|
|
|
159
190
|
try {
|
|
160
191
|
// The model must read the fix before it picks a tool.
|
|
161
192
|
const instructions = client.getInstructions() ?? "";
|
|
162
|
-
assert.match(instructions, /
|
|
193
|
+
assert.match(instructions, /NOT CONNECTED/);
|
|
194
|
+
assert.match(instructions, /start_login/);
|
|
163
195
|
assert.match(instructions, /GOOGLE_SEARCH_CONSOLE_CLIENT_ID/);
|
|
164
196
|
assert.match(instructions, /restart/);
|
|
165
197
|
|
|
@@ -170,7 +202,8 @@ test("dist binary starts without credentials: handshake, tool list, actionable c
|
|
|
170
202
|
const result = await client.callTool({ name: "list_sites", arguments: {} });
|
|
171
203
|
assert.equal(result.isError, true);
|
|
172
204
|
const text = result.content.map((c) => c.text ?? "").join(" ");
|
|
173
|
-
assert.match(text, /
|
|
205
|
+
assert.match(text, /not connected/i);
|
|
206
|
+
assert.match(text, /start_login/);
|
|
174
207
|
assert.match(text, /restart the server/);
|
|
175
208
|
} finally {
|
|
176
209
|
await client.close();
|