wordstat-bridge-mcp 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tentek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,70 @@
1
- # Temporary Holding Version
1
+ # Wordstat Bridge · by Tentek — частотность Вордстата в Claude
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ MCP-сервер, который даёт Claude данные Яндекс Вордстата: частотность, «что ещё ищут»,
4
+ динамику, регионы и готовое семантическое ядро. **Без ключей, Yandex Cloud и оплаты запросов** —
5
+ данные берутся с обычного сайта wordstat.yandex.ru в вашем браузере, под вашим аккаунтом.
6
+
7
+ ```
8
+ Claude ──> этот MCP-сервер (на вашем компьютере) ──> расширение в браузере ──> wordstat.yandex.ru
9
+ ```
10
+
11
+ ## Установка
12
+
13
+ Нужны две части: **расширение** в Chrome / Яндекс Браузере и **этот сервер** в Claude.
14
+
15
+ 1. **Расширение** «Wordstat Bridge» — из Chrome Web Store. Войдите в аккаунт Яндекса
16
+ на wordstat.yandex.ru.
17
+ 2. **Сервер:**
18
+ - **Claude Desktop** — скачайте файл [`wordstat-bridge.mcpb`](https://github.com/kaicex/wordstat-bridge/releases/latest/download/wordstat-bridge.mcpb) и откройте его
19
+ двойным кликом. Node.js ставить не нужно.
20
+ - **Claude Code:**
21
+ ```bash
22
+ claude mcp add --scope user wordstat -- npx -y wordstat-bridge-mcp
23
+ ```
24
+ - **Cursor и другие клиенты MCP** — команда `npx -y wordstat-bridge-mcp` (нужен Node.js 20+).
25
+
26
+ Проверка без Claude (браузер с расширением открыт):
27
+
28
+ ```bash
29
+ npx -y wordstat-bridge-mcp check "купить велосипед"
30
+ ```
31
+
32
+ Потом спросите Claude: «Сколько ищут „купить велосипед“ в Москве и что ещё ищут?»
33
+
34
+ ## Что умеет
35
+
36
+ | Инструмент | Что делает |
37
+ |---|---|
38
+ | `wordstat_top` | Частотность, «что ещё ищут» и похожие запросы |
39
+ | `wordstat_frequencies` | Базовая и точная частотность списка фраз (до 50) |
40
+ | `wordstat_dynamics` | Динамика по месяцам, неделям или дням |
41
+ | `wordstat_regions` | Спрос по регионам и городам с индексом интереса |
42
+ | `wordstat_semantic_core` | Семантическое ядро: раскрытие, без дублей, группы по смыслу, отсев накрутки, минус-слова |
43
+ | `wordstat_status` | Подключено ли расширение |
44
+
45
+ Числа `top`, `frequencies`, `regions` и ядра — за последние 30 дней, за которые у Вордстата есть
46
+ данные (точные даты приходят в ответе). Конкретные месяцы, недели и дни — в `wordstat_dynamics`.
47
+
48
+ ## Приватность
49
+
50
+ Всё работает на вашем компьютере. Сервер общается с расширением только через `127.0.0.1` и
51
+ принимает подключения только от расширения «Wordstat Bridge». Запросы к Вордстату
52
+ выполняются в вашем браузере, никуда больше данные не отправляются.
53
+
54
+ ## Если что-то не работает
55
+
56
+ - **«Расширение не подключено»** — браузер закрыт или расширение выключено. Значок должен быть
57
+ зелёным «ON».
58
+ - **Капча** — расширение само развернёт окно Вордстата (на значке красный «!»): пройдите её и
59
+ повторите вопрос.
60
+ - **Несколько окон Claude сразу** — работает: первое держит связь с расширением, остальные идут через него.
61
+
62
+ ## Важно
63
+
64
+ Расширение использует внутренние запросы сайта Вордстата так же, как сама страница. Яндекс может их
65
+ изменить — тогда понадобится обновление. Пользуйтесь умеренно: между запросами выдерживается пауза.
66
+
67
+ Не связан с ООО «Яндекс» и Anthropic, не официальный продукт. Вордстат и Яндекс — товарные знаки
68
+ ООО «Яндекс», Claude — товарный знак Anthropic.
69
+
70
+ MIT · Tentek
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "wordstat-bridge-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Wordstat Bridge — частотность Вордстата в Claude: MCP-сервер для данных wordstat.yandex.ru через браузерное расширение, без ключей и Yandex Cloud",
5
+ "type": "module",
6
+ "bin": {
7
+ "wordstat-bridge-mcp": "src/index.js"
8
+ },
9
+ "main": "src/index.js",
10
+ "scripts": {
11
+ "start": "node src/index.js",
12
+ "check": "node src/index.js check",
13
+ "test": "node --test test/*.test.js"
14
+ },
15
+ "engines": {
16
+ "node": ">=20"
17
+ },
18
+ "dependencies": {
19
+ "@modelcontextprotocol/sdk": "^1.32.2",
20
+ "ws": "^8.23.0",
21
+ "zod": "^3.25.76"
22
+ },
23
+ "license": "MIT",
24
+ "files": [
25
+ "src/",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "keywords": [
30
+ "mcp",
31
+ "model-context-protocol",
32
+ "claude",
33
+ "wordstat",
34
+ "yandex",
35
+ "вордстат",
36
+ "seo",
37
+ "keywords",
38
+ "семантическое ядро"
39
+ ],
40
+ "author": "Tentek",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://github.com/kaicex/wordstat-bridge.git",
44
+ "directory": "server"
45
+ },
46
+ "homepage": "https://github.com/kaicex/wordstat-bridge#readme",
47
+ "bugs": {
48
+ "url": "https://github.com/kaicex/wordstat-bridge/issues"
49
+ }
50
+ }
package/src/bridge.js ADDED
@@ -0,0 +1,367 @@
1
+ // WebSocket bridge between this MCP server and the Chrome extension.
2
+ // The extension connects to ws://127.0.0.1:<port>; we send it jobs
3
+ // ({id, endpoint, body}) and it answers ({id, ok, status, payload | error}).
4
+ //
5
+ // Several MCP servers may run at once (one per Claude session), but only one
6
+ // can own the port. The first one becomes the "hub": it holds the extension
7
+ // connection. Others become "peers": they connect to the hub over the same
8
+ // port and send their calls through it, so all calls share one queue and one
9
+ // throttle. When the hub exits, a peer takes the port over.
10
+ import WebSocket, { WebSocketServer } from "ws";
11
+
12
+ const PEER_EXTRA_MS = 15000; // a peer waits a bit longer than the hub's own timeout
13
+
14
+ // ID of the Wordstat Bridge extension. It is fixed by the "key" in
15
+ // extension/manifest.json, so it does not depend on where the folder lives.
16
+ export const EXTENSION_ID = "nlfkhnhaiecpeadgjemdpgkpoimjpijh";
17
+
18
+ /** Allowed extension IDs: WORDSTAT_EXTENSION_IDS="id1,id2" overrides the default. */
19
+ export function allowedExtensionIds(env = process.env) {
20
+ const list = String(env.WORDSTAT_EXTENSION_IDS ?? "")
21
+ .split(",")
22
+ .map((s) => s.trim())
23
+ .filter(Boolean);
24
+ return list.length ? list : [EXTENSION_ID];
25
+ }
26
+
27
+ export class ExtensionBridge {
28
+ constructor({
29
+ port = 8787,
30
+ host = "127.0.0.1",
31
+ minIntervalMs = 1500,
32
+ timeoutMs = 45000,
33
+ extensionIds = allowedExtensionIds(),
34
+ reconnectGraceMs = 8000,
35
+ log = () => {},
36
+ } = {}) {
37
+ this.reconnectGraceMs = reconnectGraceMs;
38
+ this.port = port;
39
+ this.allowedOrigins = new Set(extensionIds.map((id) => `chrome-extension://${id}`));
40
+ this.host = host;
41
+ this.minIntervalMs = minIntervalMs;
42
+ this.timeoutMs = timeoutMs;
43
+ this.log = log;
44
+ this.mode = null; // "hub" | "peer"
45
+ this.socket = null; // hub: the extension
46
+ this.extensionInfo = null;
47
+ this.peers = new Set(); // hub: connected peer servers
48
+ this.hub = null; // peer: socket to the hub
49
+ this.hubExtension = { connected: false, info: null }; // peer: hub's view of the extension
50
+ this.pending = new Map();
51
+ this.nextId = 1;
52
+ this.queue = Promise.resolve();
53
+ this.lastCallAt = 0;
54
+ this.listenError = null;
55
+ this.stopped = false;
56
+ }
57
+
58
+ /** Becomes the hub, or a peer of an existing hub. Never rejects. */
59
+ async start() {
60
+ this.stopped = false;
61
+ return this.#takeOver();
62
+ }
63
+
64
+ async #takeOver() {
65
+ const err = await this.#listen();
66
+ if (!err) return;
67
+ if (err.code !== "EADDRINUSE") {
68
+ this.listenError = err;
69
+ return;
70
+ }
71
+ const peerErr = await this.#connectToHub();
72
+ if (!peerErr) return;
73
+ // The port is taken by something that is not our hub, or the hub just
74
+ // went away. Retry once more as hub, then give up.
75
+ const again = await this.#listen();
76
+ if (!again) return;
77
+ this.listenError = again.code === "EADDRINUSE" ? peerErr : again;
78
+ }
79
+
80
+ #listen() {
81
+ return new Promise((resolve) => {
82
+ const wss = new WebSocketServer({
83
+ host: this.host,
84
+ port: this.port,
85
+ // Only our extension (by ID) and local processes (no Origin header:
86
+ // other sessions' servers) may connect. Web pages and other
87
+ // extensions always send an Origin, so they are refused here.
88
+ verifyClient: ({ origin }) => {
89
+ const ok = !origin || this.allowedOrigins.has(origin);
90
+ if (!ok) this.log(`refused connection from ${origin}`);
91
+ return ok;
92
+ },
93
+ });
94
+ wss.once("listening", () => {
95
+ this.wss = wss;
96
+ this.mode = "hub";
97
+ this.listenError = null;
98
+ wss.on("error", (err) => this.log(`bridge error: ${err.message}`));
99
+ wss.on("connection", (ws, req) => this.#onConnection(ws, req.headers.origin));
100
+ this.log(`bridge listening on ws://${this.host}:${this.port} (hub)`);
101
+ resolve(null);
102
+ });
103
+ wss.once("error", (err) => {
104
+ wss.close();
105
+ resolve(err);
106
+ });
107
+ });
108
+ }
109
+
110
+ #connectToHub() {
111
+ return new Promise((resolve) => {
112
+ const ws = new WebSocket(`ws://${this.host}:${this.port}`);
113
+ const fail = (err) => {
114
+ clearTimeout(timer);
115
+ ws.removeAllListeners();
116
+ ws.terminate();
117
+ resolve(err);
118
+ };
119
+ const timer = setTimeout(() => fail(new Error(`порт ${this.port} занят, но хаб сервера Вордстата не отвечает`)), 3000);
120
+ ws.on("error", (err) => fail(err));
121
+ ws.on("open", () => ws.send(JSON.stringify({ type: "peer-hello" })));
122
+ ws.on("message", (raw) => {
123
+ let msg;
124
+ try {
125
+ msg = JSON.parse(String(raw));
126
+ } catch {
127
+ return;
128
+ }
129
+ if (msg.type === "hub-hello") {
130
+ clearTimeout(timer);
131
+ ws.removeAllListeners("error");
132
+ this.#becomePeer(ws, msg);
133
+ resolve(null);
134
+ }
135
+ });
136
+ });
137
+ }
138
+
139
+ #becomePeer(ws, hello) {
140
+ this.hub = ws;
141
+ this.mode = "peer";
142
+ this.listenError = null;
143
+ this.hubExtension = { connected: !!hello.extension_connected, info: hello.extension ?? null };
144
+ this.log(`bridge: port ${this.port} is taken by another session, working through it (peer)`);
145
+ ws.on("message", (raw) => {
146
+ let msg;
147
+ try {
148
+ msg = JSON.parse(String(raw));
149
+ } catch {
150
+ return;
151
+ }
152
+ if (msg.type === "extension") {
153
+ this.hubExtension = { connected: !!msg.connected, info: msg.info ?? null };
154
+ return;
155
+ }
156
+ if (msg.type === "result") this.#settle(msg.id, msg);
157
+ });
158
+ ws.on("error", () => {});
159
+ ws.on("close", () => {
160
+ if (this.hub !== ws) return;
161
+ this.hub = null;
162
+ this.hubExtension = { connected: false, info: null };
163
+ this.#rejectAll("Сессия Claude, через которую шли запросы, закрылась. Повторите запрос.");
164
+ if (this.stopped) return;
165
+ this.log("bridge: hub went away, taking over");
166
+ // Small random delay so that several peers don't race for the port at once.
167
+ setTimeout(() => !this.stopped && this.#takeOver(), 200 + Math.floor(Math.random() * 600));
168
+ });
169
+ }
170
+
171
+ stop() {
172
+ this.stopped = true;
173
+ this.#rejectAll("bridge stopped");
174
+ this.socket?.close();
175
+ for (const p of this.peers) p.close();
176
+ this.hub?.close();
177
+ const wss = this.wss;
178
+ this.wss = null;
179
+ // Drop every remaining client too, or close() waits for them forever.
180
+ for (const c of wss?.clients ?? []) c.terminate();
181
+ return new Promise((r) => (wss ? wss.close(() => r()) : r()));
182
+ }
183
+
184
+ get connected() {
185
+ if (this.mode === "peer") return !!this.hub && this.hub.readyState === 1 && this.hubExtension.connected;
186
+ return !!this.socket && this.socket.readyState === 1;
187
+ }
188
+
189
+ status() {
190
+ return {
191
+ mode: this.mode,
192
+ listening: this.mode === "hub",
193
+ listen_error: this.listenError?.message ?? null,
194
+ address: `ws://${this.host}:${this.port}`,
195
+ extension_connected: this.connected,
196
+ extension: this.mode === "peer" ? this.hubExtension.info : this.extensionInfo,
197
+ ...(this.mode === "hub" ? { peer_sessions: this.peers.size } : {}),
198
+ };
199
+ }
200
+
201
+ #broadcastExtension() {
202
+ const msg = JSON.stringify({ type: "extension", connected: this.connected, info: this.extensionInfo });
203
+ for (const p of this.peers) if (p.readyState === 1) p.send(msg);
204
+ }
205
+
206
+ // Hub: a new socket is either the extension (sends "hello") or a peer
207
+ // server (sends "peer-hello"). Nothing is assigned until it says which.
208
+ #onConnection(ws, origin) {
209
+ // An extension always has an Origin; a peer server never does. Each may
210
+ // only claim its own role.
211
+ const fromExtension = !!origin && this.allowedOrigins.has(origin);
212
+ let role = null;
213
+ ws.on("message", (raw) => {
214
+ let msg;
215
+ try {
216
+ msg = JSON.parse(String(raw));
217
+ } catch {
218
+ return;
219
+ }
220
+ if (msg.type === "peer-hello" && !role && !fromExtension) {
221
+ role = "peer";
222
+ this.peers.add(ws);
223
+ ws.send(
224
+ JSON.stringify({ type: "hub-hello", extension_connected: this.connected, extension: this.extensionInfo })
225
+ );
226
+ this.log(`peer session connected (${this.peers.size})`);
227
+ return;
228
+ }
229
+ if (role === "peer") {
230
+ if (msg.type === "call") this.#servePeer(ws, msg);
231
+ return;
232
+ }
233
+ if (msg.type === "hello" && fromExtension) {
234
+ if (this.socket && this.socket !== ws) this.socket.close(4000, "replaced by newer connection");
235
+ role = "extension";
236
+ this.socket = ws;
237
+ this.extensionInfo = { version: msg.version ?? null, connected_at: new Date().toISOString() };
238
+ this.log("extension connected");
239
+ this.#broadcastExtension();
240
+ return;
241
+ }
242
+ if (role !== "extension") return;
243
+ if (msg.type === "ping") {
244
+ ws.send(JSON.stringify({ type: "pong" }));
245
+ return;
246
+ }
247
+ this.#settle(msg.id, msg);
248
+ });
249
+ ws.on("error", () => {});
250
+ ws.on("close", () => {
251
+ if (role === "peer") {
252
+ this.peers.delete(ws);
253
+ return;
254
+ }
255
+ if (this.socket === ws) {
256
+ this.socket = null;
257
+ this.log("extension disconnected");
258
+ this.#broadcastExtension();
259
+ }
260
+ });
261
+ }
262
+
263
+ async #servePeer(ws, msg) {
264
+ let reply;
265
+ try {
266
+ reply = { ok: true, payload: await this.call(msg.endpoint, msg.body, msg.meta) };
267
+ } catch (err) {
268
+ reply = { ok: false, error: err.message, code: err.code, details: err.details };
269
+ }
270
+ if (ws.readyState === 1) ws.send(JSON.stringify({ type: "result", id: msg.id, ...reply }));
271
+ }
272
+
273
+ #settle(id, msg) {
274
+ const p = this.pending.get(id);
275
+ if (!p) return;
276
+ this.pending.delete(id);
277
+ clearTimeout(p.timer);
278
+ p.resolve(msg);
279
+ }
280
+
281
+ #rejectAll(message) {
282
+ for (const { reject, timer } of this.pending.values()) {
283
+ clearTimeout(timer);
284
+ reject(new Error(message));
285
+ }
286
+ this.pending.clear();
287
+ }
288
+
289
+ #request(sock, msg, timeoutMs, endpoint) {
290
+ const id = this.nextId++;
291
+ return new Promise((resolve, reject) => {
292
+ const timer = setTimeout(() => {
293
+ this.pending.delete(id);
294
+ reject(new Error(`Таймаут ${Math.round(timeoutMs / 1000)} с: расширение не ответило на ${endpoint}.`));
295
+ }, timeoutMs);
296
+ this.pending.set(id, { resolve, reject, timer });
297
+ sock.send(JSON.stringify({ ...msg, id }));
298
+ });
299
+ }
300
+
301
+ static #toResult(reply, endpoint) {
302
+ if (!reply.ok) {
303
+ const err = new Error(reply.error || `Wordstat ${endpoint}: ошибка`);
304
+ err.code = reply.code;
305
+ err.details = reply.details ?? reply;
306
+ throw err;
307
+ }
308
+ return reply.payload;
309
+ }
310
+
311
+ /**
312
+ * The browser may put the extension's service worker to sleep and wake it
313
+ * again; it reconnects within a few seconds. Wait a little before failing.
314
+ */
315
+ async #waitConnected(ms = this.reconnectGraceMs) {
316
+ const t0 = Date.now();
317
+ while (!this.connected && Date.now() - t0 < ms && !this.stopped) await new Promise((r) => setTimeout(r, 200));
318
+ return this.connected;
319
+ }
320
+
321
+ /**
322
+ * Calls a wordstat.yandex.ru/wordstat/api/<endpoint>. Calls are serialized and throttled (on the hub).
323
+ * Endpoints starting with "__" are service calls answered by the extension itself
324
+ * (plan status, start of a semantic core). `meta` travels with the call (core token).
325
+ */
326
+ async call(endpoint, body, meta) {
327
+ if (this.mode === "peer") {
328
+ if (!(await this.#waitConnected())) throw this.#notConnectedError();
329
+ return this.#request(this.hub, { type: "call", endpoint, body, ...(meta ? { meta } : {}) }, this.timeoutMs + PEER_EXTRA_MS, endpoint).then(
330
+ (reply) => ExtensionBridge.#toResult(reply, endpoint)
331
+ );
332
+ }
333
+ const run = async () => {
334
+ if (this.listenError) {
335
+ throw new Error(
336
+ `Мост не запущен: ${this.listenError.message}. ` +
337
+ `Порт ${this.port} занят другой программой — закройте её или задайте WORDSTAT_BRIDGE_PORT.`
338
+ );
339
+ }
340
+ if (!(await this.#waitConnected())) throw this.#notConnectedError();
341
+ if (!endpoint.startsWith("__")) {
342
+ const wait = this.lastCallAt + this.minIntervalMs - Date.now();
343
+ if (wait > 0) await new Promise((r) => setTimeout(r, wait));
344
+ this.lastCallAt = Date.now();
345
+ }
346
+ let reply = await this.#request(this.socket, { type: "call", endpoint, body, ...(meta ? { meta } : {}) }, this.timeoutMs, endpoint);
347
+ // Wordstat occasionally never answers one request (the extension gives
348
+ // up and reports "timeout"); the same request usually works right away.
349
+ if (!reply.ok && reply.code === "timeout" && this.connected) {
350
+ this.log(`${endpoint}: Wordstat timed out, retrying once`);
351
+ this.lastCallAt = Date.now();
352
+ reply = await this.#request(this.socket, { type: "call", endpoint, body, ...(meta ? { meta } : {}) }, this.timeoutMs, endpoint);
353
+ }
354
+ return ExtensionBridge.#toResult(reply, endpoint);
355
+ };
356
+ const result = this.queue.then(run, run);
357
+ this.queue = result.catch(() => {});
358
+ return result;
359
+ }
360
+
361
+ #notConnectedError() {
362
+ return new Error(
363
+ "Расширение «Wordstat Bridge» не подключено. Откройте браузер, проверьте, что расширение включено " +
364
+ "(значок должен быть зелёным «ON»), и повторите запрос."
365
+ );
366
+ }
367
+ }
package/src/check.js ADDED
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env node
2
+ // Self-check without Claude: node src/check.js "купить велосипед"
3
+ // Starts the bridge, waits for the Chrome extension, makes one real request.
4
+ import { ExtensionBridge } from "./bridge.js";
5
+ import { commonBody, lastFullMonth, parseTop } from "./wordstat.js";
6
+
7
+ const phrase = process.argv[2] || "купить велосипед";
8
+ const port = Number(process.env.WORDSTAT_BRIDGE_PORT || 8787);
9
+ const say = (m) => console.log(m);
10
+
11
+ const bridge = new ExtensionBridge({ port });
12
+ await bridge.start();
13
+ if (bridge.listenError) {
14
+ say(`✗ Порт ${port} занят другой программой: ${bridge.listenError.message}`);
15
+ say(" Закройте её или задайте другой порт: WORDSTAT_BRIDGE_PORT=8788 (и то же число в окне расширения).");
16
+ process.exit(1);
17
+ }
18
+ say(
19
+ bridge.mode === "peer"
20
+ ? `✓ Шаг 1. Порт ${port} уже занят сессией Claude — работаю через неё`
21
+ : `✓ Шаг 1. Сервер запущен на ws://127.0.0.1:${port}`
22
+ );
23
+ say(" Жду подключения расширения (до 40 секунд)… Браузер с расширением должен быть открыт.");
24
+
25
+ const t0 = Date.now();
26
+ while (!bridge.connected && Date.now() - t0 < 40000) await new Promise((r) => setTimeout(r, 250));
27
+ if (!bridge.connected) {
28
+ say("✗ Шаг 2. Расширение не подключилось.");
29
+ say(" Проверьте: chrome://extensions → «Wordstat Bridge» включено, нет красной кнопки «Ошибки».");
30
+ say(" Нажмите на значок расширения: порт там должен быть " + port + ".");
31
+ await bridge.stop();
32
+ process.exit(1);
33
+ }
34
+ say(`✓ Шаг 2. Расширение подключено (${((Date.now() - t0) / 1000).toFixed(1)} с)`);
35
+
36
+ say(` Шаг 3. Запрашиваю Вордстат: «${phrase}»…`);
37
+ try {
38
+ const [startDate, endDate] = lastFullMonth();
39
+ const resp = await bridge.call("getTable", { ...commonBody({ phrase }), startDate, endDate });
40
+ const top = parseTop(resp, null);
41
+ if (top.total == null && !top.popular.length) {
42
+ say("⚠ Шаг 3. Ответ пришёл, но в непривычном формате. Пришлите этот текст разработчику:");
43
+ say(JSON.stringify(resp).slice(0, 3000));
44
+ } else {
45
+ say(`✓ Шаг 3. Работает! Запросов за ${startDate}–${endDate}: ${top.total?.toLocaleString("ru-RU")}`);
46
+ for (const r of top.popular.slice(0, 5)) say(` • ${r.phrase} — ${r.count?.toLocaleString("ru-RU")}`);
47
+ say("\nВсё готово. Теперь можно спрашивать Claude.");
48
+ }
49
+ } catch (err) {
50
+ say(`✗ Шаг 3. ${err.message}${err.code ? ` [${err.code}]` : ""}`);
51
+ if (err.details?.preview || err.details?.payload) {
52
+ say(" Подробности для разработчика:");
53
+ say(String(err.details.preview ?? JSON.stringify(err.details.payload)).slice(0, 2000));
54
+ }
55
+ }
56
+ await bridge.stop();
57
+ process.exit(0);