synabun 2026.4.27 → 2026.5.2-beta

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.
Files changed (45) hide show
  1. package/CHANGELOG.md +189 -9
  2. package/README.md +67 -7
  3. package/hooks/claude-code/post-plan.mjs +56 -3
  4. package/hooks/claude-code/session-start.mjs +28 -1
  5. package/hooks/claude-code/shared.mjs +13 -1
  6. package/hooks/claude-code/stop.mjs +23 -0
  7. package/mcp-server/src/index.ts +4 -0
  8. package/mcp-server/src/services/profiles.ts +113 -7
  9. package/mcp-server/src/tools/gsc/experience.ts +440 -0
  10. package/mcp-server/src/tools/gsc/helpers.ts +288 -0
  11. package/mcp-server/src/tools/gsc/indexing.ts +495 -0
  12. package/mcp-server/src/tools/gsc/inspect.ts +391 -0
  13. package/mcp-server/src/tools/gsc/navigate.ts +236 -0
  14. package/mcp-server/src/tools/gsc/performance.ts +352 -0
  15. package/mcp-server/src/tools/gsc/settings.ts +564 -0
  16. package/mcp-server/src/tools/gsc.ts +95 -0
  17. package/mcp-server/src/tools/loop.ts +62 -15
  18. package/mcp-server/src/tools/profile.ts +1 -0
  19. package/neural-interface/public/shared/cdx/cdx-icons.js +1 -0
  20. package/neural-interface/public/shared/cdx/cdx-panel.js +24 -5
  21. package/neural-interface/public/shared/cdx/cdx-tabs.js +42 -0
  22. package/neural-interface/public/shared/html-shell.js +35 -35
  23. package/neural-interface/public/shared/ocp/ocp-panel.js +255 -25
  24. package/neural-interface/public/shared/ocp/ocp-render.js +152 -3
  25. package/neural-interface/public/shared/ocp/ocp-styles.js +520 -31
  26. package/neural-interface/public/shared/ocp/ocp-tabs.js +786 -128
  27. package/neural-interface/public/shared/provider-icons.js +2 -0
  28. package/neural-interface/public/shared/storage.js +5 -0
  29. package/neural-interface/public/shared/styles.css +538 -141
  30. package/neural-interface/public/shared/ui-claude-panel.js +35 -17
  31. package/neural-interface/public/shared/ui-file-explorer.js +65 -41
  32. package/neural-interface/public/shared/ui-menubar.js +17 -3
  33. package/neural-interface/public/shared/ui-navbar.js +33 -9
  34. package/neural-interface/public/shared/ui-sessions.js +613 -23
  35. package/neural-interface/public/shared/ui-settings.js +1 -2
  36. package/neural-interface/public/shared/ui-sidepanel-tray.js +173 -22
  37. package/neural-interface/public/shared/ui-sync.js +11 -5
  38. package/neural-interface/public/shared/ui-tool-updates.js +35 -16
  39. package/neural-interface/public/shared/ui-tutorial-steps.js +3 -3
  40. package/neural-interface/public/shared/ui-update.js +17 -2
  41. package/neural-interface/server.js +791 -21
  42. package/neural-interface/templates/CLAUDE-template.md +19 -6
  43. package/neural-interface/templates/ruleset-versions.json +31 -0
  44. package/package.json +1 -1
  45. package/setup.js +96 -37
@@ -0,0 +1,564 @@
1
+ /**
2
+ * GSC Settings + meta tools.
3
+ * Tools: gsc_settings, gsc_crawl_stats, gsc_users, gsc_associations,
4
+ * gsc_disavow, gsc_shopping, gsc_extract_table, gsc_screenshot
5
+ */
6
+
7
+ import { z } from 'zod';
8
+ import * as ni from '../../services/neural-interface.js';
9
+ import { text } from '../response.js';
10
+ import { GSC_BASE, encodeProperty, currentProperty, ensureAuth, resolve, wait, pollFor, safeNavigate, TABLE_EXTRACTOR_SCRIPT, readMetricTileScript } from './helpers.js';
11
+
12
+ const tabId = z.string().optional();
13
+
14
+ async function loadAndExtract(
15
+ sessionId: string | undefined,
16
+ tabIdArg: string | undefined,
17
+ property: string | undefined,
18
+ path: string,
19
+ ) {
20
+ const r = await resolve(sessionId, tabIdArg);
21
+ if ('error' in r) return { err: r.error, r: null as never };
22
+ const prop = property || (await currentProperty(r));
23
+ if (!prop && !path.startsWith('http')) return { err: 'No active property.', r };
24
+ const url = path.startsWith('http')
25
+ ? `${path}${prop ? `?resource_id=${encodeProperty(prop)}` : ''}`
26
+ : `${GSC_BASE}${path}?resource_id=${encodeProperty(prop || '')}`;
27
+ const nav = await safeNavigate(r, url);
28
+ if (nav.error) return { err: `Navigation failed: ${nav.error}`, r };
29
+ const authErr = await ensureAuth(r);
30
+ if (authErr) return { err: authErr, r };
31
+ await pollFor(r, `(() => document.body.innerText.length > 200 ? true : null)()`, 20000, 500);
32
+ await wait(700);
33
+ return { err: null, r };
34
+ }
35
+
36
+ // ── gsc_settings ──────────────────────────────────────────────
37
+
38
+ export const gscSettingsSchema = {
39
+ action: z.enum(['get', 'set_address', 'change_address'] as const).optional().describe('Default get. set_address sets the Change-of-address target. change_address opens flow.'),
40
+ newProperty: z.string().optional().describe('Target property for change_address.'),
41
+ property: z.string().optional(),
42
+ sessionId: z.string().optional(),
43
+ tabId,
44
+ };
45
+
46
+ export const gscSettingsDescription =
47
+ 'Read or modify property settings — ownership/verification, users, address. action=get returns the settings page summary; action=set_address/change_address mutate.';
48
+
49
+ export async function handleGscSettings(args: { action?: string; newProperty?: string; property?: string; sessionId?: string; tabId?: string }) {
50
+ const action = args.action || 'get';
51
+ if (action === 'get') {
52
+ const { err, r } = await loadAndExtract(args.sessionId, args.tabId, args.property, '/settings');
53
+ if (err) return text(err);
54
+ const data = await ni.evaluate(
55
+ r.sessionId,
56
+ `(() => {
57
+ // Scope to [role="main"] / <main> so we don't leak the locale sidebar.
58
+ const main = document.querySelector('[role="main"], main');
59
+ const root = main || document.body;
60
+ const txt = (main ? main.innerText : document.body.innerText) || '';
61
+ const norm = (s) => (s || '').replace(/\\s+/g, ' ').trim();
62
+ const m = (re) => {
63
+ const match = txt.match(re);
64
+ if (!match) return null;
65
+ for (let i = 1; i < match.length; i++) if (match[i]) return match[i];
66
+ return null;
67
+ };
68
+ // Ownership: catch the canonical PT-BR sentence "Você é um proprietário verificado".
69
+ let ownership = null;
70
+ if (/Você é um proprietário verificado|You are a verified owner/i.test(txt)) ownership = 'verified-owner';
71
+ else if (/Você é um proprietário|You are a property owner/i.test(txt)) ownership = 'owner';
72
+ else if (/Você não é proprietário|not a verified owner/i.test(txt)) ownership = 'non-owner';
73
+ else ownership = m(/(?:Ownership|Verificação de propriedade)(?:[\\s\\S]{0,160})?(Verified|Unverified|Verificado|N[aã]o verificado)/i);
74
+ // Verification method — try labeled regex first, else derive from the
75
+ // visible verification section (PT-BR pages show no discrete label).
76
+ const headersList = Array.from(root.querySelectorAll('h2, h3, [role="heading"]'));
77
+ const verifSection = headersList.find(h =>
78
+ /Verification|Verifica[cç][aã]o de propriedade/i.test(h.textContent || ''));
79
+ const verifText = verifSection?.parentElement?.innerText?.split(/\\n+/)
80
+ .find(l => /verified|verificado|HTML|DNS|tag|domain|prefix/i.test(l)) || null;
81
+ const verificationMethod =
82
+ m(/(?:Verification method|M[ée]todo de verifica[cç][aã]o)\\s*[::]?\\s*([^\\n]+)/i)
83
+ || (verifText ? norm(verifText) : null);
84
+ // Users section: collect listed names from the "Users and permissions"
85
+ // / "Usuários e permissões" block.
86
+ const userNames = [];
87
+ const usersHeading = headersList.find(h => /Users\\s*and\\s*permissions|Usu[aá]rios\\s*e\\s*permiss[oõ]es/i.test(h.textContent || ''));
88
+ if (usersHeading) {
89
+ const sec = usersHeading.closest('section, [role="region"], div') || usersHeading.parentElement;
90
+ if (sec) {
91
+ const items = Array.from(sec.querySelectorAll('[role="listitem"], li, [class*="user" i] [class*="name" i]'));
92
+ items.forEach(i => { const t = norm(i.textContent); if (t && t.length < 120) userNames.push(t); });
93
+ }
94
+ }
95
+ return {
96
+ ownership,
97
+ verificationMethod,
98
+ users: userNames.length > 0 ? userNames : null,
99
+ fullText: txt.slice(0, 4000),
100
+ };
101
+ })()`,
102
+ r.tabId,
103
+ );
104
+ return text(JSON.stringify(data.result, null, 2));
105
+ }
106
+ if (action === 'change_address' || action === 'set_address') {
107
+ const { err, r } = await loadAndExtract(args.sessionId, args.tabId, args.property, '/settings/change-address');
108
+ if (err) return text(err);
109
+ if (action === 'set_address') {
110
+ if (!args.newProperty) return text('newProperty required for set_address.');
111
+ await ni.evaluate(
112
+ r.sessionId,
113
+ `(() => { const sel = document.querySelector('select, [role="combobox"]'); if (sel) sel.click(); })()`,
114
+ r.tabId,
115
+ );
116
+ await wait(700);
117
+ await ni.evaluate(
118
+ r.sessionId,
119
+ `(() => { const items = Array.from(document.querySelectorAll('[role="option"], option')); const t = items.find(i => i.textContent.includes(${JSON.stringify(args.newProperty)})); if (t) t.click(); })()`,
120
+ r.tabId,
121
+ );
122
+ await wait(500);
123
+ await ni.evaluate(
124
+ r.sessionId,
125
+ `(() => { const btns = Array.from(document.querySelectorAll('button, [role="button"]')); const sub = btns.find(b => /^(submit|enviar|validate|validar)$/i.test((b.textContent || '').trim())); if (sub) sub.click(); })()`,
126
+ r.tabId,
127
+ );
128
+ return text(`Change of address requested → ${args.newProperty}. Validate via browser_snapshot.`);
129
+ }
130
+ return text('Change-of-address page opened. Use browser_snapshot to view validation steps.');
131
+ }
132
+ return text(`Unknown action: ${action}`);
133
+ }
134
+
135
+ // ── gsc_crawl_stats ───────────────────────────────────────────
136
+
137
+ export const gscCrawlStatsSchema = {
138
+ property: z.string().optional(),
139
+ sessionId: z.string().optional(),
140
+ tabId,
141
+ };
142
+
143
+ export const gscCrawlStatsDescription =
144
+ 'Read Crawl Stats — totals (requests, download size, response time) and breakdowns by host status, response code, file type, Googlebot type.';
145
+
146
+ export async function handleGscCrawlStats(args: { property?: string; sessionId?: string; tabId?: string }) {
147
+ const { err, r } = await loadAndExtract(args.sessionId, args.tabId, args.property, '/settings/crawl-stats');
148
+ if (err) return text(err);
149
+ // Crawl Stats overview — read tiles first (locale-aware), then fall back
150
+ // to body-text regex with strict unit anchors so we don't catch stray digits.
151
+ const [tr, td, ar] = await Promise.all([
152
+ ni.evaluate(r.sessionId, readMetricTileScript('totalRequests'), r.tabId),
153
+ ni.evaluate(r.sessionId, readMetricTileScript('totalDownloadSize'), r.tabId),
154
+ ni.evaluate(r.sessionId, readMetricTileScript('avgResponseTime'), r.tabId),
155
+ ]);
156
+ let scalar = {
157
+ totalRequests: (tr.result as string | null) ?? null,
158
+ totalDownloadSize: (td.result as string | null) ?? null,
159
+ avgResponseTime: (ar.result as string | null) ?? null,
160
+ };
161
+ if (!scalar.totalRequests || !scalar.totalDownloadSize || !scalar.avgResponseTime) {
162
+ const fallback = await ni.evaluate(
163
+ r.sessionId,
164
+ `(() => {
165
+ const main = document.querySelector('[role="main"], main') || document.body;
166
+ const txt = main.innerText || '';
167
+ const m = (re) => {
168
+ const match = txt.match(re);
169
+ if (!match) return null;
170
+ for (let i = 1; i < match.length; i++) if (match[i]) return match[i];
171
+ return null;
172
+ };
173
+ return {
174
+ totalRequests: m(/(\\d[\\d.,KMG]*)\\s*(?:total\\s*)?(?:crawl\\s*requests?|solicita[cç][oõ]es(?:\\s*de\\s*rastreamento)?)/i),
175
+ // Require explicit unit (KB/MB/GB/byte/byte) to avoid stray "2".
176
+ totalDownloadSize: m(/(\\d[\\d.,]*\\s*(?:KB|MB|GB|TB|byte|bytes|kilobytes?|megabytes?))(?:\\s|$)/i),
177
+ avgResponseTime: m(/(\\d[\\d.,]*\\s*ms)/i),
178
+ };
179
+ })()`,
180
+ r.tabId,
181
+ );
182
+ const fb = (fallback.result as { totalRequests: string | null; totalDownloadSize: string | null; avgResponseTime: string | null } | null)
183
+ || { totalRequests: null, totalDownloadSize: null, avgResponseTime: null };
184
+ scalar = {
185
+ totalRequests: scalar.totalRequests ?? fb.totalRequests,
186
+ totalDownloadSize: scalar.totalDownloadSize ?? fb.totalDownloadSize,
187
+ avgResponseTime: scalar.avgResponseTime ?? fb.avgResponseTime,
188
+ };
189
+ }
190
+ // Sections — find each known heading and extract the table beneath it.
191
+ const sections = await ni.evaluate(
192
+ r.sessionId,
193
+ `(() => {
194
+ const main = document.querySelector('[role="main"], main') || document.body;
195
+ const headings = Array.from(main.querySelectorAll('h2, h3, [role="heading"]'));
196
+ const sectionRe = /Por status do host|Por c[oó]digo de resposta|Por tipo de arquivo|Por tipo de Googlebot|By host status|By response code|By file type|By Googlebot type/i;
197
+ const out = [];
198
+ for (const h of headings) {
199
+ const heading = (h.textContent || '').trim();
200
+ if (!sectionRe.test(heading)) continue;
201
+ const sec = h.closest('section, [role="region"], div') || h.parentElement;
202
+ if (!sec) continue;
203
+ const rows = Array.from(sec.querySelectorAll('[role="row"], tr, [role="listitem"], li')).map(r => {
204
+ const cells = Array.from(r.querySelectorAll('[role="gridcell"], [role="cell"], td, span')).map(c => (c.textContent || '').trim().replace(/\\s+/g, ' '));
205
+ return cells.filter(Boolean);
206
+ }).filter(r => r.length > 0).slice(0, 20);
207
+ out.push({ heading, rows });
208
+ }
209
+ return out;
210
+ })()`,
211
+ r.tabId,
212
+ );
213
+ return text(JSON.stringify({ ...scalar, sections: sections.result || [] }, null, 2));
214
+ }
215
+
216
+ // ── gsc_users ─────────────────────────────────────────────────
217
+
218
+ export const gscUsersSchema = {
219
+ action: z.enum(['list', 'add', 'remove', 'change_role'] as const),
220
+ email: z.string().optional(),
221
+ role: z.enum(['owner', 'full', 'restricted'] as const).optional(),
222
+ property: z.string().optional(),
223
+ sessionId: z.string().optional(),
224
+ tabId,
225
+ };
226
+
227
+ export const gscUsersDescription =
228
+ 'Manage property users. list returns email + role. add invites a user (mutating). remove revokes (mutating). change_role updates permissions (mutating).';
229
+
230
+ export async function handleGscUsers(args: { action: string; email?: string; role?: string; property?: string; sessionId?: string; tabId?: string }) {
231
+ const { err, r } = await loadAndExtract(args.sessionId, args.tabId, args.property, '/users');
232
+ if (err) return text(err);
233
+
234
+ if (args.action === 'list') {
235
+ // Users page renders mat-list cards; the shared TABLE_EXTRACTOR list-mode
236
+ // fallback handles those, but we also do a structured pass for {name,email,role}
237
+ // to give callers a useful object shape.
238
+ const structured = await ni.evaluate(
239
+ r.sessionId,
240
+ `(() => {
241
+ const items = Array.from(document.querySelectorAll('[role="listitem"], mat-list-item, li, [role="row"], tr'));
242
+ const out = [];
243
+ for (const li of items) {
244
+ // Skip the column-header row (rendered as [role="row"] but with
245
+ // [role="columnheader"] children).
246
+ if (li.querySelector('[role="columnheader"]')) continue;
247
+ const txt = (li.innerText || li.textContent || '').replace(/\\s+/g, ' ').trim();
248
+ if (!txt || txt.length > 300) continue;
249
+ // Skip header-text echoes (PT-BR / EN).
250
+ if (/^\\s*(Name|Nome)\\s+(Email|E-?mail)\\s+(Permission|Permiss[aã]o|Role|Fun[cç][aã]o)\\s*$/i.test(txt)) continue;
251
+ const emailMatch = txt.match(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}/);
252
+ const roleMatch = txt.match(/(Owner|Propriet[aá]rio|Full|Total|Restricted|Restrito)/i);
253
+ // A real user row must contain at least an email or a role keyword.
254
+ if (!emailMatch && !roleMatch) continue;
255
+ out.push({
256
+ text: txt,
257
+ email: emailMatch ? emailMatch[0] : null,
258
+ role: roleMatch ? roleMatch[0] : null,
259
+ });
260
+ }
261
+ return out.filter(o => o.text.length > 0);
262
+ })()`,
263
+ r.tabId,
264
+ );
265
+ const tableRes = await ni.evaluate(r.sessionId, TABLE_EXTRACTOR_SCRIPT('[role="grid"], [role="table"], table, [role="list"]'), r.tabId);
266
+ return text(JSON.stringify({ users: structured.result || [], raw: tableRes.result || null }, null, 2));
267
+ }
268
+
269
+ if (args.action === 'add') {
270
+ if (!args.email) return text('email required for add.');
271
+ await ni.evaluate(
272
+ r.sessionId,
273
+ `(() => { const btns = Array.from(document.querySelectorAll('button, [role="button"]')); const a = btns.find(b => /add\\s*user|adicionar\\s*usuário/i.test(b.textContent || '')); if (a) a.click(); })()`,
274
+ r.tabId,
275
+ );
276
+ await wait(900);
277
+ await ni.evaluate(
278
+ r.sessionId,
279
+ `(() => { const i = document.querySelector('input[type="email"], input[type="text"]'); if (i) { i.focus(); i.value = ${JSON.stringify(args.email)}; i.dispatchEvent(new Event('input', { bubbles: true })); } })()`,
280
+ r.tabId,
281
+ );
282
+ if (args.role) {
283
+ await wait(300);
284
+ const roleRe = args.role === 'owner' ? /owner|proprietário/i : args.role === 'full' ? /full|total/i : /restricted|restrito/i;
285
+ await ni.evaluate(
286
+ r.sessionId,
287
+ `(() => { const sel = document.querySelector('select, [role="combobox"]'); if (sel) sel.click(); })()`,
288
+ r.tabId,
289
+ );
290
+ await wait(500);
291
+ await ni.evaluate(
292
+ r.sessionId,
293
+ `(() => { const items = Array.from(document.querySelectorAll('[role="option"], option')); const t = items.find(i => ${roleRe.toString()}.test(i.textContent || '')); if (t) t.click(); })()`,
294
+ r.tabId,
295
+ );
296
+ }
297
+ await ni.evaluate(
298
+ r.sessionId,
299
+ `(() => { const btns = Array.from(document.querySelectorAll('button, [role="button"]')); const add = btns.find(b => /^(add|adicionar)$/i.test((b.textContent || '').trim())); if (add) add.click(); })()`,
300
+ r.tabId,
301
+ );
302
+ return text(`Add user requested: ${args.email}${args.role ? ` (${args.role})` : ''}.`);
303
+ }
304
+
305
+ if (args.action === 'remove' || args.action === 'change_role') {
306
+ if (!args.email) return text('email required.');
307
+ const click = await ni.evaluate(
308
+ r.sessionId,
309
+ `(() => {
310
+ const rows = Array.from(document.querySelectorAll('[role="row"], tr'));
311
+ const row = rows.find(r => (r.textContent || '').includes(${JSON.stringify(args.email)}));
312
+ if (!row) return false;
313
+ const more = row.querySelector('[aria-label*="more" i], button[aria-haspopup]');
314
+ if (more) more.click();
315
+ return true;
316
+ })()`,
317
+ r.tabId,
318
+ );
319
+ if (!click.result) return text(`User not found: ${args.email}`);
320
+ await wait(500);
321
+ if (args.action === 'remove') {
322
+ await ni.evaluate(
323
+ r.sessionId,
324
+ `(() => { const items = Array.from(document.querySelectorAll('[role="menuitem"], button')); const d = items.find(i => /remove|excluir|remover/i.test(i.textContent || '')); if (d) d.click(); })()`,
325
+ r.tabId,
326
+ );
327
+ await wait(700);
328
+ await ni.evaluate(
329
+ r.sessionId,
330
+ `(() => { const btns = Array.from(document.querySelectorAll('button, [role="button"]')); const conf = btns.find(b => /^(remove|excluir|remover)$/i.test((b.textContent || '').trim())); if (conf) conf.click(); })()`,
331
+ r.tabId,
332
+ );
333
+ return text(`Remove user requested: ${args.email}.`);
334
+ }
335
+ if (!args.role) return text('role required for change_role.');
336
+ const roleRe = args.role === 'owner' ? /owner|proprietário/i : args.role === 'full' ? /full|total/i : /restricted|restrito/i;
337
+ await ni.evaluate(
338
+ r.sessionId,
339
+ `(() => { const items = Array.from(document.querySelectorAll('[role="menuitem"], button')); const c = items.find(i => /change\\s*role|alterar\\s*função/i.test(i.textContent || '')); if (c) c.click(); })()`,
340
+ r.tabId,
341
+ );
342
+ await wait(700);
343
+ await ni.evaluate(
344
+ r.sessionId,
345
+ `(() => { const items = Array.from(document.querySelectorAll('[role="option"], option, [role="menuitem"]')); const t = items.find(i => ${roleRe.toString()}.test(i.textContent || '')); if (t) t.click(); })()`,
346
+ r.tabId,
347
+ );
348
+ return text(`Change role requested for ${args.email} → ${args.role}.`);
349
+ }
350
+
351
+ return text(`Unknown action: ${args.action}`);
352
+ }
353
+
354
+ // ── gsc_associations ──────────────────────────────────────────
355
+
356
+ export const gscAssociationsSchema = {
357
+ action: z.enum(['list', 'add', 'remove'] as const),
358
+ service: z.enum(['google_analytics', 'merchant_center', 'google_ads', 'play_store', 'youtube', 'actions_on_google', 'chrome_web_store'] as const).optional(),
359
+ identifier: z.string().optional().describe('Service-specific ID (e.g. GA4 measurement ID, Merchant Center account ID).'),
360
+ property: z.string().optional(),
361
+ sessionId: z.string().optional(),
362
+ tabId,
363
+ };
364
+
365
+ export const gscAssociationsDescription =
366
+ 'Manage Associations (Analytics / Merchant / Ads / Play / YouTube / Actions / Chrome Web Store). list returns existing associations; add/remove mutate.';
367
+
368
+ export async function handleGscAssociations(args: { action: string; service?: string; identifier?: string; property?: string; sessionId?: string; tabId?: string }) {
369
+ const { err, r } = await loadAndExtract(args.sessionId, args.tabId, args.property, '/settings/associations');
370
+ if (err) return text(err);
371
+ if (args.action === 'list') {
372
+ const data = await ni.evaluate(
373
+ r.sessionId,
374
+ `(() => {
375
+ const norm = (s) => (s || '').replace(/\\s+/g, ' ').trim();
376
+ // The Associations page has up to two tables: active associations and
377
+ // pending requests. Use heading text to discriminate.
378
+ const headings = Array.from(document.querySelectorAll('h2, h3, [role="heading"]'));
379
+ const findSection = (re) => {
380
+ const h = headings.find(x => re.test(norm(x.textContent)));
381
+ return h ? (h.closest('section, [role="region"], div') || h.parentElement) : null;
382
+ };
383
+ const activeSec = findSection(/Active|Ativ[ao]s|Associated|Associa[cç][oõ]es associadas/i);
384
+ const pendingSec = findSection(/Pending|Pendente/i);
385
+ const rowsIn = (sec) => {
386
+ if (!sec) return [];
387
+ const trs = Array.from(sec.querySelectorAll('[role="row"], tr, [role="listitem"], mat-list-item, li'));
388
+ return trs.map(tr => {
389
+ const cells = Array.from(tr.querySelectorAll('[role="gridcell"], [role="cell"], td, span'));
390
+ const text = norm(tr.innerText || tr.textContent || '');
391
+ // Skip header-only rows ("Service / Account / URL").
392
+ if (/^(Service|Servi[cç]o)\\s+(Account|Conta)/i.test(text)) return null;
393
+ return cells.length > 0
394
+ ? { service: norm(cells[0]?.textContent), account: norm(cells[1]?.textContent), text }
395
+ : { text };
396
+ }).filter(Boolean).filter(r => r.text && r.text.length > 0 && r.text.length < 300);
397
+ };
398
+ return {
399
+ active: rowsIn(activeSec),
400
+ pending: rowsIn(pendingSec),
401
+ };
402
+ })()`,
403
+ r.tabId,
404
+ );
405
+ return text(JSON.stringify(data.result, null, 2));
406
+ }
407
+ if (args.action === 'add') {
408
+ await ni.evaluate(
409
+ r.sessionId,
410
+ `(() => { const btns = Array.from(document.querySelectorAll('button, [role="button"]')); const a = btns.find(b => /associate|associar|connect|conectar/i.test(b.textContent || '')); if (a) a.click(); })()`,
411
+ r.tabId,
412
+ );
413
+ return text(`Association add flow opened (service=${args.service || 'unspecified'}). Service-specific verification requires user interaction.`);
414
+ }
415
+ if (args.action === 'remove') {
416
+ if (!args.identifier) return text('identifier required for remove.');
417
+ await ni.evaluate(
418
+ r.sessionId,
419
+ `(() => {
420
+ const rows = Array.from(document.querySelectorAll('[role="row"], tr, [role="listitem"], li'));
421
+ const row = rows.find(r => (r.textContent || '').includes(${JSON.stringify(args.identifier)}));
422
+ if (!row) return false;
423
+ const more = row.querySelector('[aria-label*="more" i], button[aria-haspopup], button');
424
+ if (more) more.click();
425
+ return true;
426
+ })()`,
427
+ r.tabId,
428
+ );
429
+ await wait(500);
430
+ await ni.evaluate(
431
+ r.sessionId,
432
+ `(() => { const items = Array.from(document.querySelectorAll('[role="menuitem"], button')); const d = items.find(i => /disassociate|disconnect|remover|desassociar/i.test(i.textContent || '')); if (d) d.click(); })()`,
433
+ r.tabId,
434
+ );
435
+ return text(`Remove association requested: ${args.identifier}.`);
436
+ }
437
+ return text(`Unknown action: ${args.action}`);
438
+ }
439
+
440
+ // ── gsc_disavow ───────────────────────────────────────────────
441
+
442
+ export const gscDisavowSchema = {
443
+ action: z.enum(['download', 'upload', 'delete'] as const),
444
+ filePath: z.string().optional().describe('Absolute path of disavow .txt file (action=upload).'),
445
+ property: z.string().optional(),
446
+ sessionId: z.string().optional(),
447
+ tabId,
448
+ };
449
+
450
+ export const gscDisavowDescription =
451
+ '[mutating for upload/delete — affects how Google trusts links to your site] Manage the Disavow Links file. download exports current; upload replaces (use sparingly).';
452
+
453
+ export async function handleGscDisavow(args: { action: string; filePath?: string; property?: string; sessionId?: string; tabId?: string }) {
454
+ const { err, r } = await loadAndExtract(args.sessionId, args.tabId, args.property, 'https://search.google.com/search-console/disavow-links');
455
+ if (err) return text(err);
456
+
457
+ if (args.action === 'download') {
458
+ await ni.evaluate(
459
+ r.sessionId,
460
+ `(() => { const btns = Array.from(document.querySelectorAll('button, [role="button"], a')); const d = btns.find(b => /download|baixar|export/i.test(b.textContent || '')); if (d) d.click(); })()`,
461
+ r.tabId,
462
+ );
463
+ return text('Disavow file download triggered. File saved to browser default download dir.');
464
+ }
465
+
466
+ if (args.action === 'upload') {
467
+ if (!args.filePath) return text('filePath required for upload.');
468
+ await ni.evaluate(
469
+ r.sessionId,
470
+ `(() => { const btns = Array.from(document.querySelectorAll('button, [role="button"]')); const r = btns.find(b => /replace|substituir|upload|carregar/i.test(b.textContent || '')); if (r) r.click(); })()`,
471
+ r.tabId,
472
+ );
473
+ await wait(800);
474
+ const up = await ni.upload(r.sessionId, 'input[type="file"]', [args.filePath], undefined, r.tabId);
475
+ if (up.error) return text(`Upload failed: ${up.error}`);
476
+ await wait(1000);
477
+ await ni.evaluate(
478
+ r.sessionId,
479
+ `(() => { const btns = Array.from(document.querySelectorAll('button, [role="button"]')); const sub = btns.find(b => /^(submit|enviar|done|concluir)$/i.test((b.textContent || '').trim())); if (sub) sub.click(); })()`,
480
+ r.tabId,
481
+ );
482
+ return text(`Disavow file uploaded: ${args.filePath}.`);
483
+ }
484
+
485
+ if (args.action === 'delete') {
486
+ await ni.evaluate(
487
+ r.sessionId,
488
+ `(() => { const btns = Array.from(document.querySelectorAll('button, [role="button"]')); const d = btns.find(b => /delete\\s*list|excluir\\s*lista|remove/i.test(b.textContent || '')); if (d) d.click(); })()`,
489
+ r.tabId,
490
+ );
491
+ await wait(700);
492
+ await ni.evaluate(
493
+ r.sessionId,
494
+ `(() => { const btns = Array.from(document.querySelectorAll('button, [role="button"]')); const conf = btns.find(b => /^(delete|excluir|remove)$/i.test((b.textContent || '').trim())); if (conf) conf.click(); })()`,
495
+ r.tabId,
496
+ );
497
+ return text('Disavow list deletion requested.');
498
+ }
499
+ return text(`Unknown action: ${args.action}`);
500
+ }
501
+
502
+ // ── gsc_shopping ──────────────────────────────────────────────
503
+
504
+ export const gscShoppingSchema = {
505
+ property: z.string().optional(),
506
+ sessionId: z.string().optional(),
507
+ tabId,
508
+ };
509
+
510
+ export const gscShoppingDescription =
511
+ 'Read Shopping/Merchant Listings report — counts and per-issue example URLs.';
512
+
513
+ export async function handleGscShopping(args: { property?: string; sessionId?: string; tabId?: string }) {
514
+ const { err, r } = await loadAndExtract(args.sessionId, args.tabId, args.property, '/r/merchant-listings');
515
+ if (err) return text(err);
516
+ const noData = await ni.evaluate(
517
+ r.sessionId,
518
+ `(() => /Nenhum dado|No data|No merchant listings|Sem listagens|This report isn't available|Este relat[oó]rio n[aã]o est[aá] dispon[ií]vel/i.test(document.body.innerText))()`,
519
+ r.tabId,
520
+ );
521
+ const tableRes = await ni.evaluate(r.sessionId, TABLE_EXTRACTOR_SCRIPT('[role="grid"], [role="table"], table'), r.tabId);
522
+ if (!tableRes.result && noData.result) {
523
+ return text(JSON.stringify({ headers: [], rows: [], status: 'no_data' }, null, 2));
524
+ }
525
+ return text(JSON.stringify(tableRes.result || { headers: [], rows: [], status: 'no_data' }, null, 2));
526
+ }
527
+
528
+ // ── gsc_extract_table ─────────────────────────────────────────
529
+
530
+ export const gscExtractTableSchema = {
531
+ selector: z.string().optional().describe('CSS scope selector (default: [role="grid"]).'),
532
+ sessionId: z.string().optional(),
533
+ tabId,
534
+ };
535
+
536
+ export const gscExtractTableDescription =
537
+ 'Generic GSC grid → JSON extractor. Useful when no specific gsc_*_report tool covers a panel.';
538
+
539
+ export async function handleGscExtractTable(args: { selector?: string; sessionId?: string; tabId?: string }) {
540
+ const r = await resolve(args.sessionId, args.tabId, false);
541
+ if ('error' in r) return text(r.error);
542
+ const sel = args.selector || '[role="grid"], [role="table"], table';
543
+ const res = await ni.evaluate(r.sessionId, TABLE_EXTRACTOR_SCRIPT(sel), r.tabId);
544
+ if (res.error) return text(`Extract failed: ${res.error}`);
545
+ return text(JSON.stringify(res.result, null, 2));
546
+ }
547
+
548
+ // ── gsc_screenshot ────────────────────────────────────────────
549
+
550
+ export const gscScreenshotSchema = {
551
+ sessionId: z.string().optional(),
552
+ tabId,
553
+ };
554
+
555
+ export const gscScreenshotDescription =
556
+ 'Capture a full-page screenshot of the active GSC tab. Saved via SynaBun image staging.';
557
+
558
+ export async function handleGscScreenshot(args: { sessionId?: string; tabId?: string }) {
559
+ const r = await resolve(args.sessionId, args.tabId, false);
560
+ if ('error' in r) return text(r.error);
561
+ const res = await ni.screenshot(r.sessionId, r.tabId);
562
+ if (res.error) return text(`Screenshot failed: ${res.error}`);
563
+ return text('Screenshot captured.');
564
+ }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Google Search Console MCP tool registration barrel.
3
+ * 100% browser-based — uses the user's authenticated Google session.
4
+ */
5
+
6
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
7
+
8
+ import {
9
+ gscNavigateSchema, gscNavigateDescription, handleGscNavigate,
10
+ gscPropertySchema, gscPropertyDescription, handleGscProperty,
11
+ } from './gsc/navigate.js';
12
+
13
+ import {
14
+ gscInspectUrlSchema, gscInspectUrlDescription, handleGscInspectUrl,
15
+ gscInspectTestLiveSchema, gscInspectTestLiveDescription, handleGscInspectTestLive,
16
+ gscInspectRequestIndexingSchema, gscInspectRequestIndexingDescription, handleGscInspectRequestIndexing,
17
+ gscInspectViewCrawledSchema, gscInspectViewCrawledDescription, handleGscInspectViewCrawled,
18
+ } from './gsc/inspect.js';
19
+
20
+ import {
21
+ gscPerformanceQuerySchema, gscPerformanceQueryDescription, handleGscPerformanceQuery,
22
+ gscPerformanceExportSchema, gscPerformanceExportDescription, handleGscPerformanceExport,
23
+ gscPerformanceChartScreenshotSchema, gscPerformanceChartScreenshotDescription, handleGscPerformanceChartScreenshot,
24
+ } from './gsc/performance.js';
25
+
26
+ import {
27
+ gscPagesReportSchema, gscPagesReportDescription, handleGscPagesReport,
28
+ gscPagesValidateFixSchema, gscPagesValidateFixDescription, handleGscPagesValidateFix,
29
+ gscVideosReportSchema, gscVideosReportDescription, handleGscVideosReport,
30
+ gscSitemapSchema, gscSitemapDescription, handleGscSitemap,
31
+ gscRemovalsSchema, gscRemovalsDescription, handleGscRemovals,
32
+ gscRemovalsCancelSchema, gscRemovalsCancelDescription, handleGscRemovalsCancel,
33
+ } from './gsc/indexing.js';
34
+
35
+ import {
36
+ gscCwvReportSchema, gscCwvReportDescription, handleGscCwvReport,
37
+ gscHttpsReportSchema, gscHttpsReportDescription, handleGscHttpsReport,
38
+ gscSecurityIssuesSchema, gscSecurityIssuesDescription, handleGscSecurityIssues,
39
+ gscManualActionsSchema, gscManualActionsDescription, handleGscManualActions,
40
+ gscEnhancementsSchema, gscEnhancementsDescription, handleGscEnhancements,
41
+ gscLinksReportSchema, gscLinksReportDescription, handleGscLinksReport,
42
+ gscLinksExportSchema, gscLinksExportDescription, handleGscLinksExport,
43
+ } from './gsc/experience.js';
44
+
45
+ import {
46
+ gscSettingsSchema, gscSettingsDescription, handleGscSettings,
47
+ gscCrawlStatsSchema, gscCrawlStatsDescription, handleGscCrawlStats,
48
+ gscUsersSchema, gscUsersDescription, handleGscUsers,
49
+ gscAssociationsSchema, gscAssociationsDescription, handleGscAssociations,
50
+ gscDisavowSchema, gscDisavowDescription, handleGscDisavow,
51
+ gscShoppingSchema, gscShoppingDescription, handleGscShopping,
52
+ gscExtractTableSchema, gscExtractTableDescription, handleGscExtractTable,
53
+ gscScreenshotSchema, gscScreenshotDescription, handleGscScreenshot,
54
+ } from './gsc/settings.js';
55
+
56
+ export function registerGscTools(server: McpServer) {
57
+ return [
58
+ // Navigation + property
59
+ server.tool('gsc_navigate', gscNavigateDescription, gscNavigateSchema, handleGscNavigate),
60
+ server.tool('gsc_property', gscPropertyDescription, gscPropertySchema, handleGscProperty),
61
+ // URL inspection
62
+ server.tool('gsc_inspect_url', gscInspectUrlDescription, gscInspectUrlSchema, handleGscInspectUrl),
63
+ server.tool('gsc_inspect_test_live', gscInspectTestLiveDescription, gscInspectTestLiveSchema, handleGscInspectTestLive),
64
+ server.tool('gsc_inspect_request_indexing', gscInspectRequestIndexingDescription, gscInspectRequestIndexingSchema, handleGscInspectRequestIndexing),
65
+ server.tool('gsc_inspect_view_crawled', gscInspectViewCrawledDescription, gscInspectViewCrawledSchema, handleGscInspectViewCrawled),
66
+ // Performance
67
+ server.tool('gsc_performance_query', gscPerformanceQueryDescription, gscPerformanceQuerySchema, handleGscPerformanceQuery),
68
+ server.tool('gsc_performance_export', gscPerformanceExportDescription, gscPerformanceExportSchema, handleGscPerformanceExport),
69
+ server.tool('gsc_performance_chart_screenshot', gscPerformanceChartScreenshotDescription, gscPerformanceChartScreenshotSchema, handleGscPerformanceChartScreenshot),
70
+ // Indexing
71
+ server.tool('gsc_pages_report', gscPagesReportDescription, gscPagesReportSchema, handleGscPagesReport),
72
+ server.tool('gsc_pages_validate_fix', gscPagesValidateFixDescription, gscPagesValidateFixSchema, handleGscPagesValidateFix),
73
+ server.tool('gsc_videos_report', gscVideosReportDescription, gscVideosReportSchema, handleGscVideosReport),
74
+ server.tool('gsc_sitemap', gscSitemapDescription, gscSitemapSchema, handleGscSitemap),
75
+ server.tool('gsc_removals', gscRemovalsDescription, gscRemovalsSchema, handleGscRemovals),
76
+ server.tool('gsc_removals_cancel', gscRemovalsCancelDescription, gscRemovalsCancelSchema, handleGscRemovalsCancel),
77
+ // Experience + enhancements + links
78
+ server.tool('gsc_cwv_report', gscCwvReportDescription, gscCwvReportSchema, handleGscCwvReport),
79
+ server.tool('gsc_https_report', gscHttpsReportDescription, gscHttpsReportSchema, handleGscHttpsReport),
80
+ server.tool('gsc_security_issues', gscSecurityIssuesDescription, gscSecurityIssuesSchema, handleGscSecurityIssues),
81
+ server.tool('gsc_manual_actions', gscManualActionsDescription, gscManualActionsSchema, handleGscManualActions),
82
+ server.tool('gsc_enhancements', gscEnhancementsDescription, gscEnhancementsSchema, handleGscEnhancements),
83
+ server.tool('gsc_links_report', gscLinksReportDescription, gscLinksReportSchema, handleGscLinksReport),
84
+ server.tool('gsc_links_export', gscLinksExportDescription, gscLinksExportSchema, handleGscLinksExport),
85
+ // Settings + meta
86
+ server.tool('gsc_settings', gscSettingsDescription, gscSettingsSchema, handleGscSettings),
87
+ server.tool('gsc_crawl_stats', gscCrawlStatsDescription, gscCrawlStatsSchema, handleGscCrawlStats),
88
+ server.tool('gsc_users', gscUsersDescription, gscUsersSchema, handleGscUsers),
89
+ server.tool('gsc_associations', gscAssociationsDescription, gscAssociationsSchema, handleGscAssociations),
90
+ server.tool('gsc_disavow', gscDisavowDescription, gscDisavowSchema, handleGscDisavow),
91
+ server.tool('gsc_shopping', gscShoppingDescription, gscShoppingSchema, handleGscShopping),
92
+ server.tool('gsc_extract_table', gscExtractTableDescription, gscExtractTableSchema, handleGscExtractTable),
93
+ server.tool('gsc_screenshot', gscScreenshotDescription, gscScreenshotSchema, handleGscScreenshot),
94
+ ];
95
+ }