Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
import { beforeEach, describe, expect, it, vi } from "vitest";
import { GscApiError, GscNotConnectedError } from "@/server/lib/gscErrors";
import * as searchConsoleTools from "./search-console-tools";
import { makeToolContext, textContent } from "./tool-test-support";
const mocks = vi.hoisted(() => ({
getProjectForOrganization: vi.fn(),
hasGoogleOAuthConfig: vi.fn(),
GscService: {
getPerformance: vi.fn(),
inspectUrls: vi.fn(),
},
}));
vi.mock("cloudflare:workers", () => ({ env: {} }));
vi.mock("@/server/features/google/oauth-config", () => ({
hasGoogleOAuthConfig: mocks.hasGoogleOAuthConfig,
}));
vi.mock("@/server/features/projects/services/ProjectService", () => ({
ProjectService: {
getProjectForOrganization: mocks.getProjectForOrganization,
},
}));
vi.mock("@/server/features/gsc/services/GscService", () => ({
GscService: mocks.GscService,
}));
const toolContext = makeToolContext();
const gscRow = (position: number, impressions = 100) => ({
keys: [`q${position}`],
clicks: 1,
impressions,
ctr: 0.041237113402061855,
position,
});
describe("search console MCP tools", () => {
beforeEach(() => {
mocks.getProjectForOrganization.mockResolvedValue({
id: "project_1",
locationCode: 2840,
languageCode: "en",
});
mocks.hasGoogleOAuthConfig.mockResolvedValue(true);
});
it("returns performance rows on success and passes filters through", async () => {
mocks.GscService.getPerformance.mockResolvedValue({
siteUrl: "https://example.com/",
connectedBy: "[email protected]",
request: {
dimensions: ["query"],
startDate: "2026-04-27",
endDate: "2026-05-25",
rowLimit: 1000,
},
rows: [
{
keys: ["seo tools"],
clicks: 12,
impressions: 300,
ctr: 0.04,
position: 7.5,
},
],
});
const { getSearchConsolePerformanceTool } = searchConsoleTools;
const result = await getSearchConsolePerformanceTool.handler(
{
projectId: "project_1",
dimensions: ["query"],
filters: [
{
dimension: "page",
operator: "equals",
expression: "https://example.com/x",
},
],
},
toolContext,
);
expect(mocks.GscService.getPerformance).toHaveBeenCalledWith(
expect.objectContaining({
projectId: "project_1",
filters: [
{
dimension: "page",
operator: "equals",
expression: "https://example.com/x",
},
],
}),
);
expect(result.structuredContent).toMatchObject({
ok: true,
siteUrl: "https://example.com/",
rowCount: 1,
});
const text = result.content?.[0];
expect(text?.type === "text" && text.text).toContain(
"key | clicks | impressions | CTR | position",
);
expect(text?.type === "text" && text.text).toContain("seo tools");
expect(text?.type === "text" && text.text).toContain("4.0%");
});
it("applies position/impression filters server-side over the full window and paginates in Google row space", async () => {
mocks.GscService.getPerformance.mockResolvedValue({
siteUrl: "https://example.com/",
connectedBy: "[email protected]",
request: {
dimensions: ["query"],
startDate: "2026-04-27",
endDate: "2026-05-25",
rowLimit: 1000,
startRow: 10,
},
rows: [
gscRow(2),
gscRow(7),
gscRow(12, 5),
gscRow(15),
gscRow(18),
gscRow(30),
],
});
const result =
await searchConsoleTools.getSearchConsolePerformanceTool.handler(
{
projectId: "project_1",
rowLimit: 2,
startRow: 10,
minPosition: 5,
maxPosition: 20,
minImpressions: 50,
},
toolContext,
);
expect(mocks.GscService.getPerformance).toHaveBeenCalledWith(
expect.objectContaining({ rowLimit: 1000, startRow: 10 }),
);
expect(mocks.GscService.getPerformance).toHaveBeenCalledWith(
expect.not.objectContaining({ minPosition: 5 }),
);
expect(result.structuredContent).toMatchObject({
rowCount: 2,
rows: [
{ keys: ["q7"], ctr: 0.0412, position: 7 },
{ keys: ["q15"], ctr: 0.0412, position: 15 },
],
hasMore: true,
// q15 was Google row index 3 of this window; next page starts after it.
nextStartRow: 14,
});
});
it("surfaces a not-connected message with a connect URL", async () => {
mocks.GscService.getPerformance.mockRejectedValue(
new GscNotConnectedError("project_1"),
);
const { getSearchConsolePerformanceTool } = searchConsoleTools;
const result = await getSearchConsolePerformanceTool.handler(
{ projectId: "project_1" },
toolContext,
);
expect(result.structuredContent).toMatchObject({
ok: false,
reason: "not_connected",
});
const first = result.content[0];
expect(first.type).toBe("text");
expect(first.type === "text" && first.text).toContain(
"/p/project_1/search-performance",
);
});
it("renders an api_error with a reconnect URL on a GSC API failure", async () => {
mocks.GscService.getPerformance.mockRejectedValue(
new GscApiError(403, "no access"),
);
const { getSearchConsolePerformanceTool } = searchConsoleTools;
const result = await getSearchConsolePerformanceTool.handler(
{ projectId: "project_1" },
toolContext,
);
expect(result.structuredContent).toMatchObject({
ok: false,
reason: "api_error",
});
const first = result.content[0];
expect(first.type === "text" && first.text).toContain(
"/p/project_1/search-performance",
);
});
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;
const result = await getSearchConsolePerformanceTool.handler(
{ projectId: "project_1", dimensions: ["query", "searchAppearance"] },
toolContext,
);
expect(result.structuredContent).toMatchObject({
reason: "invalid_request",
});
expect(mocks.GscService.getPerformance).not.toHaveBeenCalled();
});
it("rejects a half-specified explicit date range", async () => {
const { getSearchConsolePerformanceTool } = searchConsoleTools;
const result = await getSearchConsolePerformanceTool.handler(
{ projectId: "project_1", startDate: "2026-01-01" },
toolContext,
);
expect(result.structuredContent).toMatchObject({
reason: "invalid_request",
});
expect(mocks.GscService.getPerformance).not.toHaveBeenCalled();
});
it("returns a setup message in self-hosted mode without a Google client", async () => {
mocks.hasGoogleOAuthConfig.mockResolvedValue(false);
const { getSearchConsolePerformanceTool } = searchConsoleTools;
const result = await getSearchConsolePerformanceTool.handler(
{ projectId: "project_1" },
toolContext,
);
expect(result.structuredContent).toMatchObject({
reason: "gsc_oauth_not_configured",
});
expect(mocks.GscService.getPerformance).not.toHaveBeenCalled();
});
it("inspects multiple URLs and reports partial failures inline", async () => {
mocks.GscService.inspectUrls.mockResolvedValue({
siteUrl: "sc-domain:example.com",
connectedBy: "[email protected]",
results: [
{
url: "https://example.com/a",
result: {
indexStatusResult: {
verdict: "PASS",
coverageState: "Indexed",
robotsTxtState: "ALLOWED",
lastCrawlTime: "2026-08-21T04:12:39Z",
googleCanonical: "https://example.com/a",
userCanonical: "https://example.com/a?utm_source=x",
crawledAs: "MOBILE",
referringUrls: ["https://example.com/"],
},
mobileUsabilityResult: { verdict: "PASS" },
richResultsResult: { verdict: "PASS" },
},
},
{
url: "https://example.com/bad",
result: null,
error: "Search Console API error (400)",
},
],
});
const { inspectUrlsTool } = searchConsoleTools;
const result = await inspectUrlsTool.handler(
{
projectId: "project_1",
urls: ["https://example.com/a", "https://example.com/bad"],
},
toolContext,
);
expect(mocks.GscService.inspectUrls).toHaveBeenCalledWith(
expect.objectContaining({
projectId: "project_1",
urls: ["https://example.com/a", "https://example.com/bad"],
}),
);
expect(result.structuredContent).toMatchObject({
ok: true,
siteUrl: "sc-domain:example.com",
});
// Text-only clients see nothing but this block, so every inspection field
// Google returned has to land in it — including the canonical mismatch.
const text = textContent(result);
expect(text).toContain("PASS");
expect(text).toContain("robots.txt: ALLOWED");
expect(text).toContain("last crawl: 2026-08-21T04:12:39Z");
expect(text).toContain("crawled as: MOBILE");
expect(text).toContain(
"canonical: MISMATCH — Google selected https://example.com/a, page declares https://example.com/a?utm_source=x",
);
expect(text).toContain("mobile usability: PASS · rich results: PASS");
expect(text).toContain("referring URLs: https://example.com/");
// Fields Google didn't return are dropped, not printed as empty labels.
expect(text).not.toContain("sitemaps:");
expect(text).toContain("error:");
});
it("surfaces a not-connected message from inspect_urls", async () => {
mocks.GscService.inspectUrls.mockRejectedValue(
new GscNotConnectedError("project_1"),
);
const { inspectUrlsTool } = searchConsoleTools;
const result = await inspectUrlsTool.handler(
{ projectId: "project_1", urls: ["https://example.com/a"] },
toolContext,
);
expect(result.structuredContent).toMatchObject({
ok: false,
reason: "not_connected",
});
});
it("returns a setup message for inspect_urls in self-hosted mode without a Google client", async () => {
mocks.hasGoogleOAuthConfig.mockResolvedValue(false);
const { inspectUrlsTool } = searchConsoleTools;
const result = await inspectUrlsTool.handler(
{ projectId: "project_1", urls: ["https://example.com/a"] },
toolContext,
);
expect(result.structuredContent).toMatchObject({
reason: "gsc_oauth_not_configured",
});
expect(mocks.GscService.inspectUrls).not.toHaveBeenCalled();
});
});