Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Stop showing a disabled Search Console API as an expired connection (#948)
Carter Smith138aca619e14
diff --git a/docs/SELF_HOSTING_GOOGLE_SEARCH_CONSOLE.md b/docs/SELF_HOSTING_GOOGLE_SEARCH_CONSOLE.mdindex a08f148b..2a739e95 100644--- a/docs/SELF_HOSTING_GOOGLE_SEARCH_CONSOLE.md+++ b/docs/SELF_HOSTING_GOOGLE_SEARCH_CONSOLE.md@@ -113,6 +113,10 @@ docker compose up -d --force-recreate open-seouser on the OAuth consent screen (while the app is in Testing mode). Add it under**OAuth consent screen → Test users**.+**"Search Console API isn't enabled"** — the API isn't enabled in the Google+Cloud project that owns your OAuth client. Enable it (step 1), wait a minute,+then click **Try again**.+**Connected, but no properties to pick** — the Google account you authorizeddoesn't have a verified property in Search Console. Verify the site in[Search Console](https://search.google.com/search-console) first, then reconnect.diff --git a/src/client/features/integrations/GooglePropertyPicker.tsx b/src/client/features/integrations/GooglePropertyPicker.tsxindex 084135ff..191d62d4 100644--- a/src/client/features/integrations/GooglePropertyPicker.tsx+++ b/src/client/features/integrations/GooglePropertyPicker.tsx@@ -30,6 +30,7 @@ export type GooglePickerAccount = {email: string | null;requiresReconnect: boolean;unavailable?: boolean;+ apiDisabled?: boolean;properties: Property[];};type SecondaryAction = {@@ -250,7 +251,9 @@ export function GooglePropertyPicker({) : account.unavailable ? (<div className="flex flex-wrap items-center justify-between gap-2 px-2 pb-2 text-sm"><span className="text-muted-foreground">- Couldn't load properties+ {account.apiDisabled+ ? "Search Console API isn't enabled"+ : "Couldn't load properties"}</span><Button variant="ghost" size="xs" onClick={onRetry}>Try againdiff --git a/src/server/features/gsc/services/GscService.test.ts b/src/server/features/gsc/services/GscService.test.tsindex 78dad596..b5d38711 100644--- a/src/server/features/gsc/services/GscService.test.ts+++ b/src/server/features/gsc/services/GscService.test.ts@@ -166,6 +166,7 @@ describe("GscService.listSitesForUserWithGrantStatus", () => {email: "[email protected]",requiresReconnect: false,propertiesUnavailable: false,+ apiDisabled: false,sites: [{ siteUrl: "https://x/", permissionLevel: "siteOwner" }],},{@@ -173,6 +174,7 @@ describe("GscService.listSitesForUserWithGrantStatus", () => {email: null,requiresReconnect: true,propertiesUnavailable: false,+ apiDisabled: false,sites: [],},],@@ -200,55 +202,67 @@ describe("GscService.listSitesForUserWithGrantStatus", () => {email: null,requiresReconnect: false,propertiesUnavailable: false,+ apiDisabled: false,sites: [{ siteUrl: "https://x/", permissionLevel: "siteOwner" }],},],});});- it("keeps non-auth GSC API errors reportable", async () => {- mocks.getUserInfoEmail.mockImplementation(- async ({ gscAccountId }: { gscAccountId?: string }) =>- `${gscAccountId}@example.com`,- );- const rateLimit = new GscApiError(429, "slow down");- mocks.listSites.mockImplementation(- async ({ gscAccountId }: { gscAccountId?: string }) => {- if (gscAccountId === "sub-b") throw rateLimit;- return [{ siteUrl: "https://x/", permissionLevel: "siteOwner" }];- },- );- const consoleError = vi- .spyOn(console, "error")- .mockImplementation(() => undefined);-- await expect(- GscService.listSitesForUserWithGrantStatus("u1"),- ).resolves.toEqual({- accounts: [- {- accountId: "sub-a",- email: "[email protected]",- requiresReconnect: false,- propertiesUnavailable: false,- sites: [{ siteUrl: "https://x/", permissionLevel: "siteOwner" }],- },- {- accountId: "sub-b",- email: null,- requiresReconnect: false,- propertiesUnavailable: true,- sites: [],+ it.each([+ ["a rate limit", new GscApiError(429, "slow down"), false],+ [+ "a 403 because the API is disabled",+ new GscApiError(403, "denied", "SERVICE_DISABLED"),+ true,+ ],+ ])(+ "keeps %s reportable instead of asking to reconnect",+ async (_label, failure, apiDisabled) => {+ mocks.getUserInfoEmail.mockImplementation(+ async ({ gscAccountId }: { gscAccountId?: string }) =>+ `${gscAccountId}@example.com`,+ );+ mocks.listSites.mockImplementation(+ async ({ gscAccountId }: { gscAccountId?: string }) => {+ if (gscAccountId === "sub-b") throw failure;+ return [{ siteUrl: "https://x/", permissionLevel: "siteOwner" }];},- ],- });- expect(consoleError).toHaveBeenCalledWith(- "Failed to list Search Console sites for account",- "sub-b",- rateLimit,- );- consoleError.mockRestore();- });+ );+ const consoleError = vi+ .spyOn(console, "error")+ .mockImplementation(() => undefined);++ await expect(+ GscService.listSitesForUserWithGrantStatus("u1"),+ ).resolves.toEqual({+ accounts: [+ {+ accountId: "sub-a",+ email: "[email protected]",+ requiresReconnect: false,+ propertiesUnavailable: false,+ apiDisabled: false,+ sites: [{ siteUrl: "https://x/", permissionLevel: "siteOwner" }],+ },+ {+ accountId: "sub-b",+ email: null,+ requiresReconnect: false,+ propertiesUnavailable: true,+ apiDisabled,+ sites: [],+ },+ ],+ });+ expect(consoleError).toHaveBeenCalledWith(+ "Failed to list Search Console sites for account",+ "sub-b",+ failure,+ );+ consoleError.mockRestore();+ },+ );});describe("GscService.getPerformance", () => {diff --git a/src/server/features/gsc/services/GscService.ts b/src/server/features/gsc/services/GscService.tsindex 32833c7c..9196f4a8 100644--- a/src/server/features/gsc/services/GscService.ts+++ b/src/server/features/gsc/services/GscService.ts@@ -42,6 +42,7 @@ type GscSiteListResult = {email: string | null;requiresReconnect: boolean;propertiesUnavailable: boolean;+ apiDisabled: boolean;sites: GscSite[];}>;};@@ -114,10 +115,15 @@ async function listSitesForUserWithGrantStatus(email,requiresReconnect: false,propertiesUnavailable: false,+ apiDisabled: false,sites,};} catch (error) {- if (!isExpectedGrantFailure(error)) {+ // A disabled API is a self-host setup fault, not a dead grant:+ // reconnecting can't fix it, so log it and show the setup message.+ const apiDisabled = error instanceof GscApiError && error.apiDisabled;+ const requiresReconnect = isExpectedGrantFailure(error) && !apiDisabled;+ if (!requiresReconnect) {console.error("Failed to list Search Console sites for account",grant.accountId,@@ -127,8 +133,9 @@ async function listSitesForUserWithGrantStatus(return {accountId: grant.accountId,email: null,- requiresReconnect: isExpectedGrantFailure(error),- propertiesUnavailable: !isExpectedGrantFailure(error),+ requiresReconnect,+ propertiesUnavailable: !requiresReconnect,+ apiDisabled,sites: [],};}diff --git a/src/server/lib/gscErrors.ts b/src/server/lib/gscErrors.tsindex 42a29a33..9132ca29 100644--- a/src/server/lib/gscErrors.ts+++ b/src/server/lib/gscErrors.ts@@ -1,3 +1,6 @@+export const GSC_API_DISABLED_MESSAGE =+ "The Search Console API isn't enabled in the Google Cloud project that owns this deployment's OAuth client. Enable it, then retry.";+export class GscApiError extends Error {constructor(public readonly status: number,@@ -7,6 +10,12 @@ export class GscApiError extends Error {super(message);this.name = "GscApiError";}++ /** Google's 403 when the API isn't enabled in the OAuth client's Cloud+ * project: a self-host setup fault, not a dead grant. */+ get apiDisabled(): boolean {+ return this.status === 403 && !!this.body?.includes("SERVICE_DISABLED");+ }}export class GscTokenError extends Error {diff --git a/src/server/mcp/tools/google-analytics-tools.test.ts b/src/server/mcp/tools/google-analytics-tools.test.tsindex 1e1af7d8..c0af6185 100644--- a/src/server/mcp/tools/google-analytics-tools.test.ts+++ b/src/server/mcp/tools/google-analytics-tools.test.ts@@ -2,6 +2,7 @@import { beforeEach, describe, expect, it, vi } from "vitest";import { makeGa4ReportResult } from "@/server/features/ga4/services/ga4-test-fixtures";import { Ga4ReportError } from "@/server/lib/ga4Errors";+import { GscApiError } from "@/server/lib/gscErrors";import * as tools from "./google-analytics-tools";import { makeToolContext, textContent } from "./tool-test-support";@@ -251,6 +252,22 @@ describe("Google Analytics MCP tools", () => {);});+ it("reports a disabled Search Console API instead of asking to reconnect", async () => {+ mocks.getOpportunities.mockRejectedValue(+ new GscApiError(403, "denied", "SERVICE_DISABLED"),+ );++ const result = await tools.getSearchOpportunitiesTool.handler(+ { projectId: "project_1", limit: 25 },+ toolContext,+ );++ expect(result.structuredContent).toMatchObject({+ status: "error",+ error: { code: "gsc_api_disabled" },+ });+ });+it("renders measurement-health issues and the stream inventory", async () => {mocks.getMeasurementHealth.mockResolvedValue({status: "ok",diff --git a/src/server/mcp/tools/google-analytics-tools.ts b/src/server/mcp/tools/google-analytics-tools.tsindex a16afe01..a9c63690 100644--- a/src/server/mcp/tools/google-analytics-tools.ts+++ b/src/server/mcp/tools/google-analytics-tools.ts@@ -5,6 +5,7 @@ import { Ga4MeasurementHealthService } from "@/server/features/ga4/services/Ga4Mimport { OVERVIEW_METRICS } from "@/server/features/ga4/services/Ga4ReportDefinitions";import { Ga4OrganicOverviewService } from "@/server/features/ga4/services/Ga4OrganicOverviewService";import {+ GSC_API_DISABLED_MESSAGE,GscApiError,GscNotConnectedError,GscTokenError,@@ -198,6 +199,9 @@ function errorResponse(} else if (error instanceof GscNotConnectedError) {code = "gsc_not_connected";message = "Search Console is not connected for this project.";+ } else if (error instanceof GscApiError && error.apiDisabled) {+ code = "gsc_api_disabled";+ message = GSC_API_DISABLED_MESSAGE;} else if (error instanceof GscTokenError ||(error instanceof GscApiError && [401, 403].includes(error.status))diff --git a/src/server/mcp/tools/search-console-tools.test.ts b/src/server/mcp/tools/search-console-tools.test.tsindex f6bcf4b6..d49c8cb2 100644--- a/src/server/mcp/tools/search-console-tools.test.ts+++ b/src/server/mcp/tools/search-console-tools.test.ts@@ -201,6 +201,22 @@ describe("search console MCP tools", () => {);});+ it("points to API setup instead of reconnect when the API is disabled", async () => {+ mocks.GscService.getPerformance.mockRejectedValue(+ new GscApiError(403, "denied", "SERVICE_DISABLED"),+ );+ const { getSearchConsolePerformanceTool } = searchConsoleTools;++ const result = await getSearchConsolePerformanceTool.handler(+ { projectId: "project_1" },+ toolContext,+ );++ const first = result.content[0];+ expect(first.type === "text" && first.text).toContain("isn't enabled");+ expect(first.type === "text" && first.text).not.toContain("reconnect");+ });+it("rejects searchAppearance combined with another dimension", async () => {const { getSearchConsolePerformanceTool } = searchConsoleTools;diff --git a/src/server/mcp/tools/search-console-tools.ts b/src/server/mcp/tools/search-console-tools.tsindex 58f41f83..4c106b1b 100644--- a/src/server/mcp/tools/search-console-tools.ts+++ b/src/server/mcp/tools/search-console-tools.ts@@ -24,6 +24,7 @@ import {type GscPerformanceInput,} from "@/server/features/gsc/searchAnalytics";import {+ GSC_API_DISABLED_MESSAGE,GscApiError,GscNotConnectedError,GscTokenError,@@ -97,7 +98,9 @@ function describeGscError(error: unknown): string {return "The Search Console connection has expired or was revoked. Reconnect it to continue.";}if (error instanceof GscApiError) {- return error.message;+ return error.apiDisabled+ ? `${GSC_API_DISABLED_MESSAGE} Setup docs: ${GSC_SELF_HOSTED_SETUP_DOCS_URL}`+ : error.message;}return error instanceof Error ? error.message : String(error);}@@ -374,8 +377,9 @@ export const getSearchConsolePerformanceTool = {});} catch (error) {const isNotConnected = error instanceof GscNotConnectedError;+ const apiDisabled = error instanceof GscApiError && error.apiDisabled;return mcpResponse({- text: `${describeGscError(error)}${isNotConnected ? ` Connect it here: ${connectUrl}` : ` (reconnect at ${connectUrl})`}`,+ text: `${describeGscError(error)}${isNotConnected ? ` Connect it here: ${connectUrl}` : apiDisabled ? "" : ` (reconnect at ${connectUrl})`}`,meta,structuredContent: {ok: false,@@ -555,8 +559,9 @@ export const inspectUrlsTool = {});} catch (error) {const isNotConnected = error instanceof GscNotConnectedError;+ const apiDisabled = error instanceof GscApiError && error.apiDisabled;return mcpResponse({- text: `${describeGscError(error)}${isNotConnected ? ` Connect it here: ${connectUrl}` : ` (reconnect at ${connectUrl})`}`,+ text: `${describeGscError(error)}${isNotConnected ? ` Connect it here: ${connectUrl}` : apiDisabled ? "" : ` (reconnect at ${connectUrl})`}`,meta,structuredContent: {ok: false,diff --git a/src/serverFunctions/gsc.ts b/src/serverFunctions/gsc.tsindex 8cbc35a4..21cbb090 100644--- a/src/serverFunctions/gsc.ts+++ b/src/serverFunctions/gsc.ts@@ -77,6 +77,7 @@ export const listGscSites = createServerFn({ method: "POST" })email: grant.email,requiresReconnect: grant.requiresReconnect,propertiesUnavailable: grant.propertiesUnavailable,+ apiDisabled: grant.apiDisabled,sites: grant.sites.map((site) => {const isSelected = connection?.gscAccountId? connection.gscAccountId === grant.accountId &&