Skip to content

Open source alternative to Semrush and Ahrefs

fix(mcp): trim tool output and add filtered Search Console results (#625)

Ben Senescubf1ad5bc5f43
diff --git a/.agents/skills/keyword-research/SKILL.md b/.agents/skills/keyword-research/SKILL.md
index b1d99b65..24923bd5 100644
--- a/.agents/skills/keyword-research/SKILL.md
+++ b/.agents/skills/keyword-research/SKILL.md
@@ -35,7 +35,7 @@ Deliver through the `seo-report` skill, saving with `skill: "keyword-research"`.
- `research_keywords`: primary discovery tool. Use 1-5 seeds per call and prefer 150 results unless the user asks for exhaustive research.
- `get_keyword_metrics`: hydrate up to 700 known keywords with volume, keyword difficulty (KD), search intent, CPC, and monthly trends in one call. Use it to score candidate or known terms — including the Search Console striking-distance queries from step 1.
- `get_ranked_keywords`: pull exact ranking keyword rows when a target domain or page is part of the research brief.
-- `get_search_console_performance`: when Search Console is connected, start from the project's real first-party demand — queries already earning impressions and near-ranking ("striking distance") terms. Request a high `rowLimit` and filter average position 5-20 client-side, since the API sorts by clicks and can't filter by position. Then hydrate those striking-distance queries with `get_keyword_metrics` to attach difficulty and intent.
+- `get_search_console_performance`: when Search Console is connected, start from the project's real first-party demand — queries already earning impressions and near-ranking ("striking distance") terms. Pass `minPosition: 5, maxPosition: 20, minImpressions: 50` so the server filters the striking-distance rows for you (Google sorts by clicks and can't filter by position itself). Then hydrate those striking-distance queries with `get_keyword_metrics` to attach difficulty and intent.
- `get_serp_results`: inspect SERPs for the top candidate terms, especially when intent is ambiguous.
- `search_local_businesses`, `get_local_serp_results`, and `get_google_business_questions`: use for local SEO topics when a business/location radius matters.
- `list_saved_keywords`: avoid duplicating already-saved work or use existing tags as context.
@@ -43,7 +43,7 @@ Deliver through the `seo-report` skill, saving with `skill: "keyword-research"`.
## Workflow
-1. Normalize seeds into a small set of distinct research angles. If Search Console is connected for the project, first pull `get_search_console_performance` (high `rowLimit`, default lookback), filter to striking-distance positions (~5–20) client-side, and hydrate those queries with `get_keyword_metrics` to attach KD and intent. That ranked, hydrated list is your fastest opportunity set — work it before broad discovery.
+1. Normalize seeds into a small set of distinct research angles. If Search Console is connected for the project, first pull `get_search_console_performance` with `minPosition: 5, maxPosition: 20, minImpressions: 50` (default lookback), and hydrate those queries with `get_keyword_metrics` to attach KD and intent. That ranked, hydrated list is your fastest opportunity set — work it before broad discovery.
2. If the request is local SEO, identify the business, location/coordinates or service area, and local categories. Use `search_local_businesses` and `get_local_serp_results` for the most important location/keyword set instead of relying only on national keyword/SERP data.
3. Call `research_keywords` for exploratory seeds. Use bulk calls when possible.
4. Use `get_keyword_metrics` to hydrate a fixed keyword list — or the striking-distance queries from step 1 — with volume, KD, and intent before prioritizing.
diff --git a/plugins/openseo/skills/keyword-research/SKILL.md b/plugins/openseo/skills/keyword-research/SKILL.md
index b1d99b65..24923bd5 100644
--- a/plugins/openseo/skills/keyword-research/SKILL.md
+++ b/plugins/openseo/skills/keyword-research/SKILL.md
@@ -35,7 +35,7 @@ Deliver through the `seo-report` skill, saving with `skill: "keyword-research"`.
- `research_keywords`: primary discovery tool. Use 1-5 seeds per call and prefer 150 results unless the user asks for exhaustive research.
- `get_keyword_metrics`: hydrate up to 700 known keywords with volume, keyword difficulty (KD), search intent, CPC, and monthly trends in one call. Use it to score candidate or known terms — including the Search Console striking-distance queries from step 1.
- `get_ranked_keywords`: pull exact ranking keyword rows when a target domain or page is part of the research brief.
-- `get_search_console_performance`: when Search Console is connected, start from the project's real first-party demand — queries already earning impressions and near-ranking ("striking distance") terms. Request a high `rowLimit` and filter average position 5-20 client-side, since the API sorts by clicks and can't filter by position. Then hydrate those striking-distance queries with `get_keyword_metrics` to attach difficulty and intent.
+- `get_search_console_performance`: when Search Console is connected, start from the project's real first-party demand — queries already earning impressions and near-ranking ("striking distance") terms. Pass `minPosition: 5, maxPosition: 20, minImpressions: 50` so the server filters the striking-distance rows for you (Google sorts by clicks and can't filter by position itself). Then hydrate those striking-distance queries with `get_keyword_metrics` to attach difficulty and intent.
- `get_serp_results`: inspect SERPs for the top candidate terms, especially when intent is ambiguous.
- `search_local_businesses`, `get_local_serp_results`, and `get_google_business_questions`: use for local SEO topics when a business/location radius matters.
- `list_saved_keywords`: avoid duplicating already-saved work or use existing tags as context.
@@ -43,7 +43,7 @@ Deliver through the `seo-report` skill, saving with `skill: "keyword-research"`.
## Workflow
-1. Normalize seeds into a small set of distinct research angles. If Search Console is connected for the project, first pull `get_search_console_performance` (high `rowLimit`, default lookback), filter to striking-distance positions (~5–20) client-side, and hydrate those queries with `get_keyword_metrics` to attach KD and intent. That ranked, hydrated list is your fastest opportunity set — work it before broad discovery.
+1. Normalize seeds into a small set of distinct research angles. If Search Console is connected for the project, first pull `get_search_console_performance` with `minPosition: 5, maxPosition: 20, minImpressions: 50` (default lookback), and hydrate those queries with `get_keyword_metrics` to attach KD and intent. That ranked, hydrated list is your fastest opportunity set — work it before broad discovery.
2. If the request is local SEO, identify the business, location/coordinates or service area, and local categories. Use `search_local_businesses` and `get_local_serp_results` for the most important location/keyword set instead of relying only on national keyword/SERP data.
3. Call `research_keywords` for exploratory seeds. Use bulk calls when possible.
4. Use `get_keyword_metrics` to hydrate a fixed keyword list — or the striking-distance queries from step 1 — with volume, KD, and intent before prioritizing.
diff --git a/src/server/features/gsc/searchAnalytics.test.ts b/src/server/features/gsc/searchAnalytics.test.ts
index e62cae6a..2785826f 100644
--- a/src/server/features/gsc/searchAnalytics.test.ts
+++ b/src/server/features/gsc/searchAnalytics.test.ts
@@ -107,7 +107,7 @@ describe("buildSearchAnalyticsRequest", () => {
expect(request.dimensions).toEqual(["query"]);
expect(request.type).toBe("web");
expect(request.dataState).toBe("all");
- expect(request.rowLimit).toBe(1000);
+ expect(request.rowLimit).toBe(250);
});
it("clamps rowLimit to the 1000 ceiling", () => {
diff --git a/src/server/features/gsc/searchAnalytics.ts b/src/server/features/gsc/searchAnalytics.ts
index 59cc8c7b..322e97bf 100644
--- a/src/server/features/gsc/searchAnalytics.ts
+++ b/src/server/features/gsc/searchAnalytics.ts
@@ -32,7 +32,9 @@ export const GSC_DATE_RANGES = [
"last_16_months",
] as const;
-export const GSC_DEFAULT_ROW_LIMIT = 1000;
+// 250 rows fits comfortably inside one MCP tool result; the agent opts into
+// more with `rowLimit` or paginates with `startRow`.
+export const GSC_DEFAULT_ROW_LIMIT = 250;
// v1 caps rows-per-call at 1000 to protect the MCP context window. The GSC API
// supports up to 25000, but we keep fetched == returned so counts stay honest;
// the agent paginates with `startRow` for more.
diff --git a/src/server/mcp/tools/list-saved-keywords.ts b/src/server/mcp/tools/list-saved-keywords.ts
index 44515e09..277f12da 100644
--- a/src/server/mcp/tools/list-saved-keywords.ts
+++ b/src/server/mcp/tools/list-saved-keywords.ts
@@ -2,12 +2,41 @@ import { z } from "zod";
import { KeywordResearchService } from "@/server/features/keywords/services/KeywordResearchService";
import { mcpResponse } from "@/server/mcp/formatters";
import { buildProjectMeta } from "@/server/mcp/context";
-import {
- looseObjectOutputSchema,
- optionalMetaOutputSchema,
-} from "@/server/mcp/output-schemas";
+import { optionalMetaOutputSchema } from "@/server/mcp/output-schemas";
import { withMcpProjectAuth } from "@/server/mcp/project-auth";
import { projectIdSchema } from "@/server/mcp/schemas";
+import type { SavedKeywordRow, SavedKeywordTagSummary } from "@/types/keywords";
+
+// The app reads the full SavedKeywordRow through its own server functions. The
+// MCP row keeps only what an agent acts on: ids, timestamps, tag colors, and the
+// monthly trend array were ~60% of the bytes and never used.
+const savedKeywordOutputSchema = z.object({
+ keyword: z.string(),
+ searchVolume: z.number().nullable(),
+ keywordDifficulty: z.number().nullable(),
+ cpc: z.number().nullable(),
+ competition: z.number().nullable(),
+ intent: z.string().nullable(),
+ tags: z.array(z.string()),
+});
+
+function toMcpRow(
+ row: SavedKeywordRow,
+): z.infer<typeof savedKeywordOutputSchema> {
+ return {
+ keyword: row.keyword,
+ searchVolume: row.searchVolume,
+ keywordDifficulty: row.keywordDifficulty,
+ cpc: row.cpc,
+ competition: row.competition,
+ intent: row.intent,
+ tags: row.tags.map((tag) => tag.name),
+ };
+}
+
+function toMcpTag(tag: SavedKeywordTagSummary) {
+ return { name: tag.name, keywordCount: tag.keywordCount };
+}
const inputSchema = {
projectId: projectIdSchema,
@@ -36,9 +65,9 @@ export const listSavedKeywordsTool = {
"Lists keywords saved to a project (with cached metrics like search volume, difficulty, CPC, and tags if available). Uses no credits — reads from OpenSEO's database, no DataForSEO call. Use tag filters when the user asks for a saved segment; multiple tags match ANY tag.",
inputSchema,
outputSchema: {
- rows: z.array(looseObjectOutputSchema),
+ rows: z.array(savedKeywordOutputSchema),
totalCount: z.number(),
- tags: z.array(looseObjectOutputSchema),
+ tags: z.array(z.object({ name: z.string(), keywordCount: z.number() })),
...optionalMetaOutputSchema,
},
annotations: {
@@ -79,7 +108,11 @@ export const listSavedKeywordsTool = {
args.projectId,
`/p/${args.projectId}/saved`,
),
- structuredContent: { rows, totalCount, tags },
+ structuredContent: {
+ rows: rows.map(toMcpRow),
+ totalCount,
+ tags: tags.map(toMcpTag),
+ },
});
},
),
diff --git a/src/server/mcp/tools/research-keywords.test.ts b/src/server/mcp/tools/research-keywords.test.ts
new file mode 100644
index 00000000..022d9d89
--- /dev/null
+++ b/src/server/mcp/tools/research-keywords.test.ts
@@ -0,0 +1,73 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { researchKeywordsTool } from "./research-keywords";
+import { makeToolContext } from "./tool-test-support";
+
+const mocks = vi.hoisted(() => ({
+ getProjectForOrganization: vi.fn(),
+ research: vi.fn(),
+}));
+
+vi.mock("@/server/features/projects/services/ProjectService", () => ({
+ ProjectService: {
+ getProjectForOrganization: mocks.getProjectForOrganization,
+ },
+}));
+vi.mock("@/server/auth/repositories/AuthRepository", () => ({
+ AuthRepository: { getMembership: vi.fn() },
+}));
+vi.mock("@/server/features/keywords/services/KeywordResearchService", () => ({
+ KeywordResearchService: { research: mocks.research },
+}));
+
+describe("research_keywords", () => {
+ beforeEach(() => {
+ mocks.getProjectForOrganization.mockResolvedValue({
+ id: "project_1",
+ locationCode: 2840,
+ languageCode: "en",
+ });
+ });
+
+ it("returns metric rows without the monthly trend array", async () => {
+ mocks.research.mockResolvedValue({
+ source: "labs",
+ usedFallback: false,
+ rows: [
+ {
+ keyword: "seo mcp",
+ searchVolume: 320,
+ keywordDifficulty: 12,
+ cpc: 4.1,
+ competition: 0.2,
+ intent: "commercial",
+ trend: [{ year: 2026, month: 8, searchVolume: 300 }],
+ },
+ ],
+ });
+
+ const result = await researchKeywordsTool.handler(
+ { projectId: "project_1", seeds: [{ seed: "seo mcp" }] },
+ makeToolContext(),
+ );
+
+ expect(result.structuredContent?.results).toEqual([
+ {
+ seed: "seo mcp",
+ ok: true,
+ rowCount: 1,
+ source: "labs",
+ usedFallback: false,
+ rows: [
+ {
+ keyword: "seo mcp",
+ searchVolume: 320,
+ keywordDifficulty: 12,
+ cpc: 4.1,
+ competition: 0.2,
+ intent: "commercial",
+ },
+ ],
+ },
+ ]);
+ });
+});
diff --git a/src/server/mcp/tools/research-keywords.ts b/src/server/mcp/tools/research-keywords.ts
index 46862852..c40aa6e0 100644
--- a/src/server/mcp/tools/research-keywords.ts
+++ b/src/server/mcp/tools/research-keywords.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
import { KeywordResearchService } from "@/server/features/keywords/services/KeywordResearchService";
+import type { EnrichedKeyword } from "@/server/features/keywords/services/research/helpers";
import { mcpResponse } from "@/server/mcp/formatters";
import { buildProjectMeta } from "@/server/mcp/context";
import {
@@ -54,9 +55,23 @@ type ResearchRow = {
intent: string;
};
-// The full rows (including trend data) still ship in structuredContent; this
-// table exists so MCP clients that surface only text content see every keyword
-// and its metrics, not just the count summary.
+// The 12-month trend array is ~80% of the bytes per row and no MCP consumer
+// reads it; get_keyword_metrics returns trends for the few keywords that need
+// them.
+function toResearchRow(row: EnrichedKeyword): ResearchRow {
+ return {
+ keyword: row.keyword,
+ searchVolume: row.searchVolume,
+ keywordDifficulty: row.keywordDifficulty,
+ cpc: row.cpc,
+ competition: row.competition,
+ intent: row.intent,
+ };
+}
+
+// The rows also ship in structuredContent; this table exists so MCP clients
+// that surface only text content see every keyword and its metrics, not just
+// the count summary.
const RESEARCH_COLUMNS: McpTableColumn<ResearchRow>[] = [
{ header: "keyword", value: (row) => row.keyword },
{ header: "volume", value: (row) => row.searchVolume },
@@ -130,7 +145,7 @@ export const researchKeywordsTool = {
rowCount: data.rows.length,
source: data.source,
usedFallback: data.usedFallback,
- rows: data.rows,
+ rows: data.rows.map(toResearchRow),
};
} catch (error) {
return {
diff --git a/src/server/mcp/tools/save-keywords.ts b/src/server/mcp/tools/save-keywords.ts
index c9017325..f91877ed 100644
--- a/src/server/mcp/tools/save-keywords.ts
+++ b/src/server/mcp/tools/save-keywords.ts
@@ -24,7 +24,7 @@ const inputSchema = {
.max(100)
.optional()
.describe(
- "Optional metrics for the saved keywords. Copy keyword, searchVolume, keywordDifficulty, cpc, competition, and intent from research_keywords rows; map each row's trend to monthlySearches. Match each metric using its keyword field.",
+ "Optional metrics for the saved keywords. Copy keyword, searchVolume, keywordDifficulty, cpc, competition, and intent from research_keywords or get_keyword_metrics rows. monthlySearches is optional. Match each metric using its keyword field.",
),
tags: z
.array(z.string().min(1).max(64))
diff --git a/src/server/mcp/tools/saved-keywords-tools.test.ts b/src/server/mcp/tools/saved-keywords-tools.test.ts
index 1af4c38d..f1652998 100644
--- a/src/server/mcp/tools/saved-keywords-tools.test.ts
+++ b/src/server/mcp/tools/saved-keywords-tools.test.ts
@@ -196,8 +196,10 @@ describe("saved keyword MCP tools", () => {
});
expect(result.structuredContent).toMatchObject({
totalCount: 1,
- rows: [{ keyword: "technical seo" }],
+ rows: [{ keyword: "technical seo", tags: ["Content"] }],
+ tags: [{ name: "Content", keywordCount: 1 }],
});
+ expect(result.structuredContent?.rows?.[0]).not.toHaveProperty("id");
const [content] = result.content;
expect(content).toMatchObject({ type: "text" });
expect(content?.type === "text" ? content.text : "").toContain(
diff --git a/src/server/mcp/tools/search-console-tools.test.ts b/src/server/mcp/tools/search-console-tools.test.ts
index 1d5fc466..62eb326a 100644
--- a/src/server/mcp/tools/search-console-tools.test.ts
+++ b/src/server/mcp/tools/search-console-tools.test.ts
@@ -30,6 +30,14 @@ vi.mock("@/server/features/gsc/services/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({
@@ -103,6 +111,58 @@ describe("search console MCP 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"),
diff --git a/src/server/mcp/tools/search-console-tools.ts b/src/server/mcp/tools/search-console-tools.ts
index e3b15cd6..d0e1397f 100644
--- a/src/server/mcp/tools/search-console-tools.ts
+++ b/src/server/mcp/tools/search-console-tools.ts
@@ -117,6 +117,55 @@ function describeGscError(error: unknown): string {
// get_search_console_performance
// ---------------------------------------------------------------------------
+type MetricFilter = {
+ minPosition?: number;
+ maxPosition?: number;
+ minImpressions?: number;
+};
+
+function pickMetricFilter(args: MetricFilter): MetricFilter | null {
+ const { minPosition, maxPosition, minImpressions } = args;
+ if (
+ minPosition === undefined &&
+ maxPosition === undefined &&
+ minImpressions === undefined
+ ) {
+ return null;
+ }
+ return { minPosition, maxPosition, minImpressions };
+}
+
+// Rows without a position (discover/googleNews) never match a position bound.
+function matchesMetricFilter(row: GscPerfRow, filter: MetricFilter): boolean {
+ if (
+ filter.minImpressions !== undefined &&
+ row.impressions < filter.minImpressions
+ ) {
+ return false;
+ }
+ if (filter.minPosition !== undefined) {
+ if (row.position === undefined || row.position < filter.minPosition)
+ return false;
+ }
+ if (filter.maxPosition !== undefined) {
+ if (row.position === undefined || row.position > filter.maxPosition)
+ return false;
+ }
+ return true;
+}
+
+// Google returns full-precision floats (0.041237113402061855); four decimals of
+// CTR and one of position is all anyone reads and trims ~40 bytes per row.
+function roundMetrics<T extends GscPerfRow>(row: T): T {
+ return {
+ ...row,
+ ctr: Math.round(row.ctr * 10_000) / 10_000,
+ ...(row.position === undefined
+ ? {}
+ : { position: Math.round(row.position * 10) / 10 }),
+ };
+}
+
const filterSchema = z.object({
dimension: z.enum(GSC_DIMENSIONS),
operator: z.enum(GSC_FILTER_OPERATORS).default("equals"),
@@ -163,9 +212,27 @@ const perfInputSchema = {
.max(GSC_MAX_ROW_LIMIT)
.optional()
.describe(
- "Rows per call (default 1000, max 1000). GSC sorts by clicks desc and can't filter by position — filter 'striking distance' positions client-side, and paginate with startRow when hasMore is true.",
+ `Rows per call (default ${GSC_DEFAULT_ROW_LIMIT}, max ${GSC_MAX_ROW_LIMIT}). GSC sorts by clicks desc; paginate with startRow when hasMore is true.`,
),
startRow: z.number().int().min(0).optional().describe("Pagination offset."),
+ minPosition: z
+ .number()
+ .min(1)
+ .optional()
+ .describe(
+ "Keep rows with average position >= this. For 'striking distance' queries use minPosition 5, maxPosition 20, minImpressions 50.",
+ ),
+ maxPosition: z
+ .number()
+ .min(1)
+ .optional()
+ .describe("Keep rows with average position <= this."),
+ minImpressions: z
+ .number()
+ .int()
+ .min(0)
+ .optional()
+ .describe("Keep rows with at least this many impressions."),
type: z
.enum(GSC_SEARCH_TYPES)
.optional()
@@ -183,7 +250,7 @@ export const getSearchConsolePerformanceTool = {
config: {
title: "Get Google Search Console performance",
description:
- "Query the connected Search Console property's Search Analytics: clicks, impressions, CTR, and average position by query/page/country/device/date. First-party data — use it for what already ranks, near-ranking queries, and pages with real demand. ctr is a 0-1 fraction; position is a 1-based average and is omitted from rows when type is 'discover' or 'googleNews' (Google does not report it there — treat it as unavailable, not a failure); dates are Pacific Time; the last ~3 days may be incomplete. Read-only; uses no credits.",
+ "Query the connected Search Console property's Search Analytics: clicks, impressions, CTR, and average position by query/page/country/device/date. First-party data — use it for what already ranks, near-ranking queries, and pages with real demand. Google sorts by clicks and can't filter by position, so minPosition/maxPosition/minImpressions are applied server-side over the top 1000 rows of the window — use them instead of fetching everything. ctr is a 0-1 fraction; position is a 1-based average and is omitted from rows when type is 'discover' or 'googleNews' (Google does not report it there — treat it as unavailable, not a failure); dates are Pacific Time; the last ~3 days may be incomplete. Read-only; uses no credits.",
inputSchema: perfInputSchema,
outputSchema: {
ok: z.boolean(),
@@ -255,20 +322,47 @@ export const getSearchConsolePerformanceTool = {
}
try {
- const result = await GscService.getPerformance(
- args satisfies GscPerformanceInput,
- );
+ const requestedLimit = args.rowLimit ?? GSC_DEFAULT_ROW_LIMIT;
+ const metricFilter = pickMetricFilter(args);
+ // Google can't filter by position or impressions, so with a metric filter
+ // we fetch the full window and filter here; fetched == returned otherwise.
+ const fetchLimit = metricFilter ? GSC_MAX_ROW_LIMIT : requestedLimit;
+ const result = await GscService.getPerformance({
+ projectId: args.projectId,
+ dimensions: args.dimensions,
+ dateRange: args.dateRange,
+ startDate: args.startDate,
+ endDate: args.endDate,
+ filters: args.filters,
+ rowLimit: fetchLimit,
+ startRow: args.startRow,
+ type: args.type,
+ dataState: args.dataState,
+ } satisfies GscPerformanceInput);
const dimensions = result.request.dimensions ?? ["query"];
- // rowLimit is clamped to the agent cap in buildSearchAnalyticsRequest, so
- // result.rows is already <= the cap — every count below reflects what we return.
- const rows = result.rows;
- const requestedLimit = result.request.rowLimit ?? GSC_DEFAULT_ROW_LIMIT;
- const hasMore = rows.length >= requestedLimit;
- const nextStartRow = (result.request.startRow ?? 0) + rows.length;
+ const startRow = result.request.startRow ?? 0;
+ const fetched = result.rows;
+ const kept = metricFilter
+ ? fetched.filter((row) => matchesMetricFilter(row, metricFilter))
+ : fetched;
+ const rows = kept.slice(0, requestedLimit).map(roundMetrics);
+ // Pagination stays in Google's row space: the next page starts right after
+ // the last row we returned (which may be well past rows.length when a
+ // metric filter dropped rows before it).
+ const lastReturned = kept[rows.length - 1];
+ const truncated = kept.length > rows.length;
+ const hasMore = truncated || fetched.length >= fetchLimit;
+ const nextStartRow =
+ truncated && lastReturned
+ ? startRow + fetched.indexOf(lastReturned) + 1
+ : startRow + fetched.length;
+ const filterText = metricFilter
+ ? ` · filtered ${fetched.length} rows → ${kept.length}`
+ : "";
const header =
`${result.siteUrl} · ${dimensions.join("+")} · ${result.request.startDate}→${result.request.endDate} · ` +
- `${rows.length} row${rows.length === 1 ? "" : "s"}${hasMore ? " (more available — paginate with startRow)" : ""}`;
+ `${rows.length} row${rows.length === 1 ? "" : "s"}${filterText}${hasMore ? " (more available — paginate with startRow)" : ""}`;
const text =
rows.length > 0
? `${header}\n${formatMcpTable(rows, GSC_PERF_COLUMNS)}`