mcp-google-search-console 1.0.0 → 1.2.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 +188 -183
- package/README.ru.md +251 -0
- package/dist/client.js +61 -5
- package/dist/config.js +41 -12
- package/dist/index.js +62 -13
- package/dist/telemetry.js +3 -3
- package/dist/tools/auth.js +113 -0
- package/package.json +2 -1
- package/test/dist-smoke.test.js +83 -1
package/README.ru.md
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
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
|
+
- **18 инструментов.** Семь инструментов читают свойства, поисковые данные, sitemap и статус индексации; два добавляют свойство или отправляют sitemap; три могут удалить данные или вызвать произвольный метод API.
|
|
15
|
+
- **Подключение из диалога.** Скажите «подключи Google Search Console»: сервер проведёт через создание OAuth-клиента, поймает редирект Google на `127.0.0.1` с PKCE и сам сохранит токены — без конфигов и перезапуска.
|
|
16
|
+
- **Точные ID свойств.** `https://example.com/`, `https://www.example.com/` и `sc-domain:example.com` различаются. `list_sites` показывает значение, которое нужно использовать.
|
|
17
|
+
- **Поисковые данные с контекстом.** Можно получить клики, показы, CTR и позицию по дате, странице, запросу, стране, устройству или search appearance.
|
|
18
|
+
- **Индексация, а не публикация.** Проверка URL показывает текущий статус Google, но не заставляет страницу попасть в индекс.
|
|
19
|
+
|
|
20
|
+
Начните с запроса, который только читает данные:
|
|
21
|
+
|
|
22
|
+
> Покажи 20 самых популярных поисковых запросов для моего свойства за последние 28 дней, с кликами и CTR.
|
|
23
|
+
|
|
24
|
+
[Подключить сервер](#быстрый-старт) · [Посмотреть сценарии](#что-можно-поручить) · [Открыть техническую документацию](#техническая-документация)
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
## Увидеть работу за минуту
|
|
29
|
+
|
|
30
|
+
> **Вы:** Проиндексирован ли `https://example.com/pricing`? Если нет, почему?
|
|
31
|
+
>
|
|
32
|
+
> **Ассистент:** Проверяет URL и показывает вердикт индексации, покрытие, данные обхода и canonical URLs. Ничего не меняется.
|
|
33
|
+
>
|
|
34
|
+
> **Вы:** Проверь мои sitemap и подготовь повторную отправку того, где есть ошибки.
|
|
35
|
+
>
|
|
36
|
+
> **Ассистент:** Показывает sitemap, его предупреждения и ошибки, затем запрашивает подтверждение перед повторной отправкой.
|
|
37
|
+
>
|
|
38
|
+
> **Вы:** Подтверждаю.
|
|
39
|
+
>
|
|
40
|
+
> **Ассистент:** Повторно отправляет выбранный sitemap. Он не меняет содержимое страницы и не гарантирует индексацию.
|
|
41
|
+
|
|
42
|
+
## Содержание
|
|
43
|
+
|
|
44
|
+
- [Быстрый старт](#быстрый-старт)
|
|
45
|
+
- [Что можно поручить](#что-можно-поручить)
|
|
46
|
+
- [Как устроены свойства Search Console](#как-устроены-свойства-search-console)
|
|
47
|
+
- [Что может измениться](#что-может-измениться)
|
|
48
|
+
- [Как получить доступ](#как-получить-доступ)
|
|
49
|
+
- [Конфигурация](#конфигурация)
|
|
50
|
+
- [Данные, лимиты и работа в фоне](#данные-лимиты-и-работа-в-фоне)
|
|
51
|
+
- [Техническая документация](#техническая-документация)
|
|
52
|
+
- [Поддержка](#поддержка)
|
|
53
|
+
|
|
54
|
+
## Быстрый старт
|
|
55
|
+
|
|
56
|
+
Нужны Node.js 20+ и Google-аккаунт. Учётные данные при установке не нужны: сервер подключается прямо в диалоге.
|
|
57
|
+
|
|
58
|
+
1. Добавьте сервер в AI-приложение.
|
|
59
|
+
2. Скажите «подключи Google Search Console» — ассистент проведёт [создание OAuth-клиента и выдачу доступа](#как-получить-доступ), не трогая конфиги.
|
|
60
|
+
3. Начните с запроса, который только читает данные.
|
|
61
|
+
|
|
62
|
+
<details open><summary><strong>Codex</strong></summary>
|
|
63
|
+
|
|
64
|
+
<br>
|
|
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
|
|
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
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
codex mcp add google-search-console \
|
|
76
|
+
-- npx -y mcp-google-search-console@latest
|
|
77
|
+
codex mcp list
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
[Документация Codex MCP](https://learn.chatgpt.com/docs/extend/mcp?surface=cli)
|
|
81
|
+
|
|
82
|
+
</details>
|
|
83
|
+
|
|
84
|
+
<details><summary><strong>Claude Code</strong></summary>
|
|
85
|
+
|
|
86
|
+
<br>
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
claude mcp add \
|
|
90
|
+
--transport stdio --scope user google-search-console \
|
|
91
|
+
-- npx -y mcp-google-search-console@latest
|
|
92
|
+
claude mcp list
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
[Документация Claude Code MCP](https://code.claude.com/docs/en/mcp)
|
|
96
|
+
|
|
97
|
+
</details>
|
|
98
|
+
|
|
99
|
+
<details><summary><strong>Claude Desktop</strong></summary>
|
|
100
|
+
|
|
101
|
+
<br>
|
|
102
|
+
|
|
103
|
+
Актуальный официальный путь — **Settings → Extensions**. Для пользовательского desktop extension откройте **Advanced settings → Extension Developer → Install Extension…**, выберите файл `.mcpb` и следуйте подсказкам.
|
|
104
|
+
|
|
105
|
+
Этот репозиторий сейчас публикует npm-пакет со stdio и пока не содержит `.mcpb`. Поэтому используйте приведённый ниже JSON stdio-конфиг как fallback только в сборках Claude Desktop, где ещё поддерживается локальная конфигурация:
|
|
106
|
+
|
|
107
|
+
```json
|
|
108
|
+
{"mcpServers":{"google-search-console":{"command":"npx","args":["-y","mcp-google-search-console@latest"]}}}
|
|
109
|
+
```
|
|
110
|
+
|
|
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)
|
|
114
|
+
|
|
115
|
+
</details>
|
|
116
|
+
|
|
117
|
+
<details><summary><strong>Cursor</strong></summary>
|
|
118
|
+
|
|
119
|
+
<br>
|
|
120
|
+
|
|
121
|
+
Добавьте в `~/.cursor/mcp.json` на macOS/Linux или `%USERPROFILE%\.cursor\mcp.json` на Windows:
|
|
122
|
+
|
|
123
|
+
```json
|
|
124
|
+
{"mcpServers":{"google-search-console":{"type":"stdio","command":"npx","args":["-y","mcp-google-search-console@latest"]}}}
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
[Документация Cursor MCP](https://cursor.com/docs/mcp)
|
|
128
|
+
|
|
129
|
+
</details>
|
|
130
|
+
|
|
131
|
+
<details><summary><strong>VS Code</strong></summary>
|
|
132
|
+
|
|
133
|
+
<br>
|
|
134
|
+
|
|
135
|
+
Запустите **MCP: Open User Configuration** и добавьте:
|
|
136
|
+
|
|
137
|
+
```json
|
|
138
|
+
{"servers":{"google-search-console":{"type":"stdio","command":"npx","args":["-y","mcp-google-search-console@latest"]}}}
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
Проверьте сервер командой **MCP: List Servers**. [Документация VS Code MCP](https://code.visualstudio.com/docs/agent-customization/mcp-servers)
|
|
142
|
+
|
|
143
|
+
</details>
|
|
144
|
+
|
|
145
|
+
## Что можно поручить
|
|
146
|
+
|
|
147
|
+
### Найти поисковые возможности
|
|
148
|
+
|
|
149
|
+
- Какие запросы и страницы принесли больше всего кликов в этом месяце?
|
|
150
|
+
- Какие страницы потеряли клики по сравнению с прошлым периодом?
|
|
151
|
+
- Покажи запросы с `mcp`, где средняя позиция ниже 10.
|
|
152
|
+
|
|
153
|
+
### Проверить индексацию и sitemap
|
|
154
|
+
|
|
155
|
+
- Проиндексирован ли этот URL? Покажи покрытие, обход и canonical information.
|
|
156
|
+
- В каких отправленных sitemap есть ошибки или предупреждения?
|
|
157
|
+
- Повторно отправь этот sitemap, сначала показав его текущий статус.
|
|
158
|
+
|
|
159
|
+
### Аккуратно управлять свойствами
|
|
160
|
+
|
|
161
|
+
- Покажи свойства Search Console, к которым у меня есть доступ.
|
|
162
|
+
- Добавь это точное значение свойства; подтверждение владения я пройду отдельно.
|
|
163
|
+
- Удали это свойство из аккаунта после подтверждения.
|
|
164
|
+
|
|
165
|
+
## Как устроены свойства Search Console
|
|
166
|
+
|
|
167
|
+
URL-prefix property должен содержать протокол и завершающий слеш: например, `https://example.com/`. Domain property записывается как `sc-domain:example.com`. Почти совпадающее значение вернёт 403 или 404, поэтому используйте точное значение от `list_sites`.
|
|
168
|
+
|
|
169
|
+
`add_site` только регистрирует свойство. Подтверждение владения остаётся в интерфейсе Search Console или Site Verification API. Поисковые данные используют тихоокеанское время; `end_date` включительно, а финальные данные обычно отстают на два–три дня. `data_state: "all"` может включить более свежие, но меняющиеся строки.
|
|
170
|
+
|
|
171
|
+
## Что может измениться
|
|
172
|
+
|
|
173
|
+
| Операция | Что происходит | Граница подтверждения |
|
|
174
|
+
|---|---|---|
|
|
175
|
+
| Просмотр свойств, аналитики, sitemap и статуса URL | Читает данные Search Console | Ничего не меняет |
|
|
176
|
+
| Добавление свойства | Добавляет запись свойства, но не подтверждает его | Меняет доступ аккаунта |
|
|
177
|
+
| Отправка или повторная отправка sitemap | Запрашивает обработку sitemap | Меняет состояние Search Console |
|
|
178
|
+
| Удаление свойства | Отвязывает свойство от аккаунта; данные Google не удаляются | Разрушительно |
|
|
179
|
+
| Удаление sitemap | Удаляет отправленный sitemap | Разрушительно |
|
|
180
|
+
| Технический запрос API | Может вызвать endpoint записи или удаления | Потенциально разрушительно |
|
|
181
|
+
|
|
182
|
+
Как AI-приложение спрашивает подтверждение, определяет само приложение. Сервер помечает чтение, запись и удаление, чтобы оно отличило проверку от изменения.
|
|
183
|
+
|
|
184
|
+
## Как получить доступ
|
|
185
|
+
|
|
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 и автоматические установки)
|
|
200
|
+
|
|
201
|
+
1. Создайте или выберите проект Google Cloud и включите **Google Search Console API**.
|
|
202
|
+
2. Настройте OAuth consent screen и создайте OAuth-клиент типа **Desktop app**.
|
|
203
|
+
3. Через [OAuth 2.0 Playground](https://developers.google.com/oauthplayground) с включённым **Use your own OAuth credentials** авторизуйте Google-аккаунт с доступом к свойствам и получите refresh token.
|
|
204
|
+
4. Используйте `https://www.googleapis.com/auth/webmasters` для sitemap и изменения свойств. `https://www.googleapis.com/auth/webmasters.readonly` подходит, только если нужен намеренно read-only доступ.
|
|
205
|
+
|
|
206
|
+
Refresh token OAuth-приложения в режиме Testing может истечь через семь дней. Для долгого доступа опубликуйте приложение или используйте Internal-приложение Workspace. Храните client secret и refresh token как пароли.
|
|
207
|
+
|
|
208
|
+
## Конфигурация
|
|
209
|
+
|
|
210
|
+
Все переменные необязательные — без единой из них сервер подключается [из диалога](#подключение-из-диалога-рекомендуемый-путь).
|
|
211
|
+
|
|
212
|
+
| Переменная | Обязательна | Описание |
|
|
213
|
+
|---|---|---|
|
|
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. |
|
|
219
|
+
| `GOOGLE_SEARCH_CONSOLE_API_BASE` | Нет | Переопределяет базовый URL API. |
|
|
220
|
+
| `GOOGLE_SEARCH_CONSOLE_TIMEOUT_MS` | Нет | Тайм-аут запроса; по умолчанию `60000` мс. |
|
|
221
|
+
| `GOOGLE_SEARCH_CONSOLE_MAX_RETRIES` | Нет | Повторы временных ошибок; по умолчанию `3`. |
|
|
222
|
+
|
|
223
|
+
\* Передайте OAuth-тройку или access token.
|
|
224
|
+
|
|
225
|
+
## Данные, лимиты и работа в фоне
|
|
226
|
+
|
|
227
|
+
- **Приватность.** Локальный сервер вызывает Google и отправляет анонимную телеметрию с ID установки, версиями и именами инструментов — но не OAuth-токены, данные свойств, аргументы или промпты. Чтобы отключить её, задайте `ASKADS_TELEMETRY=0`.
|
|
228
|
+
- **Лимиты API.** URL inspection разрешает 2 000 проверок на свойство в сутки и 600 в минуту. Analytics возвращает максимум 25 000 строк за вызов; анонимизированные long-tail запросы никогда не возвращаются. Используйте пагинацию и не проверяйте сайт URL за URL.
|
|
229
|
+
- **Постоянного наблюдения нет.** Сервер работает только при вызове. Если AI-приложение поддерживает задания по расписанию, оно может периодически проверять sitemap или важный URL.
|
|
230
|
+
|
|
231
|
+
## Техническая документация
|
|
232
|
+
|
|
233
|
+
- [Каталог MCP-возможностей](./docs/capabilities/index.md) — страницы по пользовательским задачам для каждого инструмента.
|
|
234
|
+
- [Все инструменты и параметры](./docs/TOOLS.md)
|
|
235
|
+
- [Документация по разработке](./docs/DEVELOPMENT.md)
|
|
236
|
+
- [Документация по публикации](./docs/PUBLISHING.md)
|
|
237
|
+
- [Google Search Console API](https://developers.google.com/webmaster-tools)
|
|
238
|
+
|
|
239
|
+
## Поддержка
|
|
240
|
+
|
|
241
|
+
Нашли ошибку или не хватает сценария? [Создайте issue](https://github.com/A1-x-Tech/mcp-google-search-console/issues) или напишите в [Telegram](https://t.me/a1_mcp).
|
|
242
|
+
|
|
243
|
+
<br>
|
|
244
|
+
|
|
245
|
+
<p align="center">
|
|
246
|
+
<img src="https://github.com/ztemerbekov/a1-yandex-kit-skills/raw/main/assets/images/mona-hifive-yandex-kit-warm.gif" alt="Две Моны дают пять" width="256">
|
|
247
|
+
</p>
|
|
248
|
+
|
|
249
|
+
<p align="center">
|
|
250
|
+
Вы дочитали до конца!
|
|
251
|
+
</p>
|
package/dist/client.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { GoogleSearchConsoleError } from "./types.js";
|
|
2
|
+
import { CredentialsError, DEFAULT_BASE } 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
|
/**
|
|
@@ -12,6 +13,7 @@ function seg(value) {
|
|
|
12
13
|
}
|
|
13
14
|
export class GoogleSearchConsoleClient {
|
|
14
15
|
config;
|
|
16
|
+
tokenProvider;
|
|
15
17
|
base;
|
|
16
18
|
timeoutMs;
|
|
17
19
|
maxRetries;
|
|
@@ -20,8 +22,16 @@ export class GoogleSearchConsoleClient {
|
|
|
20
22
|
cachedToken;
|
|
21
23
|
/** In-flight refresh, deduping concurrent token requests. */
|
|
22
24
|
refreshInFlight;
|
|
23
|
-
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) {
|
|
24
33
|
this.config = config;
|
|
34
|
+
this.tokenProvider = tokenProvider;
|
|
25
35
|
this.base = config.apiBase.endsWith("/") ? config.apiBase : config.apiBase + "/";
|
|
26
36
|
this.timeoutMs = config.timeoutMs ?? 60_000;
|
|
27
37
|
this.maxRetries = config.maxRetries ?? 3;
|
|
@@ -30,16 +40,37 @@ export class GoogleSearchConsoleClient {
|
|
|
30
40
|
canRefresh() {
|
|
31
41
|
return Boolean(this.config.refreshToken && this.config.clientId && this.config.clientSecret);
|
|
32
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
|
+
}
|
|
33
56
|
/**
|
|
34
57
|
* Returns a valid Bearer token. With the refresh triple configured, mints an
|
|
35
58
|
* access token from the refresh token and caches it until shortly before it
|
|
36
59
|
* expires (concurrent callers share one in-flight refresh); otherwise the
|
|
37
|
-
* static GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN is used as-is.
|
|
60
|
+
* static GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN is used as-is. With neither
|
|
61
|
+
* configured, throws {@link CredentialsError} BEFORE any fetch — a missing
|
|
62
|
+
* setup must never enter the retry/backoff loop or trigger the 401 re-mint,
|
|
63
|
+
* because no amount of retrying mints credentials.
|
|
38
64
|
*/
|
|
39
65
|
async accessToken(forceRefresh = false) {
|
|
40
66
|
if (!this.canRefresh()) {
|
|
41
|
-
//
|
|
42
|
-
|
|
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();
|
|
43
74
|
}
|
|
44
75
|
if (!forceRefresh && this.cachedToken && Date.now() < this.cachedToken.expiresAt) {
|
|
45
76
|
return this.cachedToken.value;
|
|
@@ -169,7 +200,7 @@ export class GoogleSearchConsoleClient {
|
|
|
169
200
|
}
|
|
170
201
|
// An expired/revoked access token: re-mint once and replay. The request
|
|
171
202
|
// never executed, so this is safe for writes too.
|
|
172
|
-
if (res.status === 401 && this.
|
|
203
|
+
if (res.status === 401 && this.canReplayOn401() && !refreshedOn401) {
|
|
173
204
|
refreshedOn401 = true;
|
|
174
205
|
await this.accessToken(true);
|
|
175
206
|
continue;
|
|
@@ -288,3 +319,28 @@ function compact(obj) {
|
|
|
288
319
|
function delay(ms) {
|
|
289
320
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
290
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/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,38 @@ 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
|
+
import { authUnconfiguredPrefix, hasAuthToken, registerAuthTools } from "./tools/auth.js";
|
|
14
|
+
/**
|
|
15
|
+
* Prepended to every session as the `instructions` of the MCP initialize result
|
|
16
|
+
* — the only prose the calling model sees before it picks a tool. It carries
|
|
17
|
+
* what the tool list cannot: which product this is, what the API refuses to do,
|
|
18
|
+
* what a call costs, and how its errors decode.
|
|
19
|
+
*/
|
|
20
|
+
const INSTRUCTIONS = "Google Search Console reports how a property performs in organic Google Search and how its URLs " +
|
|
21
|
+
"stand in the index — not Google Analytics (on-site traffic), not Google Ads. Nothing here can " +
|
|
22
|
+
"request (re)indexing; a sitemap submission is the only nudge, and writes are limited to " +
|
|
23
|
+
"linking/unlinking a property and submitting/removing sitemaps. Batch work is where it bites: " +
|
|
24
|
+
"2,000 URL inspections per property a day and 200 sites/sitemaps calls a minute — never sweep a " +
|
|
25
|
+
"whole site; 429s and read-side 5xx are already retried inside the server, so a returned error is " +
|
|
26
|
+
"final. Take property ids verbatim from list_sites: a 403/404 is usually a near-miss id (scheme, " +
|
|
27
|
+
"www, trailing slash, sc-domain:), not a permissions problem; a 403 on a write points at a " +
|
|
28
|
+
"readonly token; auth failing on every call means a dead refresh token (they expire after 7 days " +
|
|
29
|
+
"while the OAuth consent screen is in Testing). Empty rows[] on the first page usually means the " +
|
|
30
|
+
"dates fall in the 2-3 day finalization lag or you queried a sibling property, not zero traffic. " +
|
|
31
|
+
"Confirm with the user before delete_site or delete_sitemap.";
|
|
32
|
+
/**
|
|
33
|
+
* Prepended to INSTRUCTIONS when no credentials are configured. The model reads
|
|
34
|
+
* this before it picks a tool, so an unconfigured session opens with the fix
|
|
35
|
+
* rather than with a failed call. There is no in-chat login here: credentials
|
|
36
|
+
* come only from the environment, so the fix is an operator action + restart.
|
|
37
|
+
*/
|
|
13
38
|
/** Reads the package version so the server reports its real version to MCP clients. */
|
|
14
39
|
function readVersion() {
|
|
15
40
|
try {
|
|
@@ -21,21 +46,27 @@ function readVersion() {
|
|
|
21
46
|
}
|
|
22
47
|
}
|
|
23
48
|
/**
|
|
24
|
-
* Loads the config
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
49
|
+
* Loads the config without dying on a bad value. A server that exits here never
|
|
50
|
+
* completes the MCP handshake, so the user sees a dead server and no reason.
|
|
51
|
+
* Instead the problem is carried into the session, where the model can read it
|
|
52
|
+
* and relay it: the config degrades to "no credentials" and every tool call
|
|
53
|
+
* fails with the actionable message.
|
|
28
54
|
*/
|
|
29
|
-
|
|
55
|
+
function loadConfigOrDegraded(telemetry) {
|
|
30
56
|
try {
|
|
31
|
-
return loadConfig();
|
|
57
|
+
return { config: loadConfig() };
|
|
32
58
|
}
|
|
33
59
|
catch (err) {
|
|
34
60
|
if (!(err instanceof ConfigError))
|
|
35
61
|
throw err;
|
|
36
62
|
console.error(`Error: ${err.message}`);
|
|
37
|
-
|
|
38
|
-
|
|
63
|
+
// Fire-and-forget now that the process survives: the historical
|
|
64
|
+
// `startup_failed` funnel stays comparable, but nothing blocks startup.
|
|
65
|
+
telemetry.send("startup_failed", { reason: err.reason });
|
|
66
|
+
return {
|
|
67
|
+
config: { apiBase: process.env.GOOGLE_SEARCH_CONSOLE_API_BASE || DEFAULT_BASE },
|
|
68
|
+
problem: err,
|
|
69
|
+
};
|
|
39
70
|
}
|
|
40
71
|
}
|
|
41
72
|
async function main() {
|
|
@@ -43,17 +74,35 @@ async function main() {
|
|
|
43
74
|
// opt out with ASKADS_TELEMETRY=0. Built before the config so missing
|
|
44
75
|
// credentials can be reported; wired to the server before tools register.
|
|
45
76
|
const telemetry = new Telemetry(readVersion());
|
|
46
|
-
const config =
|
|
47
|
-
|
|
77
|
+
const { config, problem } = loadConfigOrDegraded(telemetry);
|
|
78
|
+
// Decided once, at startup: credentials come only from the environment, so
|
|
79
|
+
// "restart after setting the variables" is the accurate advice to give.
|
|
80
|
+
const connected = hasCredentials(config) || hasAuthToken();
|
|
81
|
+
// `instructions` rides in the options argument (not serverInfo) — that is what
|
|
82
|
+
// the SDK copies into the initialize result.
|
|
48
83
|
const server = new McpServer({
|
|
49
84
|
name: "mcp-google-search-console",
|
|
50
85
|
version: readVersion(),
|
|
86
|
+
}, {
|
|
87
|
+
instructions: connected
|
|
88
|
+
? INSTRUCTIONS
|
|
89
|
+
: authUnconfiguredPrefix() + (problem ? `Configuration problem: ${problem.message} ` : "") + INSTRUCTIONS,
|
|
51
90
|
});
|
|
52
91
|
instrumentToolCalls(server, telemetry);
|
|
53
92
|
server.server.oninitialized = () => {
|
|
54
93
|
telemetry.setClientInfo(server.server.getClientVersion());
|
|
55
|
-
|
|
94
|
+
// Split on purpose: `server_start` keeps meaning "a usable install started",
|
|
95
|
+
// so the unconfigured case gets its own event instead of inflating that number.
|
|
96
|
+
if (connected)
|
|
97
|
+
telemetry.send("server_start");
|
|
98
|
+
else
|
|
99
|
+
telemetry.send("unconfigured_start", { reason: problem?.reason ?? "missing_credentials" });
|
|
56
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);
|
|
57
106
|
registerSiteTools(server, client);
|
|
58
107
|
registerSitemapTools(server, client);
|
|
59
108
|
registerAnalyticsTools(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);
|