Skip to content

Open source alternative to Semrush and Ahrefs

Claude reported "no data" for 21 tools that had plenty (#559)

Ben Senescu8829090638ce
diff --git a/src/server/features/project-context/services/ProjectContextService.ts b/src/server/features/project-context/services/ProjectContextService.ts
index 15d30fe6..59dcc51a 100644
--- a/src/server/features/project-context/services/ProjectContextService.ts
+++ b/src/server/features/project-context/services/ProjectContextService.ts
@@ -296,8 +296,11 @@ export function renderProjectContextMarkdown(context: ProjectContext): string {
context.researchLog.length === 1 ? "entry" : "entries"
})`,
[
+ // Competitors render by domain and key pages by url — the keys their
+ // remove ops take. A log entry's only address is its id, so it is the
+ // key that has to appear here for removeResearchLog to be usable.
...context.researchLog.map(
- (entry) => `- ${entry.entryDate}: ${entry.summary}`,
+ (entry) => `- ${entry.entryDate}: ${entry.summary} [id: ${entry.id}]`,
),
...(context.researchLog.length >= RESEARCH_LOG_LIMIT
? [
diff --git a/src/server/mcp/formatters.test.ts b/src/server/mcp/formatters.test.ts
index 42bba536..88a1c6f9 100644
--- a/src/server/mcp/formatters.test.ts
+++ b/src/server/mcp/formatters.test.ts
@@ -1,7 +1,34 @@
import { describe, expect, it } from "vitest";
-import { mcpResponse } from "./formatters";
+import { mcpResponse, MCP_TEXT_CHAR_BUDGET } from "./formatters";
+import { formatMcpTable } from "./table";
describe("mcpResponse", () => {
+ it("caps a single oversized row including the notice and preserves its data", () => {
+ const rows = [{ value: "x".repeat(MCP_TEXT_CHAR_BUDGET * 2) }];
+ const result = mcpResponse({
+ text: formatMcpTable(rows, [
+ { header: "value", value: (row) => row.value },
+ ]),
+ structuredContent: { rows },
+ });
+ const text = result.content[0];
+ expect(text.type).toBe("text");
+ if (text.type !== "text") throw new Error("Expected text");
+ expect(text.text).toHaveLength(MCP_TEXT_CHAR_BUDGET);
+ expect(text.text).toContain("Text truncated");
+ expect(text.text).toContain("structuredContent payload is unchanged");
+ expect(result.structuredContent.rows).toBe(rows);
+ });
+
+ it("does not promise structured data when truncating a text-only result", () => {
+ const result = mcpResponse({ text: "x".repeat(MCP_TEXT_CHAR_BUDGET + 1) });
+ const text = result.content[0];
+ if (text.type !== "text") throw new Error("Expected text");
+ expect(text.text).toHaveLength(MCP_TEXT_CHAR_BUDGET);
+ expect(text.text).not.toContain("structuredContent");
+ expect(result.structuredContent).toBeUndefined();
+ });
+
it("drops undefined meta keys and omits _meta when nothing is left", () => {
const result = mcpResponse({
text: "hi",
diff --git a/src/server/mcp/formatters.ts b/src/server/mcp/formatters.ts
index bf3646ec..b0a152d1 100644
--- a/src/server/mcp/formatters.ts
+++ b/src/server/mcp/formatters.ts
@@ -1,5 +1,9 @@
import type { CallToolResult } from "@modelcontextprotocol/server";
+// This limits the combined human/model-readable text, not structured data,
+// serialized response bytes, or model tokens.
+export const MCP_TEXT_CHAR_BUDGET = 40_000;
+
type McpResponseMeta = {
url?: string;
projectId?: string;
@@ -29,8 +33,19 @@ export function mcpResponse(opts: {
meta?: McpResponseMeta;
structuredContent?: Record<string, unknown>;
}): CallToolResult {
+ const truncationNotice =
+ `\n\n[Text truncated at ${MCP_TEXT_CHAR_BUDGET.toLocaleString("en-US")} characters; this is partial text output. ` +
+ (opts.structuredContent
+ ? "The structuredContent payload is unchanged. "
+ : "") +
+ "Use pagination or a narrower request where supported; another call may charge credits.]";
+ const text =
+ opts.text.length > MCP_TEXT_CHAR_BUDGET
+ ? opts.text.slice(0, MCP_TEXT_CHAR_BUDGET - truncationNotice.length) +
+ truncationNotice
+ : opts.text;
const result: CallToolResult = {
- content: [{ type: "text", text: opts.text }],
+ content: [{ type: "text", text }],
};
let meta: Record<string, unknown> | undefined;
if (opts.meta) {
diff --git a/src/server/mcp/table.test.ts b/src/server/mcp/table.test.ts
index cbf8e5cf..6409a18e 100644
--- a/src/server/mcp/table.test.ts
+++ b/src/server/mcp/table.test.ts
@@ -18,25 +18,62 @@ describe("formatMcpCell", () => {
])("renders %j as %j", (input, expected) => {
expect(formatMcpCell(input)).toBe(expected);
});
+
+ it("swaps pipes so provider prose can't split a cell across columns", () => {
+ expect(formatMcpCell("Best Accounting Software | QuickBooks")).toBe(
+ "Best Accounting Software ¦ QuickBooks",
+ );
+ });
});
describe("formatMcpTable", () => {
+ type Row = { keyword: string; volume: number | null };
+ const columns = [
+ { header: "keyword", value: (row: Row) => row.keyword },
+ { header: "volume", value: (row: Row) => row.volume },
+ ];
+
it("renders a header line plus one line per row", () => {
- type Row = { keyword: string; volume: number | null };
const table = formatMcpTable(
[
{ keyword: "seo tools", volume: 2400 },
{ keyword: "seo audit", volume: null },
],
- [
- { header: "keyword", value: (row: Row) => row.keyword },
- { header: "volume", value: (row: Row) => row.volume },
- ],
+ columns,
);
expect(table).toBe(
["keyword | volume", "seo tools | 2400", "seo audit | —"].join("\n"),
);
});
+
+ it("stops at the character budget and says how many rows it dropped", () => {
+ const rows = Array.from({ length: 2000 }, (_, index) => ({
+ keyword: `keyword ${index} ${"x".repeat(80)}`,
+ volume: index,
+ }));
+ const table = formatMcpTable(rows, columns);
+ const lines = table.split("\n");
+
+ // Header line and truncation line bracket the rows that did render.
+ const rendered = lines.length - 2;
+ expect(table.length).toBeLessThan(45_000);
+ expect(lines.at(-1)).toBe(
+ `…${rows.length - rendered} more rows are in structuredContent; this table preview is truncated. A narrower request is a new call and, on credit-charging tools, a new charge.`,
+ );
+ });
+
+ it("honours a caller-supplied budget so multi-table tools can split it", () => {
+ const rows = [
+ { keyword: "a", volume: 1 },
+ { keyword: "b", volume: 2 },
+ { keyword: "c", volume: 3 },
+ ];
+ const lines = formatMcpTable(rows, columns, 24).split("\n");
+
+ expect(lines).toHaveLength(3);
+ expect(lines[1]).toBe("a | 1");
+ expect(lines[2]).toContain("…2 more rows");
+ });
});
describe("readPath", () => {
diff --git a/src/server/mcp/table.ts b/src/server/mcp/table.ts
index 1484a499..762e7d7d 100644
--- a/src/server/mcp/table.ts
+++ b/src/server/mcp/table.ts
@@ -1,7 +1,9 @@
+import { MCP_TEXT_CHAR_BUDGET } from "./formatters";
+
// Shared renderer for MCP tool text output. Tools return row data in
// structuredContent, but MCP clients that surface only the text content block
-// would otherwise see just a summary. Rendering every row as a compact
-// pipe-delimited table here keeps the text block in parity with the data.
+// would otherwise see just a summary. Render a compact table from the same
+// rows; large tables may be truncated with an explicit notice.
export type McpTableColumn<T> = {
header: string;
@@ -11,8 +13,9 @@ export type McpTableColumn<T> = {
};
/** Format a single cell. Nullish/empty -> "—"; integers stay exact; other
- * numbers get 2 decimals; strings are collapsed to a single line so a stray
- * newline can't break the table layout. */
+ * numbers get 2 decimals; text is collapsed to a single line and its pipes
+ * become "¦" so provider prose ("Best Software | Brand") can't split one cell
+ * across two columns. */
export function formatMcpCell(value: unknown): string {
if (value == null || value === "") return "—";
if (typeof value === "number") {
@@ -20,17 +23,31 @@ export function formatMcpCell(value: unknown): string {
return Number.isInteger(value) ? String(value) : value.toFixed(2);
}
if (typeof value === "boolean") return value ? "yes" : "no";
- if (typeof value === "string") return value.replace(/\s+/g, " ").trim();
if (typeof value === "bigint") return value.toString();
// Arrays/objects would stringify to "[object Object]"; emit compact JSON so a
// stray nested value still reads as something in the text table.
+ const text = typeof value === "string" ? value : safeJson(value);
+ return text.replace(/\s+/g, " ").replace(/\|/g, "¦").trim() || "—";
+}
+
+function safeJson(value: unknown): string {
try {
- return JSON.stringify(value) ?? "—";
+ return JSON.stringify(value) ?? "";
} catch {
- return "—";
+ return "";
}
}
+/** Column `format` for a 0-1 ratio rendered as a percentage (GSC/GA4 CTR). */
+export function percentCell(value: unknown): string {
+ return typeof value === "number" ? `${(value * 100).toFixed(1)}%` : "—";
+}
+
+/** Column `format` for an average SERP position, which is fractional. */
+export function positionCell(value: unknown): string {
+ return typeof value === "number" ? value.toFixed(1) : "—";
+}
+
/** Column `format` that truncates long text after normal cell formatting, so
* provider prose can't dominate the table (full text stays in
* structuredContent). */
@@ -41,21 +58,46 @@ export function truncatedCell(maxLength: number) {
};
}
-/** Render rows as a `header | header` table with one line per row. */
+/** Row budget for each of `sections` tables sharing one response. Each section
+ * keeps 500 characters back for its own header and "more rows" notice plus
+ * its share of the footer, so the last table ends on that notice instead of
+ * being cut mid-row by the response cap. */
+export function sectionTableBudget(sections: number): number {
+ return Math.floor(MCP_TEXT_CHAR_BUDGET / Math.max(sections, 1)) - 500;
+}
+
+/** Render complete table rows up to a target size. Multi-query tools split
+ * this allowance so the first query cannot crowd out every later query.
+ * Headers, notices and a single wide row can exceed this target; mcpResponse
+ * applies the actual combined text cap. */
export function formatMcpTable<T>(
rows: readonly T[],
columns: readonly McpTableColumn<T>[],
+ budget = MCP_TEXT_CHAR_BUDGET,
): string {
- const headerLine = columns.map((column) => column.header).join(" | ");
- const rowLines = rows.map((row) =>
- columns
+ const header = columns.map((column) => column.header).join(" | ");
+ const lines = [header];
+ let used = header.length;
+ let rendered = 0;
+ for (const row of rows) {
+ const line = columns
.map((column) => {
const raw = column.value(row);
return column.format ? column.format(raw) : formatMcpCell(raw);
})
- .join(" | "),
- );
- return [headerLine, ...rowLines].join("\n");
+ .join(" | ");
+ // Always render one row, so a single very wide row still reaches the model.
+ if (rendered > 0 && used + line.length > budget) break;
+ lines.push(line);
+ used += line.length + 1;
+ rendered += 1;
+ }
+ if (rendered < rows.length) {
+ lines.push(
+ `…${rows.length - rendered} more rows are in structuredContent; this table preview is truncated. A narrower request is a new call and, on credit-charging tools, a new charge.`,
+ );
+ }
+ return lines.join("\n");
}
/** Walk a chain of keys through nested unknown records (provider rows).
diff --git a/src/server/mcp/tools/dataforseo-research-tools.test.ts b/src/server/mcp/tools/dataforseo-research-tools.test.ts
index d6e4c8e4..8fdd3b86 100644
--- a/src/server/mcp/tools/dataforseo-research-tools.test.ts
+++ b/src/server/mcp/tools/dataforseo-research-tools.test.ts
@@ -1,3 +1,4 @@
+/* eslint-disable max-lines, max-lines-per-function -- every DataForSEO research tool is covered in this one spec, matching dataforseo-research-tools.ts */
import { beforeEach, describe, expect, it, vi } from "vitest";
import { z } from "zod";
import type { fetchKeywordMetricsForList as FetchKeywordMetricsForList } from "@/server/lib/dataforseo/keyword-metrics";
@@ -167,6 +168,29 @@ describe("DataForSEO research MCP tools", () => {
expect(textContent(result)).toContain("Acme Cafe");
});
+ // EVE-67: a coordinate with no zoom lets DataForSEO pick one, and its guess
+ // returned 1 row for "bookkeeping services" at this exact coordinate — the
+ // agent then told the customer they had no competitors.
+ it("falls back to a city-sized zoom when the caller gives no zoom", async () => {
+ const local = vi.fn().mockResolvedValue([]);
+ mocks.createDataforseoClient.mockReturnValue({ serp: { local } });
+
+ await researchTools.getLocalSerpResultsTool.handler(
+ {
+ projectId: "project_1",
+ keyword: "bookkeeping services",
+ near: { latitude: 37.3079, longitude: -121.8917 },
+ },
+ toolContext,
+ );
+
+ expect(local).toHaveBeenCalledWith(
+ expect.objectContaining({
+ locationCoordinate: "37.3079,-121.8917,12z",
+ }),
+ );
+ });
+
it("fetches Google Business Q&A as an explicit tool", async () => {
const questionsAnswers = vi
.fn()
@@ -304,7 +328,9 @@ describe("DataForSEO research MCP tools", () => {
main_intent: "commercial",
});
const out = textContent(result);
- expect(out).toContain("keyword | volume | KD | CPC | competition | intent");
+ expect(out).toContain(
+ "keyword | volume | trend | KD | CPC | competition | intent",
+ );
expect(out).toContain("seo automation");
});
diff --git a/src/server/mcp/tools/dataforseo-research-tools.ts b/src/server/mcp/tools/dataforseo-research-tools.ts
index d416c881..7fded867 100644
--- a/src/server/mcp/tools/dataforseo-research-tools.ts
+++ b/src/server/mcp/tools/dataforseo-research-tools.ts
@@ -1,5 +1,5 @@
/* eslint-disable max-lines */
-import { sort } from "remeda";
+import { firstBy, sort } from "remeda";
import { z } from "zod";
import {
createDataforseoClient,
@@ -14,8 +14,10 @@ import {
} from "@/server/mcp/output-schemas";
import { withMcpProjectAuth } from "@/server/mcp/project-auth";
import {
+ formatMcpCell,
formatMcpTable,
readPath,
+ truncatedCell,
type McpTableColumn,
} from "@/server/mcp/table";
import {
@@ -118,10 +120,21 @@ const localSerpNearSchema = z
.min(4)
.max(18)
.optional()
- .describe("Map zoom level (4-18). Higher zoom narrows the local area."),
+ .describe(
+ "Map zoom level (4-18). Higher zoom narrows the local area. Defaults to 12, a city-sized viewport; raise it for a neighbourhood, lower it for a metro.",
+ ),
})
.describe("Coordinate (and optional map zoom) the SERP is fetched from.");
+// A coordinate with no zoom lets DataForSEO infer one, and its guess is far too
+// tight for a city-level query: measured at San Jose's centre (37.3079,
+// -121.8917) on 2026-09-03, "bookkeeping services" returned 1 row with no zoom
+// and 20 at zoom 12; "plumber" returned 0 and 20. An agent reads that as "you
+// have no competitors". Zoom 12 is a ~12 km viewport at mid latitudes — one
+// city, not one neighbourhood and not a whole metro. 10 and 11 also return a
+// full page but span 47 km and 23 km, which drags in another city's businesses.
+const DEFAULT_LOCAL_SERP_ZOOM = 12;
+
const domainTargetSchema = z
.string()
.min(1)
@@ -617,7 +630,10 @@ type RankedKeywordRow = {
keyword: unknown;
rank: unknown;
volume: unknown;
+ kd: unknown;
+ intent: unknown;
cpc: unknown;
+ traffic: unknown;
url: unknown;
};
@@ -630,7 +646,18 @@ function toRankedKeywordRow(item: unknown): RankedKeywordRow {
readPath(item, "ranked_serp_element", "rank_absolute") ??
readPath(item, "rank_absolute"),
volume: readPath(item, "keyword_data", "keyword_info", "search_volume"),
+ kd:
+ readPath(
+ item,
+ "keyword_data",
+ "keyword_properties",
+ "keyword_difficulty",
+ ) ?? readPath(item, "keyword_data", "keyword_info", "keyword_difficulty"),
+ intent: readPath(item, "keyword_data", "search_intent_info", "main_intent"),
cpc: readPath(item, "keyword_data", "keyword_info", "cpc"),
+ traffic:
+ readPath(item, "ranked_serp_element", "serp_item", "etv") ??
+ readPath(item, "ranked_serp_element", "etv"),
url:
readPath(item, "ranked_serp_element", "serp_item", "url") ??
readPath(item, "ranked_serp_element", "url"),
@@ -641,7 +668,10 @@ const RANKED_KEYWORD_COLUMNS: McpTableColumn<RankedKeywordRow>[] = [
{ header: "keyword", value: (row) => row.keyword },
{ header: "rank", value: (row) => row.rank },
{ header: "volume", value: (row) => row.volume },
+ { header: "KD", value: (row) => row.kd },
+ { header: "intent", value: (row) => row.intent },
{ header: "CPC", value: (row) => row.cpc },
+ { header: "traffic", value: (row) => row.traffic },
{ header: "url", value: (row) => row.url },
];
@@ -700,8 +730,14 @@ const LOCAL_BUSINESS_COLUMNS: McpTableColumn<unknown>[] = [
{ header: "category", value: (row) => readPath(row, "category") },
{ header: "rating", value: (row) => readPath(row, "rating", "value") },
{ header: "reviews", value: (row) => readPath(row, "rating", "votes_count") },
+ { header: "claimed", value: (row) => readPath(row, "is_claimed") },
+ { header: "domain", value: (row) => readPath(row, "domain") },
{ header: "phone", value: (row) => readPath(row, "phone") },
{ header: "address", value: (row) => readPath(row, "address") },
+ // The ids are what get_business_profile / reviews / updates take, so a
+ // text-only client needs them here to follow the tool descriptions.
+ { header: "cid", value: (row) => readPath(row, "cid") },
+ { header: "place_id", value: (row) => readPath(row, "place_id") },
];
const LOCAL_SERP_COLUMNS: McpTableColumn<unknown>[] = [
@@ -715,6 +751,8 @@ const LOCAL_SERP_COLUMNS: McpTableColumn<unknown>[] = [
{ header: "reviews", value: (row) => readPath(row, "rating", "votes_count") },
{ header: "phone", value: (row) => readPath(row, "phone") },
{ header: "address", value: (row) => readPath(row, "address") },
+ { header: "cid", value: (row) => readPath(row, "cid") },
+ { header: "place_id", value: (row) => readPath(row, "place_id") },
];
// Q&A rows carry a ~300-char uule URL plus avatar/contributor links on every
@@ -747,8 +785,31 @@ function trimBusinessQuestionRow(row: unknown): Record<string, unknown> {
return trimmed;
}
+/** Answers without a timestamp sort last; ties keep the earlier answer. */
+function answerTimestamp(answer: unknown): string {
+ const at = readPath(answer, "timestamp");
+ return typeof at === "string" ? at : "";
+}
+
+// The answers are half of what this tool fetches, so the text table carries the
+// most recent one; the full thread stays in structuredContent. Provider order
+// isn't guaranteed, so pick by timestamp and fall back to the first answer.
+function latestAnswerText(row: unknown): unknown {
+ const items = readPath(row, "items");
+ if (!Array.isArray(items) || items.length === 0) return undefined;
+ const answers: unknown[] = items;
+ const latest = firstBy(answers, [answerTimestamp, "desc"]);
+ return (
+ readPath(latest, "answer_text") ?? readPath(latest, "original_answer_text")
+ );
+}
+
const BUSINESS_QUESTION_COLUMNS: McpTableColumn<unknown>[] = [
- { header: "question", value: (row) => readPath(row, "question_text") },
+ {
+ header: "question",
+ value: (row) =>
+ readPath(row, "question_text") ?? readPath(row, "original_question_text"),
+ },
{ header: "asked by", value: (row) => readPath(row, "profile_name") },
{ header: "when", value: (row) => readPath(row, "time_ago") },
{
@@ -758,6 +819,11 @@ const BUSINESS_QUESTION_COLUMNS: McpTableColumn<unknown>[] = [
return Array.isArray(answers) ? answers.length : 0;
},
},
+ {
+ header: "latest answer",
+ value: latestAnswerText,
+ format: truncatedCell(160),
+ },
];
const SERP_COMPETITOR_COLUMNS: McpTableColumn<unknown>[] = [
@@ -769,9 +835,34 @@ const SERP_COMPETITOR_COLUMNS: McpTableColumn<unknown>[] = [
{ header: "etv", value: (row) => readPath(row, "etv") },
];
+function monthOrdinal(entry: unknown): number {
+ const year = readPath(entry, "year");
+ const month = readPath(entry, "month");
+ return (
+ (typeof year === "number" ? year : 0) * 12 +
+ (typeof month === "number" ? month : 0)
+ );
+}
+
+/** Render monthly_searches as the last three volumes, oldest → newest
+ * ("880 → 1300 → 1900"). Provider order isn't guaranteed, so sort by
+ * year/month before slicing; the full series stays in structuredContent. */
+function monthlyTrendCell(value: unknown): string {
+ if (!Array.isArray(value) || value.length === 0) return "—";
+ return sort(value, (a, b) => monthOrdinal(a) - monthOrdinal(b))
+ .slice(-3)
+ .map((entry) => formatMcpCell(readPath(entry, "search_volume")))
+ .join(" → ");
+}
+
const KEYWORD_METRIC_COLUMNS: McpTableColumn<unknown>[] = [
{ header: "keyword", value: (row) => readPath(row, "keyword") },
{ header: "volume", value: (row) => readPath(row, "search_volume") },
+ {
+ header: "trend",
+ value: (row) => readPath(row, "monthly_searches"),
+ format: monthlyTrendCell,
+ },
{ header: "KD", value: (row) => readPath(row, "keyword_difficulty") },
{ header: "CPC", value: (row) => readPath(row, "cpc") },
{ header: "competition", value: (row) => readPath(row, "competition") },
@@ -841,7 +932,7 @@ export const getRankedKeywordsTool = {
const text =
rankedRows.length === 0
? `No ranked keyword rows for ${targetLabel}.`
- : `Found ${rankedRows.length} ranked keyword rows for ${targetLabel}${keywords.totalCount != null ? ` (of ${keywords.totalCount} total)` : ""}:\n${formatMcpTable(rankedRows, RANKED_KEYWORD_COLUMNS)}`;
+ : `Found ${rankedRows.length} ranked keyword rows for ${targetLabel}${keywords.totalCount != null ? ` (of ${keywords.totalCount} total)` : ""}. Columns: KD = keyword difficulty (0-100), traffic = estimated monthly organic visits from this keyword; "—" = unavailable.\n${formatMcpTable(rankedRows, RANKED_KEYWORD_COLUMNS)}`;
return mcpResponse({
text,
meta: buildProjectMeta(
@@ -865,7 +956,7 @@ export const searchLocalBusinessesTool = {
config: {
title: "Search local businesses",
description:
- "Searches local business listings near a coordinate, with optional rating, review-count, and claimed-status filters. Use this to find local business candidates, nearby competitors, or unclaimed listings; it does not run Maps rank checks or Q&A. Returns a compact row per business (identity, contact, rating, claim status); use get_business_profile for one business's full profile. Charges credits.",
+ "Searches local business listings near a coordinate, with optional rating, review-count, and claimed-status filters. Use this to discover businesses you cannot name yet: local candidates, nearby competitors, or unclaimed listings. It does not run Maps rank checks or Q&A. When you already know the business, use get_business_profile instead — it returns the full profile and costs less than half the credits, so it is also the cheap way to check whether a Google Business Profile exists at all. Charges credits.",
inputSchema: searchLocalBusinessesInputSchema,
outputSchema: z.looseObject({
businesses: z.array(looseObjectOutputSchema),
@@ -929,7 +1020,10 @@ export const getLocalSerpResultsTool = {
const client = createDataforseoClient(context.billing);
const rows = await client.serp.local({
keyword: args.keyword,
- locationCoordinate: formatLocalSerpCoordinate(args.near),
+ locationCoordinate: formatLocalSerpCoordinate({
+ ...args.near,
+ zoom: args.near.zoom ?? DEFAULT_LOCAL_SERP_ZOOM,
+ }),
languageCode: args.languageCode ?? context.project.languageCode,
searchType: args.searchType ?? "maps",
device: args.device ?? "mobile",
@@ -988,7 +1082,7 @@ export const getGoogleBusinessQuestionsTool = {
text:
questions.length === 0
? header
- : `${header}\n${formatMcpTable(questions, BUSINESS_QUESTION_COLUMNS)}`,
+ : `${header} Columns: answers = answer count, latest answer = most recent answer text (truncated; every answer is in structuredContent).\n${formatMcpTable(questions, BUSINESS_QUESTION_COLUMNS)}`,
meta: buildProjectMeta(context, args.projectId, `/p/${args.projectId}`),
structuredContent: { questions },
});
@@ -1096,7 +1190,7 @@ export const getKeywordMetricsTool = {
: row,
);
- const header = `Fetched metrics for ${rows.length} keywords. Columns: volume = monthly searches, KD = keyword difficulty (0-100), CPC in USD, competition = paid competition (0-1); "—" = unavailable.`;
+ const header = `Fetched metrics for ${rows.length} keywords. Columns: volume = monthly searches, trend = search volume for the last 3 months, oldest → newest, KD = keyword difficulty (0-100), CPC in USD, competition = paid competition (0-1); "—" = unavailable.`;
return mcpResponse({
text:
rows.length === 0
diff --git a/src/server/mcp/tools/get-backlinks-overview.ts b/src/server/mcp/tools/get-backlinks-overview.ts
index 15b2090e..3d9889db 100644
--- a/src/server/mcp/tools/get-backlinks-overview.ts
+++ b/src/server/mcp/tools/get-backlinks-overview.ts
@@ -8,6 +8,7 @@ import {
} from "@/server/mcp/output-schemas";
import { withMcpProjectAuth } from "@/server/mcp/project-auth";
import {
+ formatMcpCell,
formatMcpTable,
readPath,
type McpTableColumn,
@@ -21,6 +22,12 @@ import {
import { normalizeBacklinksTarget } from "@/server/lib/dataforseo";
import { researchScopeSchema } from "@/shared/researchScope";
+/** Provider timestamps look like "2019-03-05 07:34:01 +00:00"; the day is all a
+ * link-age column needs. */
+function dayCell(value: unknown) {
+ return formatMcpCell(value).slice(0, 10);
+}
+
const REFERRING_DOMAIN_COLUMNS: McpTableColumn<unknown>[] = [
{ header: "domain", value: (row) => readPath(row, "domain") },
{ header: "backlinks", value: (row) => readPath(row, "backlinks") },
@@ -29,6 +36,13 @@ const REFERRING_DOMAIN_COLUMNS: McpTableColumn<unknown>[] = [
value: (row) => readPath(row, "referringPages"),
},
{ header: "rank", value: (row) => readPath(row, "rank") },
+ { header: "spam", value: (row) => readPath(row, "spamScore") },
+ { header: "broken", value: (row) => readPath(row, "brokenBacklinks") },
+ {
+ header: "first seen",
+ value: (row) => readPath(row, "firstSeen"),
+ format: dayCell,
+ },
];
const inputSchema = {
@@ -50,8 +64,17 @@ const inputSchema = {
type Args = z.infer<z.ZodObject<typeof inputSchema>>;
-function formatMetric(value: unknown) {
- return typeof value === "number" || typeof value === "string" ? value : "?";
+/** Link velocity, appended to the total it belongs to. Dropped entirely when
+ * the provider returned neither side. */
+function formatNewLost(newValue: unknown, lostValue: unknown) {
+ if (newValue == null && lostValue == null) return "";
+ return ` (new ${formatMcpCell(newValue)} / lost ${formatMcpCell(lostValue)})`;
+}
+
+/** Bullet for a metric the provider may not return at all — omitted rather
+ * than rendered as a bare "—" the reader has to interpret. */
+function optionalMetric(label: string, value: unknown) {
+ return value == null ? [] : [`- ${label}: ${formatMcpCell(value)}`];
}
export const getBacklinksOverviewTool = {
@@ -118,16 +141,28 @@ export const getBacklinksOverviewTool = {
const text = [
`Backlinks profile for ${displayTarget} (scope: ${scope}):`,
...(scopeNote ? [`Note: ${scopeNote}`] : []),
- `- backlinks: ${formatMetric(summary.backlinks)}`,
- `- referring domains: ${formatMetric(summary.referringDomains)}`,
- `- referring pages: ${formatMetric(summary.referringPages)}`,
- `- rank: ${formatMetric(summary.rank)}`,
+ `- backlinks: ${formatMcpCell(summary.backlinks)}${formatNewLost(
+ summary.newBacklinks,
+ summary.lostBacklinks,
+ )}`,
+ `- referring domains: ${formatMcpCell(
+ summary.referringDomains,
+ )}${formatNewLost(
+ summary.newReferringDomains,
+ summary.lostReferringDomains,
+ )}`,
+ `- referring pages: ${formatMcpCell(summary.referringPages)}`,
+ `- rank: ${formatMcpCell(summary.rank)}`,
+ ...optionalMetric("broken backlinks", summary.brokenBacklinks),
+ ...optionalMetric("broken pages", summary.brokenPages),
+ ...optionalMetric("backlinks spam score", summary.backlinksSpamScore),
+ ...optionalMetric("target spam score", summary.targetSpamScore),
"",
refDomains === null
? "Referring-domains breakdown unavailable for subfolder scope."
: topDomains.length === 0
? "No referring domains found."
- : `Referring domains (${topDomains.length}):\n${formatMcpTable(topDomains, REFERRING_DOMAIN_COLUMNS)}`,
+ : `Referring domains (top ${topDomains.length} of ${formatMcpCell(summary.referringDomains)}):\n${formatMcpTable(topDomains, REFERRING_DOMAIN_COLUMNS)}`,
].join("\n");
return mcpResponse({
text,
diff --git a/src/server/mcp/tools/get-backlinks-profile.ts b/src/server/mcp/tools/get-backlinks-profile.ts
index a59b9959..f4bc6d56 100644
--- a/src/server/mcp/tools/get-backlinks-profile.ts
+++ b/src/server/mcp/tools/get-backlinks-profile.ts
@@ -7,7 +7,11 @@ import {
optionalMetaOutputSchema,
} from "@/server/mcp/output-schemas";
import { withMcpProjectAuth } from "@/server/mcp/project-auth";
-import { formatMcpTable, type McpTableColumn } from "@/server/mcp/table";
+import {
+ formatMcpCell,
+ formatMcpTable,
+ type McpTableColumn,
+} from "@/server/mcp/table";
import { projectIdSchema } from "@/server/mcp/schemas";
import {
BACKLINKS_DEFAULT_SORT,
@@ -76,10 +80,6 @@ const inputSchema = {
type Args = z.infer<z.ZodObject<typeof inputSchema>>;
-function formatMetric(value: unknown) {
- return typeof value === "number" || typeof value === "string" ? value : "?";
-}
-
function formatLinkType(value: boolean | null | undefined) {
if (value === true) return "dofollow";
if (value === false) return "nofollow";
@@ -168,7 +168,7 @@ export const getBacklinksProfileTool = {
`- page: ${backlinks.page}`,
`- page size: ${backlinks.pageSize}`,
`- rows returned: ${backlinks.rows.length}`,
- `- total backlinks: ${formatMetric(backlinks.totalCount)}`,
+ `- total backlinks: ${formatMcpCell(backlinks.totalCount)}`,
`- has more: ${backlinks.hasMore ? "yes" : "no"}`,
"",
backlinks.rows.length === 0
diff --git a/src/server/mcp/tools/get-domain-keyword-suggestions.ts b/src/server/mcp/tools/get-domain-keyword-suggestions.ts
index 6def3c29..f0839ad9 100644
--- a/src/server/mcp/tools/get-domain-keyword-suggestions.ts
+++ b/src/server/mcp/tools/get-domain-keyword-suggestions.ts
@@ -33,6 +33,10 @@ const SUGGESTION_COLUMNS: McpTableColumn<unknown>[] = [
{ header: "position", value: (row) => readPath(row, "position") },
{ header: "volume", value: (row) => readPath(row, "searchVolume") },
{ header: "KD", value: (row) => readPath(row, "keywordDifficulty") },
+ { header: "CPC", value: (row) => readPath(row, "cpc") },
+ // Rows come back ordered by estimated traffic, so it's the signal behind the
+ // order a text-only client is shown.
+ { header: "traffic", value: (row) => readPath(row, "traffic") },
];
const inputSchema = {
@@ -98,7 +102,7 @@ export const getDomainKeywordSuggestionsTool = {
const text =
keywords.length === 0
? `No ranked keywords found for ${targetLabel}.`
- : `Keywords for ${targetLabel} (${keywords.length}):\n${formatMcpTable(keywords, SUGGESTION_COLUMNS)}`;
+ : `Keywords for ${targetLabel} (${keywords.length}). Columns: KD = keyword difficulty (0-100), traffic = estimated monthly organic visits; "—" = unavailable.\n${formatMcpTable(keywords, SUGGESTION_COLUMNS)}`;
return mcpResponse({
text,
meta: buildProjectMeta(
diff --git a/src/server/mcp/tools/get-rank-tracker.ts b/src/server/mcp/tools/get-rank-tracker.ts
index b3aa053c..5f3f91b5 100644
--- a/src/server/mcp/tools/get-rank-tracker.ts
+++ b/src/server/mcp/tools/get-rank-tracker.ts
@@ -1,4 +1,5 @@
import { z } from "zod";
+import { sortBy } from "remeda";
import { RankTrackingService } from "@/server/features/rank-tracking/services/RankTrackingService";
import { mcpResponse } from "@/server/mcp/formatters";
import { buildProjectMeta } from "@/server/mcp/context";
@@ -8,6 +9,7 @@ import {
} from "@/server/mcp/output-schemas";
import { withMcpProjectAuth } from "@/server/mcp/project-auth";
import {
+ formatMcpCell,
formatMcpTable,
readPath,
type McpTableColumn,
@@ -16,6 +18,11 @@ import { projectIdSchema } from "@/server/mcp/schemas";
import { googleSerpUrl } from "@/shared/google-serp-url";
const RANK_RESULT_COLUMNS: McpTableColumn<unknown>[] = [
+ // Put the removal id before provider text that may be truncated.
+ {
+ header: "trackingKeywordId",
+ value: (row) => readPath(row, "trackingKeywordId"),
+ },
{ header: "keyword", value: (row) => readPath(row, "keyword") },
{ header: "desktop", value: (row) => readPath(row, "desktop", "position") },
{
@@ -31,9 +38,45 @@ const RANK_RESULT_COLUMNS: McpTableColumn<unknown>[] = [
header: "pinned",
value: (row) => (readPath(row, "pinned") === true ? "yes" : "no"),
},
+ {
+ // Both devices resolve to the same page in practice, so one column carries
+ // whichever device actually ranked.
+ header: "ranking url",
+ value: (row) =>
+ readPath(row, "desktop", "rankingUrl") ??
+ readPath(row, "mobile", "rankingUrl"),
+ },
{ header: "google serp", value: (row) => readPath(row, "googleSerpUrl") },
];
+function formatLocation(code: unknown, name: unknown): string {
+ const codeCell = formatMcpCell(code);
+ return typeof name === "string" && name
+ ? `${codeCell} · ${formatMcpCell(name)}`
+ : codeCell;
+}
+
+const CONFIG_COLUMNS: McpTableColumn<unknown>[] = [
+ { header: "domain", value: (row) => readPath(row, "domain") },
+ {
+ // locationName is part of a tracker's uniqueness key — without it two city
+ // trackers on the same domain and country are indistinguishable.
+ header: "location",
+ value: (row) =>
+ formatLocation(
+ readPath(row, "locationCode"),
+ readPath(row, "locationName"),
+ ),
+ },
+ { header: "lang", value: (row) => readPath(row, "languageCode") },
+ { header: "devices", value: (row) => readPath(row, "devices") },
+ { header: "depth", value: (row) => readPath(row, "serpDepth") },
+ { header: "schedule", value: (row) => readPath(row, "scheduleInterval") },
+ { header: "last checked", value: (row) => readPath(row, "lastCheckedAt") },
+ { header: "skip reason", value: (row) => readPath(row, "lastSkipReason") },
+ { header: "trackerId", value: (row) => readPath(row, "id") },
+];
+
/**
* `lastCheckedAt` comes from the newest snapshot, so a run that finished
* without saving any (e.g. every keyword errored) would otherwise read
@@ -64,6 +107,21 @@ const inputSchema = {
.describe(
"Rank tracker config ID. If omitted, lists all rank trackers in the project.",
),
+ offset: z
+ .number()
+ .int()
+ .min(0)
+ .optional()
+ .describe("Keyword row offset when trackerId is provided. Defaults to 0."),
+ limit: z
+ .number()
+ .int()
+ .min(1)
+ .max(1000)
+ .optional()
+ .describe(
+ "Keyword rows per page when trackerId is provided. Defaults to 100. Lower this if the text is truncated.",
+ ),
} as const;
type Args = z.infer<z.ZodObject<typeof inputSchema>>;
@@ -73,7 +131,7 @@ export const getRankTrackerTool = {
config: {
title: "Get rank tracker",
description:
- "Read-only access to rank tracker configs and their latest results. With `trackerId`, returns config + latest snapshot per keyword, including `trackingKeywordId` for removals and pins, `pinned` (pinned keywords are listed first), and `googleSerpUrl`, a live Google search for the tracked keyword, language, country, and city. Without it, lists all trackers in the project. Uses no credits. Use create_rank_tracker when no tracker exists; then use add_rank_tracking_keywords, remove_rank_tracking_keywords, pin_rank_tracking_keywords, estimate_rank_tracker_cost, or run_rank_tracker to manage it. `lastCheckedAt` shows position freshness. A null position means the domain was not found in the results the check returned, which can be fewer than `serpDepth`, so it does not prove the domain ranks below `serpDepth`.",
+ "Read-only access to rank tracker configs and their latest results. With `trackerId`, returns config + a page of latest snapshots (pinned keywords first), including `trackingKeywordId` for removals and pins, `pinned`, and `googleSerpUrl`, a live Google search for the tracked keyword, language, country, and city. Use offset/limit to read additional keywords. Without it, lists all trackers in the project. Uses no credits. Use create_rank_tracker when no tracker exists; then use add_rank_tracking_keywords, remove_rank_tracking_keywords, pin_rank_tracking_keywords, estimate_rank_tracker_cost, or run_rank_tracker to manage it. `lastCheckedAt` shows position freshness. A null position means the domain was not found in the results the check returned, which can be fewer than `serpDepth`, so it does not prove the domain ranks below `serpDepth`.",
inputSchema,
outputSchema: z
.object({
@@ -82,6 +140,10 @@ export const getRankTrackerTool = {
results: z
.object({
rows: z.array(looseObjectOutputSchema),
+ totalCount: z.number().int().nonnegative(),
+ offset: z.number().int().nonnegative(),
+ limit: z.number().int().positive(),
+ nextOffset: z.number().int().nonnegative().nullable(),
run: z
.object({
id: z.string(),
@@ -112,13 +174,10 @@ export const getRankTrackerTool = {
const text =
configs.length === 0
? "No rank trackers configured for this project."
- : `Rank trackers (${configs.length}):\n` +
- configs
- .map(
- (c) =>
- `- ${c.id} ${c.domain} loc:${c.locationCode}${c.locationName ? ` location:"${c.locationName}"` : ""} schedule:${c.scheduleInterval}`,
- )
- .join("\n");
+ : `Rank trackers (${configs.length}):\n${formatMcpTable(
+ configs,
+ CONFIG_COLUMNS,
+ )}`;
return mcpResponse({
text,
meta: buildProjectMeta(
@@ -134,23 +193,35 @@ export const getRankTrackerTool = {
args.trackerId,
args.projectId,
);
- const allRows = results.rows.map((row) => ({
- ...row,
- googleSerpUrl: googleSerpUrl(row.keyword, config),
- }));
- // Pinned keywords first, as in the app's keyword table.
- const rows = [
- ...allRows.filter((row) => row.pinned),
- ...allRows.filter((row) => !row.pinned),
- ];
+ const offset = args.offset ?? 0;
+ const limit = args.limit ?? 100;
+ // Pinned keywords first, as in the app's keyword table; the stable
+ // tiebreakers keep offset pages from overlapping.
+ const rows = sortBy(
+ results.rows,
+ (row) => (row.pinned ? 0 : 1),
+ (row) => row.keyword,
+ (row) => row.trackingKeywordId,
+ )
+ .slice(offset, offset + limit)
+ .map((row) => ({
+ ...row,
+ googleSerpUrl: googleSerpUrl(row.keyword, config),
+ }));
+ const totalCount = results.rows.length;
+ const nextOffset =
+ offset + rows.length < totalCount ? offset + rows.length : null;
const text = [
- `Tracker ${config.id} (${config.domain}${config.locationName ? `, ${config.locationName}` : ""}):`,
- `Schedule: ${config.scheduleInterval}, devices: ${config.devices}, depth: ${config.serpDepth}`,
+ `Tracker ${config.id} (${config.domain}):`,
+ `Keyword page: offset=${offset}, limit=${limit}, ${rows.length} of ${totalCount} rows.${nextOffset !== null ? ` Next page: offset=${nextOffset}.` : ""} If text is truncated, repeat offset=${offset} with a smaller limit.`,
+ `Schedule: ${config.scheduleInterval}, devices: ${config.devices}, depth: ${config.serpDepth}, location: ${formatLocation(config.locationCode, config.locationName)}, lang: ${config.languageCode}`,
formatLatestRun(results.run),
- `Keywords (${results.rows.length}):`,
- results.rows.length === 0
+ `Keywords (${totalCount}):`,
+ totalCount === 0
? "No keywords tracked yet."
- : formatMcpTable(rows, RANK_RESULT_COLUMNS),
+ : rows.length === 0
+ ? "No keywords at this offset."
+ : formatMcpTable(rows, RANK_RESULT_COLUMNS),
].join("\n");
return mcpResponse({
text,
@@ -159,7 +230,10 @@ export const getRankTrackerTool = {
args.projectId,
`/p/${args.projectId}/rank-tracking/${args.trackerId}`,
),
- structuredContent: { config, results: { ...results, rows } },
+ structuredContent: {
+ config,
+ results: { ...results, rows, totalCount, offset, limit, nextOffset },
+ },
});
}),
};
diff --git a/src/server/mcp/tools/get-serp-results.ts b/src/server/mcp/tools/get-serp-results.ts
index 7ad63069..dd6afd88 100644
--- a/src/server/mcp/tools/get-serp-results.ts
+++ b/src/server/mcp/tools/get-serp-results.ts
@@ -12,7 +12,12 @@ import { withMcpProjectAuth } from "@/server/mcp/project-auth";
import { resolveMarket } from "@/shared/keyword-locations";
import { assertLocalResearchLocation } from "@/server/features/keywords/services/research/local-volume";
import { toolErrorMessage } from "@/server/mcp/tool-error-message";
-import { formatMcpTable, type McpTableColumn } from "@/server/mcp/table";
+import {
+ formatMcpTable,
+ sectionTableBudget,
+ truncatedCell,
+ type McpTableColumn,
+} from "@/server/mcp/table";
import {
languageCodeSchema,
locationCodeSchema,
@@ -38,12 +43,22 @@ const serpItemSchema = z
type SerpItem = z.infer<typeof serpItemSchema>;
+// `type` is load-bearing: the advanced SERP is a mixed list, so without it a
+// featured_snippet or people_also_ask row (which has no domain/title/url) reads
+// as an unlabeled organic position. Snippets are trimmed so the prose column
+// can't dominate the table — the full text stays in structuredContent.
const SERP_ITEM_COLUMNS: McpTableColumn<SerpItem>[] = [
{ header: "rank", value: (item) => item.rank },
+ { header: "type", value: (item) => item.type },
{ header: "organic rank", value: (item) => item.organicRank },
{ header: "domain", value: (item) => item.domain },
{ header: "title", value: (item) => item.title },
{ header: "url", value: (item) => item.url },
+ {
+ header: "description",
+ value: (item) => item.description,
+ format: truncatedCell(120),
+ },
];
const querySchema = z.object({
@@ -201,6 +216,9 @@ export const getSerpResultsTool = {
);
const okCount = results.filter((r) => r.ok).length;
+ // One budget for the whole response: ten queries split it, so a 10 × depth
+ // 100 call can't render 300k characters of text.
+ const budget = sectionTableBudget(results.length);
const text =
results
.map((r) => {
@@ -210,7 +228,7 @@ export const getSerpResultsTool = {
if (r.items.length === 0) {
return `"${r.keyword}" (0 results)`;
}
- return `"${r.keyword}" (${r.items.length} results):\n${formatMcpTable(r.items, SERP_ITEM_COLUMNS)}`;
+ return `"${r.keyword}" (${r.items.length} results):\n${formatMcpTable(r.items, SERP_ITEM_COLUMNS, budget)}`;
})
.join("\n\n") +
`\n\n${okCount} of ${results.length} queries succeeded.`;
diff --git a/src/server/mcp/tools/google-analytics-tools.test.ts b/src/server/mcp/tools/google-analytics-tools.test.ts
index e51dbaff..1e1af7d8 100644
--- a/src/server/mcp/tools/google-analytics-tools.test.ts
+++ b/src/server/mcp/tools/google-analytics-tools.test.ts
@@ -1,11 +1,15 @@
+/* eslint-disable max-lines, max-lines-per-function -- one spec covers every GA4 MCP tool */
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 * as tools from "./google-analytics-tools";
-import { makeToolContext } from "./tool-test-support";
+import { makeToolContext, textContent } from "./tool-test-support";
const mocks = vi.hoisted(() => ({
runReport: vi.fn(),
+ getOrganicOverview: vi.fn(),
+ getMeasurementHealth: vi.fn(),
+ getOpportunities: vi.fn(),
getProjectForOrganization: vi.fn(),
}));
@@ -16,13 +20,17 @@ vi.mock("@/server/features/ga4/services/Ga4ReportingService", () => ({
},
}));
vi.mock("@/server/features/ga4/services/Ga4OrganicOverviewService", () => ({
- Ga4OrganicOverviewService: { getOrganicOverview: vi.fn() },
+ Ga4OrganicOverviewService: {
+ getOrganicOverview: mocks.getOrganicOverview,
+ },
}));
vi.mock("@/server/features/ga4/services/Ga4MeasurementHealthService", () => ({
- Ga4MeasurementHealthService: { getMeasurementHealth: vi.fn() },
+ Ga4MeasurementHealthService: {
+ getMeasurementHealth: mocks.getMeasurementHealth,
+ },
}));
vi.mock("@/server/features/ga4/services/SearchOpportunityService", () => ({
- SearchOpportunityService: { getOpportunities: vi.fn() },
+ SearchOpportunityService: { getOpportunities: mocks.getOpportunities },
}));
vi.mock("@/server/features/projects/services/ProjectService", () => ({
ProjectService: {
@@ -186,4 +194,231 @@ describe("Google Analytics MCP tools", () => {
},
});
});
+
+ it("returns the cross-source opportunity envelope and renders ranked rows", async () => {
+ mocks.getOpportunities.mockResolvedValue({
+ status: "ok",
+ rowCount: 2,
+ totalCandidateRows: 2,
+ request: {
+ dateRange: { startDate: "2026-07-01", endDate: "2026-07-28" },
+ },
+ rows: [
+ {
+ page: "https://example.com/a",
+ clicks: 12,
+ impressions: 900,
+ ctr: 0.013,
+ position: 8.4,
+ joinStatus: "joined",
+ ga4: { sessions: 40, keyEvents: 3, engagementRate: 0.62 },
+ score: 90,
+ },
+ {
+ page: "https://example.com/b",
+ clicks: 1,
+ impressions: 120,
+ ctr: 0.008,
+ position: 14,
+ joinStatus: "gsc_only",
+ ga4: null,
+ score: null,
+ },
+ ],
+ coverage: { matchedRows: 1 },
+ });
+ const { getSearchOpportunitiesTool } = tools;
+ const result = await getSearchOpportunitiesTool.handler(
+ { projectId: "project_1", limit: 25 },
+ toolContext,
+ );
+ expect(mocks.getOpportunities).toHaveBeenCalledWith({
+ projectId: "project_1",
+ limit: 25,
+ });
+ expect(result.structuredContent).toMatchObject({
+ status: "ok",
+ rowCount: 2,
+ totalCandidateRows: 2,
+ });
+ expect(textContent(result)).toEqual(
+ [
+ "Search opportunities for 2026-07-01 through 2026-07-28: 2 returned from 2 candidates. 1 candidates matched GA4 landing pages.",
+ "score | page | position | impressions | clicks | CTR | sessions | keyEvents | engagementRate | match",
+ "90 | https://example.com/a | 8.4 | 900 | 12 | 1.3% | 40 | 3 | 0.62 | joined",
+ "— | https://example.com/b | 14.0 | 120 | 1 | 0.8% | — | — | — | gsc_only",
+ ].join("\n"),
+ );
+ });
+
+ it("renders measurement-health issues and the stream inventory", async () => {
+ mocks.getMeasurementHealth.mockResolvedValue({
+ status: "ok",
+ summary: { webStreamCount: 1, keyEventCount: 1, issueCount: 1 },
+ issues: ["site_search_measurement_disabled"],
+ webStreams: [
+ {
+ streamId: "111",
+ displayName: "Example site",
+ measurementId: "G-ABC123",
+ defaultUri: "https://example.com",
+ enhancedMeasurement: {
+ streamEnabled: true,
+ siteSearchEnabled: false,
+ },
+ },
+ ],
+ otherStreams: [],
+ keyEvents: [{ eventName: "purchase", countingMethod: "ONCE_PER_EVENT" }],
+ customDefinitions: {
+ dimensions: [
+ { parameterName: "plan", displayName: "Plan", scope: "EVENT" },
+ ],
+ metrics: [],
+ },
+ });
+ const { getGoogleAnalyticsMeasurementHealthTool } = tools;
+ const result = await getGoogleAnalyticsMeasurementHealthTool.handler(
+ { projectId: "project_1" },
+ toolContext,
+ );
+ expect(textContent(result)).toEqual(
+ [
+ "Measurement health: 1 web stream(s), 1 key event(s), and 1 diagnostic issue(s). Issues: site_search_measurement_disabled.",
+ "Web streams:",
+ "streamId | displayName | measurementId | defaultUri | enhancedMeasurement | siteSearch",
+ "111 | Example site | G-ABC123 | https://example.com | yes | no",
+ "Key events:",
+ "eventName | countingMethod | custom",
+ "purchase | ONCE_PER_EVENT | no",
+ "Custom dimensions:",
+ "parameterName | displayName | scope",
+ "plan | Plan | EVENT",
+ ].join("\n"),
+ );
+ });
+
+ it("renders report diagnostics and previous-period deltas", async () => {
+ mocks.runReport.mockResolvedValue(
+ makeGa4ReportResult({
+ rowCount: 1,
+ totalRowCount: 1,
+ rows: [{ sessionDefaultChannelGroup: "Organic Search", sessions: 120 }],
+ request: {
+ reportKind: "traffic_acquisition",
+ channel: "all",
+ dimensions: ["sessionDefaultChannelGroup"],
+ metrics: ["sessions"],
+ },
+ diagnostics: [
+ {
+ code: "attribution_not_set_share_high",
+ severity: "warning",
+ message: "A notable share of sessions has no source/medium.",
+ evidence: { sessions: 30, totalSessions: 150, share: 0.2 },
+ },
+ ],
+ comparison: {
+ previousDateRange: {
+ startDate: "2026-06-11",
+ endDate: "2026-07-08",
+ },
+ dimensions: ["sessionDefaultChannelGroup"],
+ metrics: ["sessions"],
+ rows: [
+ {
+ dimensions: { sessionDefaultChannelGroup: "Organic Search" },
+ metrics: {
+ sessions: {
+ current: 120,
+ previous: 100,
+ absoluteChange: 20,
+ percentChange: 0.2,
+ },
+ },
+ },
+ ],
+ coverage: {
+ complete: true,
+ current: { fetchedRowCount: 1, totalRowCount: 1 },
+ previous: { fetchedRowCount: 1, totalRowCount: 1 },
+ },
+ reportMetadata: {
+ hasLimitedData: false,
+ current: makeGa4ReportResult().reportMetadata,
+ previous: makeGa4ReportResult().reportMetadata,
+ },
+ quota: null,
+ },
+ }),
+ );
+
+ const result = await tools.getGoogleAnalyticsTrafficAcquisitionTool.handler(
+ {
+ projectId: "project_1",
+ breakdown: "channel_group",
+ comparePreviousPeriod: true,
+ limit: 100,
+ offset: 0,
+ },
+ toolContext,
+ );
+
+ expect(textContent(result)).toEqual(
+ [
+ "Traffic acquisition: 1 of 1 rows for 2026-07-09 through 2026-08-05.",
+ "sessionDefaultChannelGroup | sessions",
+ "Organic Search | 120",
+ "Diagnostics:",
+ "severity | code | message | evidence",
+ 'warning | attribution_not_set_share_high | A notable share of sessions has no source/medium. | {"sessions":30,"totalSessions":150,"share":0.2}',
+ "Compared with 2026-06-11 through 2026-07-08 (current vs previous):",
+ "sessionDefaultChannelGroup | sessions",
+ "Organic Search | 120 vs 100 (+20.0%)",
+ ].join("\n"),
+ );
+ });
+
+ it("renders the requested overview trend series and its diagnostics", async () => {
+ mocks.getOrganicOverview.mockResolvedValue({
+ status: "ok",
+ request: {
+ resolvedDateRange: { startDate: "2026-07-09", endDate: "2026-08-05" },
+ previousDateRange: { startDate: "2026-06-11", endDate: "2026-07-08" },
+ trend: "weekly",
+ },
+ warnings: [],
+ current: { sessions: 120, keyEvents: 2 },
+ previous: { sessions: 100, keyEvents: 9 },
+ comparison: {},
+ trend: [
+ { yearWeek: "202628", sessions: 60, keyEvents: 1 },
+ { yearWeek: "202629", sessions: 60, keyEvents: 1 },
+ ],
+ diagnostics: [
+ {
+ code: "key_events_sharp_decline",
+ severity: "warning",
+ message: "Organic key events declined sharply.",
+ evidence: { current: 2, previous: 9, percentChange: -0.78 },
+ },
+ ],
+ });
+
+ const result = await tools.getGoogleAnalyticsOrganicOverviewTool.handler(
+ { projectId: "project_1", trend: "weekly" },
+ toolContext,
+ );
+
+ const out = textContent(result);
+ expect(out).toContain(
+ "warning | key_events_sharp_decline | Organic key events declined sharply.",
+ );
+ expect(out).toContain("Weekly trend:");
+ expect(out).toContain(
+ "yearWeek | sessions | activeUsers | engagedSessions | engagementRate | keyEvents | transactions | purchaseRevenue",
+ );
+ expect(out).toContain("202628 | 60 | — | — | — | 1 | — | —");
+ expect(out).toContain("202629 | 60 | — | — | — | 1 | — | —");
+ });
});
diff --git a/src/server/mcp/tools/google-analytics-tools.ts b/src/server/mcp/tools/google-analytics-tools.ts
index 8d0ec479..a16afe01 100644
--- a/src/server/mcp/tools/google-analytics-tools.ts
+++ b/src/server/mcp/tools/google-analytics-tools.ts
@@ -21,7 +21,15 @@ import { mcpResponse } from "@/server/mcp/formatters";
import { looseObjectOutputSchema } from "@/server/mcp/output-schemas";
import { withMcpProjectAuth } from "@/server/mcp/project-auth";
import { projectIdSchema } from "@/server/mcp/schemas";
-import { formatMcpTable, type McpTableColumn } from "@/server/mcp/table";
+import {
+ formatMcpCell,
+ formatMcpTable,
+ percentCell,
+ positionCell,
+ readPath,
+ truncatedCell,
+ type McpTableColumn,
+} from "@/server/mcp/table";
import { buildDashboardUrl } from "@/server/mcp/urls";
const dateSchema = z
@@ -219,9 +227,96 @@ function errorResponse(
}
type Ga4ReportRow = Ga4ReportResult["rows"][number];
+type Ga4ComparisonRow = NonNullable<
+ Ga4ReportResult["comparison"]
+>["rows"][number];
type Ga4OverviewResult = Awaited<
ReturnType<typeof Ga4OrganicOverviewService.getOrganicOverview>
>;
+type Ga4TrendRow = Ga4OverviewResult["trend"][number];
+type Ga4MeasurementHealthResult = Awaited<
+ ReturnType<typeof Ga4MeasurementHealthService.getMeasurementHealth>
+>;
+type SearchOpportunityResult = Awaited<
+ ReturnType<typeof SearchOpportunityService.getOpportunities>
+>;
+type SearchOpportunityRow = SearchOpportunityResult["rows"][number];
+
+// Comparison rows come from a complete (unpaginated) report, so cap what the
+// text block renders. Rows arrive in current-report order, which GA4 sorts by
+// the report's order metric, so the first rows are the largest ones.
+const COMPARISON_ROW_LIMIT = 50;
+
+/** Leading newline so callers can concatenate sections directly. */
+function section<T>(
+ label: string,
+ rows: readonly T[],
+ columns: readonly McpTableColumn<T>[],
+): string {
+ if (rows.length === 0) return "";
+ return `\n${label}:\n${formatMcpTable(rows, columns)}`;
+}
+
+// Diagnostics are built per report kind, so their element type is a union of
+// record shapes; read the shared fields by path.
+function diagnosticsSection(diagnostics: readonly unknown[]): string {
+ return section("Diagnostics", diagnostics, [
+ { header: "severity", value: (row) => readPath(row, "severity") },
+ { header: "code", value: (row) => readPath(row, "code") },
+ { header: "message", value: (row) => readPath(row, "message") },
+ {
+ header: "evidence",
+ value: (row) => readPath(row, "evidence"),
+ format: truncatedCell(160),
+ },
+ ]);
+}
+
+function deltaCell(value: unknown): string {
+ const current = formatMcpCell(readPath(value, "current"));
+ const previous = formatMcpCell(readPath(value, "previous"));
+ const percent = readPath(value, "percentChange");
+ const change =
+ typeof percent === "number" && Number.isFinite(percent)
+ ? ` (${percent > 0 ? "+" : ""}${percentCell(percent)})`
+ : "";
+ return `${current} vs ${previous}${change}`;
+}
+
+function comparisonSection(comparison: Ga4ReportResult["comparison"]): string {
+ if (!comparison) return "";
+ // A requested comparison that came back empty must still be distinguishable
+ // from one that was never requested.
+ if (comparison.rows.length === 0) {
+ return "\nPrevious-period comparison returned no rows.";
+ }
+ const rows = comparison.rows.slice(0, COMPARISON_ROW_LIMIT);
+ const truncated =
+ comparison.rows.length > rows.length
+ ? `, top ${rows.length} of ${comparison.rows.length} rows`
+ : "";
+ const range = comparison.previousDateRange;
+ const columns: McpTableColumn<Ga4ComparisonRow>[] = [
+ ...comparison.dimensions.map(
+ (dimension): McpTableColumn<Ga4ComparisonRow> => ({
+ header: dimension,
+ value: (row) => row.dimensions[dimension],
+ }),
+ ),
+ ...comparison.metrics.map(
+ (metric): McpTableColumn<Ga4ComparisonRow> => ({
+ header: metric,
+ value: (row) => row.metrics[metric],
+ format: deltaCell,
+ }),
+ ),
+ ];
+ return section(
+ `Compared with ${range.startDate} through ${range.endDate} (current vs previous${truncated})`,
+ rows,
+ columns,
+ );
+}
// These four MCP tools accept channel=all. landing_pages is Organic Search
// only and has no channel argument.
@@ -268,22 +363,39 @@ function endDateClampNote(result: {
function reportText(label: string, result: Ga4ReportResult) {
const range = result.request.resolvedDateRange;
- const comparison = result.comparison
- ? ` Previous-period comparison returned ${result.comparison.rows.length} row(s).`
- : "";
- const diagnostics =
- result.diagnostics.length > 0
- ? ` ${result.diagnostics.length} diagnostic finding(s) are included.`
- : "";
const limited = result.reportMetadata.hasLimitedData
? " Google marked this report as limited; inspect reportMetadata."
: "";
const paginate = result.pageInfo.hasMore
? " More rows are available; call again with offset to page through them."
: "";
- const summary = `${label}: ${result.rowCount} of ${result.totalRowCount} rows for ${range.startDate} through ${range.endDate}.${endDateClampNote(result)}${comparison}${diagnostics}${limited}${emptyOrganicHint(result)}${paginate}`;
- if (result.rows.length === 0) return summary;
- return `${summary}\n${formatMcpTable(result.rows, reportTableColumns(result))}`;
+ const summary = `${label}: ${result.rowCount} of ${result.totalRowCount} rows for ${range.startDate} through ${range.endDate}.${endDateClampNote(result)}${limited}${emptyOrganicHint(result)}${paginate}`;
+ const rows =
+ result.rows.length === 0
+ ? ""
+ : `\n${formatMcpTable(result.rows, reportTableColumns(result))}`;
+ // Rows stay adjacent to the summary line that counts them; the labelled
+ // sections follow so neither table can be mistaken for the other.
+ return `${summary}${rows}${diagnosticsSection(result.diagnostics)}${comparisonSection(result.comparison)}`;
+}
+
+function trendSection(result: Ga4OverviewResult): string {
+ const weekly = result.request.trend === "weekly";
+ const dimension = weekly ? "yearWeek" : "date";
+ const columns: McpTableColumn<Ga4TrendRow>[] = [
+ { header: dimension, value: (row) => row[dimension] },
+ ...OVERVIEW_METRICS.map(
+ (metric): McpTableColumn<Ga4TrendRow> => ({
+ header: metric,
+ value: (row) => row[metric],
+ }),
+ ),
+ ];
+ return section(
+ weekly ? "Weekly trend" : "Daily trend",
+ result.trend,
+ columns,
+ );
}
function overviewText(result: Ga4OverviewResult) {
@@ -301,11 +413,76 @@ function overviewText(result: Ga4OverviewResult) {
current: result.current[metric] ?? null,
previous: result.previous?.[metric] ?? null,
}));
- return `${summary}\n${formatMcpTable(rows, [
+ const totals = formatMcpTable(rows, [
{ header: "metric", value: (row) => row.metric },
{ header: "current", value: (row) => row.current },
{ header: "previous", value: (row) => row.previous },
- ])}`;
+ ]);
+ return `${summary}\n${totals}${diagnosticsSection(result.diagnostics)}${trendSection(result)}`;
+}
+
+const OPPORTUNITY_COLUMNS: McpTableColumn<SearchOpportunityRow>[] = [
+ { header: "score", value: (row) => row.score },
+ { header: "page", value: (row) => row.page },
+ { header: "position", value: (row) => row.position, format: positionCell },
+ { header: "impressions", value: (row) => row.impressions },
+ { header: "clicks", value: (row) => row.clicks },
+ { header: "CTR", value: (row) => row.ctr, format: percentCell },
+ { header: "sessions", value: (row) => row.ga4?.sessions },
+ { header: "keyEvents", value: (row) => row.ga4?.keyEvents },
+ { header: "engagementRate", value: (row) => row.ga4?.engagementRate },
+ { header: "match", value: (row) => row.joinStatus },
+];
+
+function opportunityText(result: SearchOpportunityResult) {
+ const range = result.request.dateRange;
+ const summary = `Search opportunities for ${range.startDate} through ${range.endDate}: ${result.rowCount} returned from ${result.totalCandidateRows} candidates. ${result.coverage.matchedRows} candidates matched GA4 landing pages.`;
+ if (result.rows.length === 0) return summary;
+ return `${summary}\n${formatMcpTable(result.rows, OPPORTUNITY_COLUMNS)}`;
+}
+
+function measurementHealthText(result: Ga4MeasurementHealthResult) {
+ const summary = `Measurement health: ${result.summary.webStreamCount} web stream(s), ${result.summary.keyEventCount} key event(s), and ${result.summary.issueCount} diagnostic issue(s).`;
+ const issues =
+ result.issues.length > 0 ? ` Issues: ${result.issues.join(", ")}.` : "";
+ return [
+ `${summary}${issues}`,
+ section("Web streams", result.webStreams, [
+ { header: "streamId", value: (row) => row.streamId },
+ { header: "displayName", value: (row) => row.displayName },
+ { header: "measurementId", value: (row) => row.measurementId },
+ { header: "defaultUri", value: (row) => row.defaultUri },
+ {
+ header: "enhancedMeasurement",
+ value: (row) => row.enhancedMeasurement.streamEnabled,
+ },
+ {
+ header: "siteSearch",
+ value: (row) => row.enhancedMeasurement.siteSearchEnabled,
+ },
+ ]),
+ section("Other streams", result.otherStreams, [
+ { header: "streamId", value: (row) => row.streamId },
+ { header: "type", value: (row) => row.type },
+ { header: "displayName", value: (row) => row.displayName },
+ ]),
+ section("Key events", result.keyEvents, [
+ { header: "eventName", value: (row) => row.eventName },
+ { header: "countingMethod", value: (row) => row.countingMethod },
+ { header: "custom", value: (row) => row.custom ?? false },
+ ]),
+ section("Custom dimensions", result.customDefinitions.dimensions, [
+ { header: "parameterName", value: (row) => row.parameterName },
+ { header: "displayName", value: (row) => row.displayName },
+ { header: "scope", value: (row) => row.scope },
+ ]),
+ section("Custom metrics", result.customDefinitions.metrics, [
+ { header: "parameterName", value: (row) => row.parameterName },
+ { header: "displayName", value: (row) => row.displayName },
+ { header: "scope", value: (row) => row.scope },
+ { header: "measurementUnit", value: (row) => row.measurementUnit },
+ ]),
+ ].join("");
}
function createAnalyticsReportHandler<TArgs extends ProjectArgs>(
@@ -449,7 +626,7 @@ export const getSearchOpportunitiesTool = {
try {
const result = await SearchOpportunityService.getOpportunities(args);
return mcpResponse({
- text: `Search opportunities: ${result.rowCount} returned from ${result.totalCandidateRows} candidates. ${result.coverage.matchedRows} candidates matched GA4 landing pages.`,
+ text: opportunityText(result),
meta: buildProjectMeta(context, args.projectId),
structuredContent: result,
});
@@ -659,7 +836,7 @@ export const getGoogleAnalyticsMeasurementHealthTool = {
args.projectId,
);
return mcpResponse({
- text: `Measurement health: ${result.summary.webStreamCount} web stream(s), ${result.summary.keyEventCount} key event(s), and ${result.summary.issueCount} diagnostic issue(s).`,
+ text: measurementHealthText(result),
meta: buildProjectMeta(context, args.projectId),
structuredContent: result,
});
diff --git a/src/server/mcp/tools/local-seo-tools.test.ts b/src/server/mcp/tools/local-seo-tools.test.ts
index df19ba86..ecfec586 100644
--- a/src/server/mcp/tools/local-seo-tools.test.ts
+++ b/src/server/mcp/tools/local-seo-tools.test.ts
@@ -223,9 +223,12 @@ describe("get_business_reviews", () => {
taskId: "extended:task-9",
});
const out = textContent(result);
- expect(out).toContain("# | when | rating | author | source | review");
+ expect(out).toContain(
+ "# | when | rating | author | source | review | owner reply",
+ );
expect(out).toContain("Rare bottles and great staff.");
- expect(out).toContain("| yes");
+ // The owner's own words, not a yes/no — answering reviews reads them.
+ expect(out).toContain("| Thanks!");
await expect(
getBusinessReviewsTool.handler(
@@ -324,7 +327,11 @@ describe("get_local_rank_grid", () => {
},
matchedBusiness: { title: "Acme Cafe", cid: "123", placeId: "p1" },
});
- expect(textContent(result)).toContain(" 2 2 2");
+ const out = textContent(result);
+ expect(out).toContain(" 2 2 2");
+ expect(out).toContain(
+ "Matched business: Acme Cafe (cid 123, place_id p1).",
+ );
});
it("records each point's result count and top business so nulls are interpretable", async () => {
@@ -341,6 +348,15 @@ describe("get_local_rank_grid", () => {
topResult: { title: "Other Cafe", cid: "999" },
}),
);
+ // A text-only client reads the same context: the ASCII grid alone can't
+ // tell "outranked" from "nobody ranked here".
+ const out = textContent(result);
+ expect(out).toContain(
+ "row | col | lat | lon | rank | results | top result",
+ );
+ expect(out).toContain(
+ "0 | 0 | 40.0180874 | -74.0234532 | — | 1 | Other Cafe | 999",
+ );
});
it("falls back to a case-insensitive title match", async () => {
diff --git a/src/server/mcp/tools/local-seo-tools.ts b/src/server/mcp/tools/local-seo-tools.ts
index d51a35c5..2e4efa70 100644
--- a/src/server/mcp/tools/local-seo-tools.ts
+++ b/src/server/mcp/tools/local-seo-tools.ts
@@ -35,6 +35,7 @@ import {
businessIdentifierInputSchema,
businessIdentifierKeyword,
formatBusinessDataCoordinate,
+ formatCoordinate,
formatLocalSerpCoordinate,
pickRowFields,
resolveBusinessIdentifier,
@@ -220,7 +221,7 @@ export const getBusinessProfileTool = {
config: {
title: "Get business profile",
description:
- "Reads one Google Business Profile: categories, rating and review count, rating breakdown, address, phone, website, claimed status, opening hours, and photo count. Use it to audit your own profile or to compare a competitor's. Charges credits.",
+ "Reads one Google Business Profile by name, cid, or placeId: categories, rating and review count, rating breakdown, address, phone, website, claimed status, opening hours, and photo count. Use it to audit your own profile, to compare a named competitor's, or to check whether a business has a Google Business Profile at all — it is the cheapest tool for that question, less than half the credits of search_local_businesses. For identity or existence checks, reuse a business already present in your search results. Fetch the full profile when you need missing details such as opening hours or rating breakdown. Charges credits.",
inputSchema: getBusinessProfileInputSchema,
outputSchema: z.looseObject({
profile: looseObjectOutputSchema.nullable(),
@@ -350,14 +351,17 @@ const REVIEW_COLUMNS: McpTableColumn<unknown>[] = [
header: "source",
value: (row) => readPath(row, "source", "title") ?? "Google",
},
+ // Review-gap analysis reads the prose, and answering reviews reads what the
+ // owner already said — both need the text itself, not a length-safe stub.
{
header: "review",
value: (row) => readPath(row, "review_text"),
- format: truncatedCell(120),
+ format: truncatedCell(300),
},
{
- header: "owner replied",
- value: (row) => readPath(row, "owner_answer") != null,
+ header: "owner reply",
+ value: (row) => readPath(row, "owner_answer"),
+ format: truncatedCell(200),
},
];
@@ -366,7 +370,7 @@ export const getBusinessReviewsTool = {
config: {
title: "Get business reviews",
description:
- "Collects Google reviews for a business, with rating, author, text, and whether the owner replied. Use it for review-gap analysis against competitors and to spot unanswered reviews. Usually completes within this call; if the queued job is still running you get status 'processing' plus a taskId — call again with that taskId in 30-60 seconds to collect the result at no extra cost. Charges credits.",
+ "Collects Google reviews for a business, with rating, author, text, and the owner's reply. Use it for review-gap analysis against competitors and to spot unanswered reviews. Usually completes within this call; if the queued job is still running you get status 'processing' plus a taskId — call again with that taskId in 30-60 seconds to collect the result at no extra cost. Charges credits.",
inputSchema: getBusinessReviewsInputSchema,
outputSchema: z.looseObject({
status: z.enum(["completed", "processing"]),
@@ -435,7 +439,7 @@ export const getBusinessReviewsTool = {
text:
reviews.length === 0
? `${header} This profile has no reviews matching the request.`
- : `${header} Review text is truncated in this table; full text is in the structured result.\n${formatMcpTable(reviews, REVIEW_COLUMNS)}`,
+ : `${header} Reviews longer than 300 characters and owner replies longer than 200 end in "…" (full text in structuredContent).\n${formatMcpTable(reviews, REVIEW_COLUMNS)}`,
meta: buildProjectMeta(context, args.projectId, `/p/${args.projectId}`),
structuredContent: {
status: "completed",
@@ -488,18 +492,33 @@ const BUSINESS_UPDATE_ROW_FIELDS = [
"links",
] as const;
+/** Post CTA links as "title → url"; the raw array would land in the cell as
+ * JSON, and the CTA target is the point of auditing offers and events. */
+function formatPostLinks(links: unknown): string {
+ if (!Array.isArray(links) || links.length === 0) return "—";
+ const rendered = links.map((link) => {
+ const url = readString(link, "url");
+ const title = readString(link, "title") ?? readString(link, "type");
+ if (url == null) return title ?? "";
+ return title == null ? url : `${title} → ${url}`;
+ });
+ return rendered.filter((entry) => entry !== "").join("; ") || "—";
+}
+
const BUSINESS_UPDATE_COLUMNS: McpTableColumn<unknown>[] = [
{ header: "#", value: (row) => readPath(row, "rank_absolute") },
{
header: "posted",
value: (row) => readPath(row, "post_date") ?? readPath(row, "timestamp"),
},
+ { header: "author", value: (row) => readPath(row, "author") },
{
header: "post",
value: (row) => readPath(row, "post_text") ?? readPath(row, "snippet"),
- format: truncatedCell(120),
+ format: truncatedCell(300),
},
{ header: "url", value: (row) => readPath(row, "url") },
+ { header: "links", value: (row) => formatPostLinks(readPath(row, "links")) },
];
export const getBusinessUpdatesTool = {
@@ -561,7 +580,7 @@ export const getBusinessUpdatesTool = {
text:
updates.length === 0
? `${header} This profile has published no posts.`
- : `${header}\n${formatMcpTable(updates, BUSINESS_UPDATE_COLUMNS)}`,
+ : `${header} Posts longer than 300 characters end in "…" (full text in structuredContent).\n${formatMcpTable(updates, BUSINESS_UPDATE_COLUMNS)}`,
meta: buildProjectMeta(context, args.projectId, `/p/${args.projectId}`),
structuredContent: { status: "completed", taskId, updates },
});
@@ -795,6 +814,12 @@ type GridPoint = {
longitude: number;
};
+type MatchedBusiness = {
+ title: string | null;
+ cid: string | null;
+ placeId: string | null;
+};
+
type GridPointResult = GridPoint & {
rank: number | null;
// How many businesses the SERP returned there, and who ranked first: a null
@@ -897,6 +922,34 @@ function renderGrid(results: GridPointResult[], gridSize: number): string {
return lines.join("\n");
}
+// The map above is only ranks, so every cell's context — where the point is,
+// how contested it was, who won it — lives here. Coordinates are pre-formatted
+// because formatMcpCell's 2-decimal rounding would move a point by kilometres.
+const GRID_POINT_COLUMNS: McpTableColumn<GridPointResult>[] = [
+ { header: "row", value: (point) => point.row },
+ { header: "col", value: (point) => point.col },
+ { header: "lat", value: (point) => formatCoordinate(point.latitude) },
+ { header: "lon", value: (point) => formatCoordinate(point.longitude) },
+ {
+ header: "rank",
+ value: (point) => (point.error ? "search failed" : point.rank),
+ },
+ { header: "results", value: (point) => point.resultsCount },
+ {
+ header: "top result",
+ value: (point) => point.topResult?.title,
+ format: truncatedCell(60),
+ },
+ { header: "top cid", value: (point) => point.topResult?.cid },
+];
+
+function formatMatchedBusiness(business: MatchedBusiness | null): string {
+ if (!business) {
+ return "Matched business: none — the target was not found at any point, so no point has a rank.";
+ }
+ return `Matched business: ${formatMcpCell(business.title)} (cid ${formatMcpCell(business.cid)}, place_id ${formatMcpCell(business.placeId)}).`;
+}
+
export const getLocalRankGridTool = {
name: "get_local_rank_grid",
config: {
@@ -1053,11 +1106,7 @@ export const getLocalRankGridTool = {
);
}
- let matchedBusiness: {
- title: string | null;
- cid: string | null;
- placeId: string | null;
- } | null = null;
+ let matchedBusiness: MatchedBusiness | null = null;
const grid = points.map((point, index): GridPointResult => {
const outcome = outcomes[index];
if (outcome.status !== "completed") {
@@ -1107,11 +1156,14 @@ export const getLocalRankGridTool = {
const text = [
`Local rank grid for "${args.keyword}" (${gridSize}x${gridSize}, ${spacingKm} km spacing, zoom ${zoom}, top ${RANK_GRID_DEPTH} checked).`,
- `Rank per point, north at the top ("–" = not among the results returned there; check that point's resultsCount and topResult before reading it as outranked, "x" = search failed but may still be charged):`,
+ formatMatchedBusiness(matchedBusiness),
+ `Rank per point, north at the top ("–" = not among the results returned there, "x" = search failed but may still be charged):`,
renderGrid(grid, gridSize),
`- ranked at ${summary.pointsFound} of ${summary.pointsSearched} points`,
`- average rank where found: ${summary.averageRank ?? "—"}`,
`- top 3 at ${summary.top3Count} points, top 10 at ${summary.top10Count} points`,
+ `Every point (row 0 = north edge, col 0 = west edge). An empty rank next to a full results count means outranked there; next to a small count it means the SERP was sparse:`,
+ formatMcpTable(grid, GRID_POINT_COLUMNS),
].join("\n");
return mcpResponse({
diff --git a/src/server/mcp/tools/research-keywords.ts b/src/server/mcp/tools/research-keywords.ts
index 2120dd41..4a6f09f6 100644
--- a/src/server/mcp/tools/research-keywords.ts
+++ b/src/server/mcp/tools/research-keywords.ts
@@ -9,7 +9,11 @@ import {
} from "@/server/mcp/output-schemas";
import { withMcpProjectAuth } from "@/server/mcp/project-auth";
import { resolveMarket } from "@/shared/keyword-locations";
-import { formatMcpTable, type McpTableColumn } from "@/server/mcp/table";
+import {
+ formatMcpTable,
+ sectionTableBudget,
+ type McpTableColumn,
+} from "@/server/mcp/table";
import { assertLanguageForLocation } from "@/server/lib/market";
import { toolErrorMessage } from "@/server/mcp/tool-error-message";
import {
@@ -188,6 +192,8 @@ export const researchKeywordsTool = {
const okCount = results.filter((r) => r.ok).length;
const failCount = results.length - okCount;
+ // One text budget for the whole response, split across the seeds.
+ const budget = sectionTableBudget(results.length);
const text =
results
.map((r) => {
@@ -201,7 +207,7 @@ export const researchKeywordsTool = {
if (r.rowCount === 0) {
return `${header}\n(no keywords returned)`;
}
- return `${header}\n${formatMcpTable(r.rows, RESEARCH_COLUMNS)}`;
+ return `${header}\n${formatMcpTable(r.rows, RESEARCH_COLUMNS, budget)}`;
})
.join("\n\n") +
`\n\nResearched ${okCount} of ${results.length} seeds${failCount > 0 ? ` (${failCount} failed)` : ""}. Columns: volume = monthly searches, KD = keyword difficulty (0-100), CPC in USD, competition = paid competition (0-1); "—" = unavailable. Google Ads close variants may share search volumes; do not add their volumes together.`;
diff --git a/src/server/mcp/tools/search-console-tools.test.ts b/src/server/mcp/tools/search-console-tools.test.ts
index 98dabb2e..f6bcf4b6 100644
--- a/src/server/mcp/tools/search-console-tools.test.ts
+++ b/src/server/mcp/tools/search-console-tools.test.ts
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { GscApiError, GscNotConnectedError } from "@/server/lib/gscErrors";
import * as searchConsoleTools from "./search-console-tools";
-import { makeToolContext } from "./tool-test-support";
+import { makeToolContext, textContent } from "./tool-test-support";
const mocks = vi.hoisted(() => ({
getProjectForOrganization: vi.fn(),
@@ -244,6 +244,72 @@ describe("search console MCP tools", () => {
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"),
diff --git a/src/server/mcp/tools/search-console-tools.ts b/src/server/mcp/tools/search-console-tools.ts
index 6680b650..58f41f83 100644
--- a/src/server/mcp/tools/search-console-tools.ts
+++ b/src/server/mcp/tools/search-console-tools.ts
@@ -4,7 +4,12 @@ import { buildProjectMeta } from "@/server/mcp/context";
import { mcpResponse } from "@/server/mcp/formatters";
import { optionalMetaOutputSchema } from "@/server/mcp/output-schemas";
import { withMcpProjectAuth } from "@/server/mcp/project-auth";
-import { formatMcpTable, type McpTableColumn } from "@/server/mcp/table";
+import {
+ formatMcpTable,
+ percentCell,
+ positionCell,
+ type McpTableColumn,
+} from "@/server/mcp/table";
import { projectIdSchema } from "@/server/mcp/schemas";
import { buildDashboardUrl } from "@/server/mcp/urls";
import { hasGoogleOAuthConfig } from "@/server/features/google/oauth-config";
@@ -25,8 +30,6 @@ import {
} from "@/server/lib/gscErrors";
import { GSC_SELF_HOSTED_SETUP_DOCS_URL } from "@/shared/gsc";
-const TEXT_SUMMARY_ROWS = 15;
-
type GscPerfRow = {
keys?: string[];
clicks: number;
@@ -39,17 +42,8 @@ const GSC_PERF_COLUMNS: McpTableColumn<GscPerfRow>[] = [
{ header: "key", value: (row) => row.keys?.join(" / ") ?? "(total)" },
{ header: "clicks", value: (row) => row.clicks },
{ header: "impressions", value: (row) => row.impressions },
- {
- header: "CTR",
- value: (row) => row.ctr,
- format: (value) =>
- typeof value === "number" ? `${(value * 100).toFixed(1)}%` : "—",
- },
- {
- header: "position",
- value: (row) => row.position,
- format: (value) => (typeof value === "number" ? value.toFixed(1) : "—"),
- },
+ { header: "CTR", value: (row) => row.ctr, format: percentCell },
+ { header: "position", value: (row) => row.position, format: positionCell },
];
type ProjectAuthContext = {
@@ -357,7 +351,7 @@ export const getSearchConsolePerformanceTool = {
: "";
const header =
`${result.siteUrl} · ${dimensions.join("+")} · ${result.request.startDate}→${result.request.endDate} · ` +
- `${rows.length} row${rows.length === 1 ? "" : "s"}${filterText}${hasMore ? " (more available — paginate with startRow)" : ""}`;
+ `${rows.length} row${rows.length === 1 ? "" : "s"}${filterText}${hasMore ? ` (more available — call again with startRow=${nextStartRow})` : ""}`;
const text =
rows.length > 0
? `${header}\n${formatMcpTable(rows, GSC_PERF_COLUMNS)}`
@@ -397,6 +391,88 @@ export const getSearchConsolePerformanceTool = {
// inspect_urls
// ---------------------------------------------------------------------------
+const INSPECT_LIST_PREVIEW = 2;
+
+type UrlInspection = Awaited<
+ ReturnType<typeof GscService.inspectUrls>
+>["results"][number];
+
+/** Join `label: value` pairs into one compact line, dropping pairs Google
+ * didn't report. Returns undefined when nothing survives, so the caller can
+ * skip the line entirely instead of printing empty labels. */
+function detailLine(pairs: [string, string | undefined][]): string | undefined {
+ const rendered = pairs
+ .filter((pair): pair is [string, string] => Boolean(pair[1]))
+ .map(([label, value]) => `${label}: ${value}`);
+ return rendered.length > 0 ? rendered.join(" · ") : undefined;
+}
+
+/** Show the first couple of URLs plus a count so sitemap/referrer lists can't
+ * dominate the block (the full arrays stay in structuredContent). */
+function listPreview(values: string[] | undefined): string | undefined {
+ if (!values || values.length === 0) return undefined;
+ const shown = values.slice(0, INSPECT_LIST_PREVIEW).join(", ");
+ const rest = values.length - INSPECT_LIST_PREVIEW;
+ return rest > 0 ? `${values.length} (${shown}, +${rest} more)` : shown;
+}
+
+/** A Google-selected canonical that differs from the declared one is the usual
+ * answer to "why isn't my page indexed?", so call the mismatch out. */
+function canonicalSummary(
+ google: string | undefined,
+ user: string | undefined,
+): string | undefined {
+ if (google && user) {
+ return google === user
+ ? `${google} (declared canonical matches)`
+ : `MISMATCH — Google selected ${google}, page declares ${user}`;
+ }
+ if (google) return `Google selected ${google} (no declared canonical)`;
+ if (user) return `page declares ${user}`;
+ return undefined;
+}
+
+/** One block per inspected URL: the headline verdict plus the fields an SEO
+ * acts on. Issue lists stay in structuredContent; sitemaps and referring
+ * URLs are previewed. */
+function inspectionBlock(inspection: UrlInspection): string {
+ if (inspection.error) return `${inspection.url} — error: ${inspection.error}`;
+ if (!inspection.result) {
+ return `${inspection.url} — no inspection result returned.`;
+ }
+
+ const index = inspection.result.indexStatusResult;
+ const headline = `${inspection.url} — ${index?.verdict ?? "UNKNOWN"}: ${index?.coverageState ?? "no coverage state reported"}`;
+ const lines = [
+ detailLine([
+ ["robots.txt", index?.robotsTxtState],
+ ["indexing", index?.indexingState],
+ ["page fetch", index?.pageFetchState],
+ ]),
+ detailLine([
+ ["last crawl", index?.lastCrawlTime],
+ ["crawled as", index?.crawledAs],
+ ]),
+ detailLine([
+ [
+ "canonical",
+ canonicalSummary(index?.googleCanonical, index?.userCanonical),
+ ],
+ ]),
+ detailLine([
+ ["mobile usability", inspection.result.mobileUsabilityResult?.verdict],
+ ["rich results", inspection.result.richResultsResult?.verdict],
+ ]),
+ detailLine([
+ ["sitemaps", listPreview(index?.sitemap)],
+ ["referring URLs", listPreview(index?.referringUrls)],
+ ]),
+ detailLine([["details", inspection.result.inspectionResultLink]]),
+ ].filter((line) => line !== undefined);
+
+ return [headline, ...lines.map((line) => ` ${line}`)].join("\n");
+}
+
const inspectInputSchema = {
projectId: projectIdSchema,
urls: z
@@ -467,19 +543,10 @@ export const inspectUrlsTool = {
languageCode: args.languageCode,
});
- const summaryLines = results.slice(0, TEXT_SUMMARY_ROWS).map((r) => {
- if (r.error) return ` ${r.url} — error: ${r.error}`;
- const index = r.result?.indexStatusResult;
- const verdict = index?.verdict ?? "UNKNOWN";
- const coverage = index?.coverageState ?? "—";
- const canonical = index?.googleCanonical
- ? `, google-canonical ${index.googleCanonical}`
- : "";
- return ` ${r.url} — ${verdict}: ${coverage}${canonical}`;
- });
+ const blocks = results.map(inspectionBlock);
const text =
- `${siteUrl} · inspected ${results.length} URL${results.length === 1 ? "" : "s"}\n` +
- summaryLines.join("\n");
+ `${siteUrl} · inspected ${results.length} URL${results.length === 1 ? "" : "s"}\n\n` +
+ blocks.join("\n\n");
return mcpResponse({
text,
diff --git a/src/server/mcp/tools/site-audit-tools.ts b/src/server/mcp/tools/site-audit-tools.ts
index d84f4f4e..d9016745 100644
--- a/src/server/mcp/tools/site-audit-tools.ts
+++ b/src/server/mcp/tools/site-audit-tools.ts
@@ -1,3 +1,4 @@
+/* eslint-disable max-lines -- all site-audit MCP tools are intentionally kept in one module */
import { sort } from "remeda";
import { z } from "zod";
import { AuditRepository } from "@/server/features/audit/repositories/AuditRepository";
@@ -12,6 +13,12 @@ import {
import { PAGE_FETCH_CLASSES } from "@/shared/audit-fetch-class";
import { mcpResponse } from "@/server/mcp/formatters";
import { buildProjectMeta } from "@/server/mcp/context";
+import {
+ formatMcpCell,
+ formatMcpTable,
+ type McpTableColumn,
+ truncatedCell,
+} from "@/server/mcp/table";
import {
looseObjectOutputSchema,
optionalMetaOutputSchema,
@@ -211,7 +218,7 @@ export const getAuditStatusTool = {
? ` The audit stopped early but kept results for the ${status.pagesCrawled} pages it crawled — call get_audit_issues for the partial issue report.`
: "";
return mcpResponse({
- text: `Audit ${status.id} (${status.startUrl}): ${status.status} — phase ${status.currentPhase}, ${status.pagesCrawled}/${status.pagesTotal} pages${lighthouseNote}.${nextStep}`,
+ text: `Audit ${status.id} (${status.startUrl}): ${status.status}${status.errorCode ? ` (${status.errorCode})` : ""} — phase ${status.currentPhase}, ${status.pagesCrawled}/${status.pagesTotal} pages${lighthouseNote}.${nextStep}`,
meta: buildProjectMeta(
context,
args.projectId,
@@ -224,6 +231,28 @@ export const getAuditStatusTool = {
// ─── get_audit_issues ────────────────────────────────────────────────────────
+// Text-only clients read just the text block, so each issue type renders its
+// remediation steps plus a bounded sample of affected URLs. Every URL of every
+// type would be a data dump; the per-type count keeps the sample honest.
+const ISSUE_SAMPLE_SIZE = 5;
+
+/** Render an issue's parsed details record as ` (statusCode: 404, length: 12)`. */
+function formatIssueDetails(details: unknown): string {
+ if (typeof details !== "object" || details === null || Array.isArray(details))
+ return "";
+ const parts = Object.entries(details)
+ .filter(([, value]) => value !== null && value !== undefined)
+ .map(
+ ([key, value]) =>
+ `${key}: ${
+ Array.isArray(value)
+ ? value.map(formatMcpCell).join(" → ")
+ : formatMcpCell(value)
+ }`,
+ );
+ return parts.length > 0 ? ` (${parts.join(", ")})` : "";
+}
+
const issuesInputSchema = {
projectId: projectIdSchema,
auditId: auditIdSchema,
@@ -316,20 +345,56 @@ export const getAuditIssuesTool = {
};
});
+ // Sample affected URLs from the returned rows, keyed by issue type; counts
+ // still come from `summary`, which covers every matching row.
+ const samples = new Map<string, typeof issues>();
+ for (const issue of issues) {
+ const sample = samples.get(issue.issueType) ?? [];
+ if (sample.length < ISSUE_SAMPLE_SIZE) sample.push(issue);
+ samples.set(issue.issueType, sample);
+ }
+ let sampled = false;
+
+ const sections = summary.map((entry) => {
+ const shown = samples.get(entry.issueType) ?? [];
+ const remaining = entry.count - shown.length;
+ if (remaining > 0) sampled = true;
+ const howToFix = getIssueDescriptor(entry.issueType)?.howToFix;
+ return [
+ `[${entry.severity}] ${entry.title} (${entry.issueType}): ${entry.count} affected page${entry.count === 1 ? "" : "s"}`,
+ howToFix ? ` Fix: ${howToFix}` : null,
+ ...shown.map(
+ (issue) => ` - ${issue.url}${formatIssueDetails(issue.details)}`,
+ ),
+ // A low-severity type can fall entirely outside the limit-truncated
+ // rows, leaving counts with no rows to sample from.
+ shown.length === 0
+ ? ` (no sample URLs within the first ${limit} issue rows — raise limit to see examples)`
+ : remaining > 0
+ ? ` …and ${remaining} more affected URL${remaining === 1 ? "" : "s"} in this issue.`
+ : null,
+ ]
+ .filter((line) => line !== null)
+ .join("\n");
+ });
+
const text =
rows.length === 0
? args.severity || args.issueType
? `No issues found for audit ${audit.id} matching the given filters.`
: `No issues recorded for audit ${audit.id}. Note: audits run before issue checks existed have no issue data — re-run the audit with run_site_audit to get a real report.`
: [
- `Audit ${audit.id} (${audit.startUrl}): ${rows.length} issues${rows.length > limit ? ` (showing ${limit})` : ""}.`,
- "By type:",
- ...summary.map(
- (entry) =>
- `- [${entry.severity}] ${entry.title} (${entry.issueType}): ${entry.count}`,
- ),
- "Full issue rows with how_to_fix instructions are in structuredContent.issues.",
- ].join("\n");
+ `Audit ${audit.id} (${audit.startUrl}): ${rows.length} issues across ${summary.length} issue type${summary.length === 1 ? "" : "s"}.`,
+ ...sections,
+ sampled
+ ? `Up to ${ISSUE_SAMPLE_SIZE} affected URLs are listed per issue type — open the audit in the dashboard for the full list.`
+ : null,
+ rows.length > limit
+ ? `Structured issue rows are capped at the ${limit} highest-severity issues; raise limit (max 1000) for more.`
+ : null,
+ ]
+ .filter((block) => block !== null)
+ .join("\n\n");
return mcpResponse({
text,
@@ -374,6 +439,29 @@ const pagesInputSchema = {
type PagesArgs = z.infer<z.ZodObject<typeof pagesInputSchema>>;
+type AuditPageRow = Awaited<
+ ReturnType<typeof AuditRepository.getPagesForAudit>
+>[number];
+
+const PAGE_COLUMNS: McpTableColumn<AuditPageRow>[] = [
+ { header: "url", value: (page) => page.url },
+ { header: "status", value: (page) => page.statusCode },
+ { header: "fetch", value: (page) => page.fetchClass },
+ { header: "title", value: (page) => page.title, format: truncatedCell(70) },
+ {
+ header: "description",
+ value: (page) => page.metaDescription,
+ format: truncatedCell(90),
+ },
+ { header: "words", value: (page) => page.wordCount },
+ { header: "indexable", value: (page) => page.isIndexable },
+ { header: "depth", value: (page) => page.crawlDepth },
+ { header: "in sitemap", value: (page) => page.inSitemap },
+ { header: "internal links", value: (page) => page.internalLinkCount },
+ { header: "ms", value: (page) => page.responseTimeMs },
+ { header: "redirect", value: (page) => page.redirectUrl },
+];
+
export const getAuditPagesTool = {
name: "get_audit_pages",
config: {
@@ -408,16 +496,11 @@ export const getAuditPagesTool = {
const limit = args.limit ?? 100;
const pages = filtered.slice(0, limit);
- const text = [
- `Audit ${audit.id}: ${filtered.length} pages${filtered.length > limit ? ` (showing ${limit})` : ""}.`,
- ...pages
- .slice(0, 25)
- .map(
- (page) =>
- `- ${page.statusCode} ${page.url}${page.fetchClass !== "ok" ? ` [${page.fetchClass}]` : ""} "${page.title ?? ""}"`,
- ),
- "Full rows are in structuredContent.pages.",
- ].join("\n");
+ const header = `Audit ${audit.id}: ${filtered.length} page${filtered.length === 1 ? "" : "s"}${filtered.length > limit ? ` (showing ${limit}; raise limit (max 1000) or narrow with urlContains/fetchClass/statusCode for the rest)` : ""}.`;
+ const text =
+ pages.length === 0
+ ? `${header}\nNo crawled pages match these filters.`
+ : `${header}\n${formatMcpTable(pages, PAGE_COLUMNS)}`;
return mcpResponse({
text,
diff --git a/src/server/mcp/tools/tool-text-output.test.ts b/src/server/mcp/tools/tool-text-output.test.ts
index 5cf56ad9..ff2ca126 100644
--- a/src/server/mcp/tools/tool-text-output.test.ts
+++ b/src/server/mcp/tools/tool-text-output.test.ts
@@ -1,5 +1,6 @@
/* eslint-disable max-lines, max-lines-per-function -- one spec covers every service-backed MCP text table */
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { reverse } from "remeda";
import * as researchTools from "./dataforseo-research-tools";
import { getBacklinksOverviewTool } from "./get-backlinks-overview";
import { getDomainKeywordSuggestionsTool } from "./get-domain-keyword-suggestions";
@@ -110,6 +111,8 @@ describe("MCP tool text output (service-backed tools)", () => {
overview: {
summary: {
backlinks: 1200,
+ newBacklinks: 30,
+ lostBacklinks: 7,
referringDomains: 340,
referringPages: 900,
rank: 55,
@@ -123,6 +126,9 @@ describe("MCP tool text output (service-backed tools)", () => {
backlinks: 42,
referringPages: 5,
rank: 30,
+ spamScore: 12,
+ brokenBacklinks: 1,
+ firstSeen: "2019-03-05 07:34:01 +00:00",
},
],
});
@@ -132,8 +138,11 @@ describe("MCP tool text output (service-backed tools)", () => {
);
const out = textContent(result);
- expect(out).toContain("domain | backlinks | referring pages | rank");
- expect(out).toContain("linker.example | 42 | 5 | 30");
+ expect(out).toContain(
+ "domain | backlinks | referring pages | rank | spam | broken | first seen",
+ );
+ expect(out).toContain("- backlinks: 1200 (new 30 / lost 7)");
+ expect(out).toContain("linker.example | 42 | 5 | 30 | 12 | 1 | 2019-03-05");
});
it("get_rank_tracker renders every tracked-keyword row (detail view)", async () => {
@@ -169,6 +178,73 @@ describe("MCP tool text output (service-backed tools)", () => {
expect(out).toContain("seo tools | 3 | 5 | 7 | —");
});
+ it("get_rank_tracker pages through every removal id in a large tracker", async () => {
+ const rows = Array.from({ length: 230 }, (_, index) => ({
+ keyword: `keyword ${String(index).padStart(3, "0")}`,
+ trackingKeywordId: `tracked-${index}`,
+ desktop: {
+ position: 3,
+ previousPosition: 5,
+ rankingUrl: `https://example.com/${"x".repeat(500)}`,
+ },
+ mobile: null,
+ }));
+ mocks.getTracker.mockResolvedValue({
+ config: {
+ id: "tracker_1",
+ domain: "example.com",
+ scheduleInterval: "daily",
+ devices: "desktop",
+ serpDepth: 20,
+ },
+ results: { rows: reverse(rows), run: null },
+ });
+ const initial = await getRankTrackerTool.handler(
+ { projectId: "project_1", trackerId: "tracker_1" },
+ toolContext,
+ );
+ expect(textContent(initial)).toContain("truncated");
+ expect(textContent(initial)).toContain(
+ "repeat offset=0 with a smaller limit",
+ );
+ const ids: unknown[] = [];
+ let offset: number | null = 0;
+ while (offset !== null) {
+ const result = await getRankTrackerTool.handler(
+ { projectId: "project_1", trackerId: "tracker_1", offset, limit: 25 },
+ toolContext,
+ );
+ const page = getRankTrackerTool.config.outputSchema.parse(
+ result.structuredContent,
+ ).results;
+ if (!page) throw new Error("Expected tracker results");
+ expect(page.totalCount).toBe(230);
+ expect(page.rows.length).toBeLessThanOrEqual(25);
+ for (const row of page.rows) {
+ expect(textContent(result)).toContain(
+ `${String(row.trackingKeywordId)} |`,
+ );
+ ids.push(row.trackingKeywordId);
+ }
+ if (page.nextOffset !== null) {
+ expect(page.nextOffset).toBeGreaterThan(offset);
+ expect(textContent(result)).toContain(
+ `Next page: offset=${page.nextOffset}`,
+ );
+ }
+ offset = page.nextOffset;
+ }
+ expect(ids).toEqual(rows.map((row) => row.trackingKeywordId));
+ const beyond = await getRankTrackerTool.handler(
+ { projectId: "project_1", trackerId: "tracker_1", offset: 500 },
+ toolContext,
+ );
+ expect(textContent(beyond)).toContain("No keywords at this offset");
+ expect(beyond.structuredContent).toMatchObject({
+ results: { rows: [], nextOffset: null },
+ });
+ });
+
it("get_rank_tracker surfaces the latest run failure", async () => {
mocks.getTracker.mockResolvedValue({
config: {
@@ -215,9 +291,15 @@ describe("MCP tool text output (service-backed tools)", () => {
keyword_data: {
keyword: "seo tools",
keyword_info: { search_volume: 1000, cpc: 3.2 },
+ keyword_properties: { keyword_difficulty: 55 },
+ search_intent_info: { main_intent: "commercial" },
},
ranked_serp_element: {
- serp_item: { rank_absolute: 4, url: "https://example.com/tools" },
+ serp_item: {
+ rank_absolute: 4,
+ url: "https://example.com/tools",
+ etv: 120.5,
+ },
},
},
],
@@ -234,9 +316,11 @@ describe("MCP tool text output (service-backed tools)", () => {
);
const out = textContent(result);
- expect(out).toContain("keyword | rank | volume | CPC | url");
expect(out).toContain(
- "seo tools | 4 | 1000 | 3.20 | https://example.com/tools",
+ "keyword | rank | volume | KD | intent | CPC | traffic | url",
+ );
+ expect(out).toContain(
+ "seo tools | 4 | 1000 | 55 | commercial | 3.20 | 120.50 | https://example.com/tools",
);
});
@@ -252,8 +336,12 @@ describe("MCP tool text output (service-backed tools)", () => {
{
rank_absolute: 1,
post_date: "04/02/2020 00:00:00",
+ author: "Acme Cafe",
post_text: "We are open for takeaway.",
url: "https://search.google.com/local/posts?q=acme",
+ links: [
+ { type: "Order online", url: "https://acme.example/order" },
+ ],
},
],
},
@@ -265,9 +353,9 @@ describe("MCP tool text output (service-backed tools)", () => {
);
const out = textContent(result);
- expect(out).toContain("# | posted | post | url");
+ expect(out).toContain("# | posted | author | post | url | links");
expect(out).toContain(
- "1 | 04/02/2020 00:00:00 | We are open for takeaway. | https://search.google.com/local/posts?q=acme",
+ "1 | 04/02/2020 00:00:00 | Acme Cafe | We are open for takeaway. | https://search.google.com/local/posts?q=acme | Order online → https://acme.example/order",
);
});
@@ -395,6 +483,7 @@ describe("MCP tool text output (service-backed tools)", () => {
previous: null,
comparison: {},
trend: [],
+ diagnostics: [],
});
const result = await getGoogleAnalyticsOrganicOverviewTool.handler(