@xevrion/gsc-mcp 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,128 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, copyFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { spawnSync } from "node:child_process";
5
+ export const PACKAGE = "@xevrion/gsc-mcp";
6
+ const NAME = "search-console";
7
+ function home() {
8
+ return process.env.GSC_MCP_HOME || homedir();
9
+ }
10
+ function appData() {
11
+ const h = home();
12
+ if (process.platform === "darwin")
13
+ return join(h, "Library", "Application Support");
14
+ if (process.platform === "win32")
15
+ return process.env.GSC_MCP_HOME ? join(h, "AppData", "Roaming") : process.env.APPDATA || join(h, "AppData", "Roaming");
16
+ return process.env.XDG_CONFIG_HOME && !process.env.GSC_MCP_HOME ? process.env.XDG_CONFIG_HOME : join(h, ".config");
17
+ }
18
+ /**
19
+ * GUI apps like Claude Desktop do not inherit the shell PATH, so a bare "npx"
20
+ * fails for nvm/volta/homebrew users. Point at the npx next to the running node.
21
+ */
22
+ export function npxCommand() {
23
+ const local = join(dirname(process.execPath), process.platform === "win32" ? "npx.cmd" : "npx");
24
+ return existsSync(local) ? local : "npx";
25
+ }
26
+ function serverEntry(env, absolute) {
27
+ return { command: absolute ? npxCommand() : "npx", args: ["-y", PACKAGE], ...(Object.keys(env).length ? { env } : {}) };
28
+ }
29
+ function readJson(path) {
30
+ if (!existsSync(path))
31
+ return {};
32
+ const raw = readFileSync(path, "utf8").trim();
33
+ if (!raw)
34
+ return {};
35
+ try {
36
+ return JSON.parse(raw);
37
+ }
38
+ catch {
39
+ throw new Error(`${path} is not valid JSON, so it was left untouched. Fix or remove it and run setup again.`);
40
+ }
41
+ }
42
+ function writeJson(path, data) {
43
+ mkdirSync(dirname(path), { recursive: true });
44
+ if (existsSync(path))
45
+ copyFileSync(path, `${path}.bak`);
46
+ writeFileSync(path, JSON.stringify(data, null, 2) + "\n");
47
+ }
48
+ function jsonTarget(id, label, path, opts = {}) {
49
+ const key = opts.key ?? "mcpServers";
50
+ return {
51
+ id,
52
+ label,
53
+ path,
54
+ detected: existsSync(opts.detectDir ?? dirname(path)),
55
+ install(env) {
56
+ const cfg = readJson(path);
57
+ cfg[key] ??= {};
58
+ const entry = serverEntry(env, opts.absolute ?? false);
59
+ cfg[key][NAME] = opts.vscode ? { type: "stdio", ...entry } : entry;
60
+ writeJson(path, cfg);
61
+ return path;
62
+ },
63
+ };
64
+ }
65
+ function hasCli(bin) {
66
+ const r = spawnSync(process.platform === "win32" ? "where" : "which", [bin], { stdio: "ignore" });
67
+ return r.status === 0;
68
+ }
69
+ export function targets() {
70
+ const h = home();
71
+ const ad = appData();
72
+ const list = [
73
+ {
74
+ id: "claude-code",
75
+ label: "Claude Code",
76
+ path: null,
77
+ detected: !process.env.GSC_MCP_HOME && hasCli("claude"),
78
+ install(env) {
79
+ spawnSync("claude", ["mcp", "remove", "--scope", "user", NAME], { stdio: "ignore" });
80
+ const envArgs = Object.entries(env).flatMap(([k, v]) => ["-e", `${k}=${v}`]);
81
+ const r = spawnSync("claude", ["mcp", "add", "--scope", "user", ...envArgs, NAME, "--", "npx", "-y", PACKAGE], { encoding: "utf8" });
82
+ if (r.status !== 0)
83
+ throw new Error((r.stderr || r.stdout || "claude mcp add failed").trim());
84
+ return "claude mcp add --scope user";
85
+ },
86
+ },
87
+ jsonTarget("claude-desktop", "Claude Desktop", join(ad, "Claude", "claude_desktop_config.json"), { absolute: true }),
88
+ jsonTarget("cursor", "Cursor", join(h, ".cursor", "mcp.json")),
89
+ jsonTarget("windsurf", "Windsurf", join(h, ".codeium", "windsurf", "mcp_config.json")),
90
+ jsonTarget("vscode", "VS Code", join(ad, "Code", "User", "mcp.json"), { key: "servers", vscode: true, absolute: true }),
91
+ jsonTarget("gemini", "Gemini CLI", join(h, ".gemini", "settings.json")),
92
+ {
93
+ id: "codex",
94
+ label: "Codex",
95
+ path: join(h, ".codex", "config.toml"),
96
+ detected: existsSync(join(h, ".codex")),
97
+ install(env) {
98
+ const path = join(h, ".codex", "config.toml");
99
+ const current = existsSync(path) ? readFileSync(path, "utf8") : "";
100
+ if (existsSync(path))
101
+ copyFileSync(path, `${path}.bak`);
102
+ const header = `[mcp_servers.${NAME}]`;
103
+ // Drop any previous block of ours (up to the next table header) before appending a fresh one.
104
+ const without = current.replace(new RegExp(`\\n?\\[mcp_servers\\.${NAME}(\\.env)?\\][\\s\\S]*?(?=\\n\\[(?!mcp_servers\\.${NAME}\\b)|$)`, "g"), "");
105
+ const block = [header, `command = "npx"`, `args = ["-y", "${PACKAGE}"]`, ...(Object.keys(env).length ? ["", `[mcp_servers.${NAME}.env]`, ...Object.entries(env).map(([k, v]) => `${k} = ${JSON.stringify(v)}`)] : [])].join("\n");
106
+ mkdirSync(dirname(path), { recursive: true });
107
+ writeFileSync(path, `${without.trimEnd()}${without.trim() ? "\n\n" : ""}${block}\n`);
108
+ return path;
109
+ },
110
+ },
111
+ ];
112
+ return list;
113
+ }
114
+ export function installInto(ids, env = {}) {
115
+ const all = targets();
116
+ const chosen = ids === "detected" ? all.filter((t) => t.detected) : all.filter((t) => ids.includes(t.id));
117
+ return chosen.map((t) => {
118
+ try {
119
+ return { label: t.label, ok: true, where: t.install(env) };
120
+ }
121
+ catch (e) {
122
+ return { label: t.label, ok: false, where: e.message };
123
+ }
124
+ });
125
+ }
126
+ export function manualConfig() {
127
+ return JSON.stringify({ mcpServers: { [NAME]: serverEntry({}, false) } }, null, 2);
128
+ }
@@ -0,0 +1,16 @@
1
+ import { z } from "zod";
2
+ const site = z.string().optional().describe("Site, e.g. example.com (optional if you have one property)");
3
+ function user(text) {
4
+ return { messages: [{ role: "user", content: { type: "text", text } }] };
5
+ }
6
+ export function registerPrompts(server) {
7
+ server.registerPrompt("seo_report", { title: "SEO report", description: "A plain-English report on how the site is doing and the 5 things to do next.", argsSchema: { site } }, ({ site }) => user(`Write an SEO report for ${site ?? "my site"} using Search Console. Call site_overview, then find_opportunities, find_low_ctr, find_content_decay and find_cannibalization. ` +
8
+ `Lead with a three-sentence summary of how the site is doing. Then list the 5 highest-impact actions, each naming the exact page or query, what to change, and the estimated extra clicks from the tool output. ` +
9
+ `Only use numbers that the tools returned. Keep it readable for someone who is not an SEO expert.`));
10
+ server.registerPrompt("why_traffic_dropped", { title: "Why did my traffic drop?", description: "Find when and why clicks fell, and what to do about it.", argsSchema: { site } }, ({ site }) => user(`My Google traffic${site ? ` for ${site}` : ""} dropped. Use diagnose_traffic_drop first, then compare_periods by query for the worst pages, and inspect_url on the top 5 losing pages. ` +
11
+ `Explain in plain English: when it happened, whether it lines up with a Google update, which pages and queries lost the most, and the likely cause for each. Finish with a prioritized fix list.`));
12
+ server.registerPrompt("quick_wins", { title: "Quick wins", description: "Keywords close to page one, and exactly what to change on each page.", argsSchema: { site, brand: z.string().optional().describe("Brand name to exclude") } }, ({ site, brand }) => user(`Find SEO quick wins for ${site ?? "my site"}. Call find_opportunities${brand ? ` with brand "${brand}"` : ""} and find_low_ctr. ` +
13
+ `Group the opportunities by page (use search_analytics filtered by query to find the ranking page when needed). For each page give: the target queries, a suggested new title tag under 60 characters, and 2-3 concrete content additions. Order by estimated extra clicks.`));
14
+ server.registerPrompt("indexing_check", { title: "Indexing check", description: "Find pages Google is not showing and why.", argsSchema: { site } }, ({ site }) => user(`Check indexing for ${site ?? "my site"}. Call list_sitemaps, then audit_indexing. Group the problems by cause (not indexed, canonical mismatch, blocked by robots, never crawled) and explain how to fix each group in plain English.`));
15
+ server.registerPrompt("content_refresh_plan", { title: "Content refresh plan", description: "Which old pages to update first and how.", argsSchema: { site } }, ({ site }) => user(`Make a content refresh plan for ${site ?? "my site"}. Call find_content_decay and find_cannibalization. For the top 10 decaying pages, pull their top queries with search_analytics (filter page equals the URL) and suggest what to update. Flag any page that should be merged into another instead.`));
16
+ }
package/dist/server.js ADDED
@@ -0,0 +1,26 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { readFileSync } from "node:fs";
3
+ import { LazyAuth, writesEnabled } from "./auth.js";
4
+ import { GscClient } from "./gsc.js";
5
+ import { registerTools } from "./tools.js";
6
+ import { registerPrompts } from "./prompts.js";
7
+ import { demoFetch, DEMO_AUTH, DEMO_SITE } from "./demo.js";
8
+ export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
9
+ export function isDemo() {
10
+ return /^(1|true|yes)$/i.test(process.env.GSC_DEMO ?? "");
11
+ }
12
+ export function createServer(client) {
13
+ const demo = isDemo();
14
+ if (demo)
15
+ process.env.GSC_DEFAULT_SITE ??= DEMO_SITE;
16
+ const auth = new LazyAuth();
17
+ const gsc = client ?? (demo ? new GscClient(DEMO_AUTH, demoFetch) : new GscClient(auth));
18
+ const server = new McpServer({ name: "gsc-mcp", version: VERSION }, {
19
+ instructions: "Google Search Console data for the user's own sites. Start with site_overview for 'how is my site doing', diagnose_traffic_drop for drops, and the find_* tools for recommendations. " +
20
+ "If a tool says Search Console is not connected, call connect_account. Only report numbers the tools return, and say which date range they cover. Position is an impression-weighted average. Finalized data lags about 3 days." +
21
+ (demo ? " DEMO MODE: all data is synthetic, for the fictional site sc-domain:brewguide.coffee." : ""),
22
+ });
23
+ registerTools(server, gsc, { writes: writesEnabled() && !demo, auth: client ? undefined : auth, demo });
24
+ registerPrompts(server);
25
+ return server;
26
+ }