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.
@@ -0,0 +1,113 @@
1
+ import { OAuthError, registerGoogleAuth, TokenProvider, unconfiguredPrefix, USERINFO_URL, } from "@a1-x-tech/mcp-google-auth";
2
+ import { probeApi } from "../client.js";
3
+ import { GoogleSearchConsoleError } from "../types.js";
4
+ /**
5
+ * The scopes an in-chat login requests (the per-task table lives in
6
+ * docs/TOOLS.md). The component always adds the identity scopes on top. The read-write `webmasters` scope is requested because the tool surface includes sitemap submission; `webmasters.readonly` would fail there.
7
+ */
8
+ export const LOGIN_SCOPES = [
9
+ "https://www.googleapis.com/auth/webmasters",
10
+ ];
11
+ /**
12
+ * True when a Google API error body says the API itself is switched off in the
13
+ * caller's Cloud project. Google reports this two ways at once and has been
14
+ * migrating between them: the legacy `error.errors[].reason` is
15
+ * `accessNotConfigured`, the newer `error.details[].reason` is
16
+ * `SERVICE_DISABLED`. Either spelling means the same fix, so both are matched.
17
+ */
18
+ function isApiDisabled(body) {
19
+ if (typeof body !== "object" || body === null)
20
+ return false;
21
+ const error = body.error;
22
+ if (typeof error !== "object" || error === null)
23
+ return false;
24
+ const reasons = new Set();
25
+ for (const key of ["errors", "details"]) {
26
+ const list = error[key];
27
+ if (Array.isArray(list)) {
28
+ for (const entry of list) {
29
+ if (typeof entry === "object" && entry !== null) {
30
+ reasons.add(entry.reason);
31
+ }
32
+ }
33
+ }
34
+ }
35
+ return reasons.has("accessNotConfigured") || reasons.has("SERVICE_DISABLED");
36
+ }
37
+ /**
38
+ * `verifyIdentity` for the component: one cheap Google Search Console read, plus the
39
+ * translation the component cannot do itself. An API that is not enabled in the
40
+ * user's Cloud project answers the first call with HTTP 403 — the most likely
41
+ * failure right after a login — as a bare error reading "PERMISSION_DENIED",
42
+ * which sends the user to check permissions they cannot fix. Re-thrown as
43
+ * `OAuthError("accessNotConfigured")` it becomes the real advice: enable the
44
+ * API in the SAME project as the OAuth client.
45
+ *
46
+ * Checking the product API (rather than the component's default OIDC userinfo)
47
+ * is the point: OIDC answers even when Google Search Console API is switched off, so a
48
+ * login would look successful and the first real tool call would fail instead.
49
+ */
50
+ async function verifyIdentity(accessToken) {
51
+ try {
52
+ await probeApi(accessToken);
53
+ }
54
+ catch (error) {
55
+ if (error instanceof GoogleSearchConsoleError && error.status === 403 && isApiDisabled(error.body)) {
56
+ throw new OAuthError("accessNotConfigured", "Google Search Console API", error.status);
57
+ }
58
+ throw error;
59
+ }
60
+ return { email: await accountEmail(accessToken) };
61
+ }
62
+ /**
63
+ * The account label shown after a login. Best-effort on purpose: the connection
64
+ * is already proven by the probe above, and failing the whole login over a
65
+ * cosmetic label would be wrong.
66
+ */
67
+ async function accountEmail(accessToken) {
68
+ try {
69
+ const res = await fetch(USERINFO_URL, {
70
+ headers: { Authorization: `Bearer ${accessToken}` },
71
+ signal: AbortSignal.timeout(10_000),
72
+ });
73
+ if (!res.ok)
74
+ return undefined;
75
+ const data = await res.json();
76
+ const email = data.email;
77
+ return typeof email === "string" ? email : undefined;
78
+ }
79
+ catch {
80
+ return undefined;
81
+ }
82
+ }
83
+ /**
84
+ * The single source of the auth wiring: serverName "search-console" puts the stored
85
+ * login in ~/.config/mcp-google-search-console/credentials.json (the component
86
+ * prefixes "mcp-google-"), envPrefix keeps the provider reading the exact
87
+ * GOOGLE_SEARCH_CONSOLE_* variables config.ts documents — which is what preserves the
88
+ * env-beats-stored priority for existing installs.
89
+ */
90
+ export const AUTH_OPTIONS = {
91
+ serverName: "search-console",
92
+ envPrefix: "GOOGLE_SEARCH_CONSOLE",
93
+ scopes: LOGIN_SCOPES,
94
+ verifyIdentity,
95
+ };
96
+ /**
97
+ * Registers the six onboarding tools (auth_status, setup_instructions,
98
+ * set_client, start_login, finish_login, logout) and returns the TokenProvider
99
+ * the client plugs in as its fallback token source — the same instance, so a
100
+ * login finished mid-session is visible to the very next API call without a
101
+ * restart.
102
+ */
103
+ export function registerAuthTools(server) {
104
+ return registerGoogleAuth(server, AUTH_OPTIONS);
105
+ }
106
+ /** True when any token exists — env variables or a stored in-chat login. */
107
+ export function hasAuthToken() {
108
+ return new TokenProvider(AUTH_OPTIONS).hasToken();
109
+ }
110
+ /** The "NOT CONNECTED" prefix for the initialize instructions (names both fixes). */
111
+ export function authUnconfiguredPrefix() {
112
+ return unconfiguredPrefix(AUTH_OPTIONS);
113
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-google-search-console",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "MCP server for the Google Search Console API — search analytics, sitemaps, URL inspection and site management. For Claude, Cursor, Codex and other AI clients.",
5
5
  "mcpName": "io.github.A1-x-Tech/mcp-google-search-console",
6
6
  "type": "module",
@@ -51,6 +51,7 @@
51
51
  "url": "https://github.com/A1-x-Tech/mcp-google-search-console/issues"
52
52
  },
53
53
  "dependencies": {
54
+ "@a1-x-tech/mcp-google-auth": "^0.1.0",
54
55
  "@modelcontextprotocol/sdk": "^1.29.0",
55
56
  "zod": "^3.25.0"
56
57
  },
@@ -1,4 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
+ import { mkdtempSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
2
5
  import test from "node:test";
3
6
  import { fileURLToPath } from "node:url";
4
7
 
@@ -11,22 +14,47 @@ import { registerSitemapTools } from "../dist/tools/sitemaps.js";
11
14
  import { registerAnalyticsTools } from "../dist/tools/analytics.js";
12
15
  import { registerInspectionTools } from "../dist/tools/inspection.js";
13
16
  import { registerRawTool } from "../dist/tools/raw.js";
17
+ import { registerAuthTools } from "../dist/tools/auth.js";
14
18
 
19
+ /**
20
+ * Sorted, because every assertion compares it against a sorted tool list. The
21
+ * six onboarding tools come from @a1-x-tech/mcp-google-auth, so this list is
22
+ * also the check that the component is wired into the published binary.
23
+ */
15
24
  const ALL_TOOLS = [
16
25
  "add_site",
26
+ "auth_status",
17
27
  "delete_site",
18
28
  "delete_sitemap",
29
+ "finish_login",
19
30
  "get_site",
20
31
  "get_sitemap",
21
32
  "get_top_queries",
22
33
  "inspect_url",
23
34
  "list_sitemaps",
24
35
  "list_sites",
36
+ "logout",
25
37
  "raw_request",
26
38
  "search_analytics",
39
+ "set_client",
40
+ "setup_instructions",
41
+ "start_login",
27
42
  "submit_sitemap",
28
43
  ];
29
44
 
45
+ /**
46
+ * A throwaway $XDG_CONFIG_HOME for the spawned server. The auth component
47
+ * re-reads $XDG_CONFIG_HOME/mcp-google-search-console/credentials.json per call, so
48
+ * without this a real login on the developer's machine would make the
49
+ * "unconfigured" case pass for the wrong reason.
50
+ */
51
+ function isolatedConfigDir(t) {
52
+ const dir = mkdtempSync(join(tmpdir(), "mcp-search-console-dist-smoke-"));
53
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
54
+ return dir;
55
+ }
56
+
57
+
30
58
  test("dist client rejects foreign-origin paths before sending the Bearer token", async () => {
31
59
  const original = globalThis.fetch;
32
60
  let called = false;
@@ -87,6 +115,7 @@ test("dist registers the expected tools", () => {
87
115
  };
88
116
  const client = {};
89
117
 
118
+ registerAuthTools(server, client);
90
119
  registerSiteTools(server, client);
91
120
  registerSitemapTools(server, client);
92
121
  registerAnalyticsTools(server, client);
@@ -96,13 +125,14 @@ test("dist registers the expected tools", () => {
96
125
  assert.deepEqual(names.sort(), ALL_TOOLS);
97
126
  });
98
127
 
99
- test("dist binary completes a real MCP handshake over stdio and lists every tool", async () => {
128
+ test("dist binary completes a real MCP handshake over stdio and lists every tool", async (t) => {
100
129
  const transport = new StdioClientTransport({
101
130
  command: process.execPath,
102
131
  args: [fileURLToPath(new URL("../dist/index.js", import.meta.url))],
103
132
  env: {
104
133
  ...process.env,
105
134
  GOOGLE_SEARCH_CONSOLE_ACCESS_TOKEN: "test-token",
135
+ XDG_CONFIG_HOME: isolatedConfigDir(t),
106
136
  ASKADS_TELEMETRY: "0", // keep the suite offline
107
137
  },
108
138
  stderr: "pipe",
@@ -114,6 +144,12 @@ test("dist binary completes a real MCP handshake over stdio and lists every tool
114
144
  assert.equal(server?.name, "mcp-google-search-console");
115
145
  assert.match(String(server?.version), /^\d+\.\d+\.\d+$/);
116
146
 
147
+ // The initialize result must carry the instructions block — the only prose
148
+ // the calling model reads before it picks a tool.
149
+ const instructions = client.getInstructions() ?? "";
150
+ assert.ok(instructions.length > 200, `initialize must carry instructions (got ${instructions.length} chars)`);
151
+ assert.match(instructions, /list_sites/);
152
+
117
153
  const { tools } = await client.listTools();
118
154
  assert.deepEqual(tools.map((t) => t.name).sort(), ALL_TOOLS);
119
155
 
@@ -127,3 +163,49 @@ test("dist binary completes a real MCP handshake over stdio and lists every tool
127
163
  await client.close();
128
164
  }
129
165
  });
166
+
167
+ /**
168
+ * The degraded-start contract: without any credentials the binary used to
169
+ * exit(1) before the handshake, leaving the client a dead server and no reason.
170
+ * It must now start, list every tool, open the instructions with the fix, and
171
+ * answer a tool call with the actionable error — offline: the CredentialsError
172
+ * fires before any fetch, so this test never touches the network.
173
+ */
174
+ test("dist binary starts without credentials: handshake, tool list, actionable call error", async (t) => {
175
+ const env = Object.fromEntries(
176
+ Object.entries(process.env).filter(
177
+ ([key, value]) => value !== undefined && !key.startsWith("GOOGLE_SEARCH_CONSOLE_"),
178
+ ),
179
+ );
180
+ env.ASKADS_TELEMETRY = "0"; // keep the suite offline
181
+ env.XDG_CONFIG_HOME = isolatedConfigDir(t); // ignore any real login on this machine
182
+ const transport = new StdioClientTransport({
183
+ command: process.execPath,
184
+ args: [fileURLToPath(new URL("../dist/index.js", import.meta.url))],
185
+ env,
186
+ stderr: "pipe",
187
+ });
188
+ const client = new Client({ name: "dist-smoke-unconfigured", version: "0.0.0" });
189
+ await client.connect(transport);
190
+ try {
191
+ // The model must read the fix before it picks a tool.
192
+ const instructions = client.getInstructions() ?? "";
193
+ assert.match(instructions, /NOT CONNECTED/);
194
+ assert.match(instructions, /start_login/);
195
+ assert.match(instructions, /GOOGLE_SEARCH_CONSOLE_CLIENT_ID/);
196
+ assert.match(instructions, /restart/);
197
+
198
+ const { tools } = await client.listTools();
199
+ assert.deepEqual(tools.map((t) => t.name).sort(), ALL_TOOLS);
200
+
201
+ // A tool call fails with the exact message instead of killing the server.
202
+ const result = await client.callTool({ name: "list_sites", arguments: {} });
203
+ assert.equal(result.isError, true);
204
+ const text = result.content.map((c) => c.text ?? "").join(" ");
205
+ assert.match(text, /not connected/i);
206
+ assert.match(text, /start_login/);
207
+ assert.match(text, /restart the server/);
208
+ } finally {
209
+ await client.close();
210
+ }
211
+ });