Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Show search volume for rank tracking keywords added over MCP (#1089)
Carter Smith9637a60b56f5
diff --git a/src/server/mcp/tools/add-rank-tracking-keywords.ts b/src/server/mcp/tools/add-rank-tracking-keywords.tsindex db482bfe..5ddef99a 100644--- a/src/server/mcp/tools/add-rank-tracking-keywords.ts+++ b/src/server/mcp/tools/add-rank-tracking-keywords.ts@@ -1,6 +1,8 @@import { z } from "zod";import { MAX_TRACKED_KEYWORD_LENGTH } from "@/shared/rank-tracking";import { RankTrackingService } from "@/server/features/rank-tracking/services/RankTrackingService";+import type { BillingCustomerContext } from "@/server/billing/subscription";+import { asAppError } from "@/server/lib/errors";import { buildProjectMeta } from "@/server/mcp/context";import { mcpResponse } from "@/server/mcp/formatters";import { optionalMetaOutputSchema } from "@/server/mcp/output-schemas";@@ -36,12 +38,34 @@ const inputSchema = {type Args = z.infer<z.ZodObject<typeof inputSchema>>;+// The keywords are saved before this runs, so a billing refusal is reported+// rather than thrown: failing the call would read as the add having failed.+async function fetchKeywordMetrics(+ args: Args,+ billing: BillingCustomerContext,+) {+ try {+ const { updated } = await RankTrackingService.refreshKeywordMetrics(+ args.trackerId,+ args.projectId,+ billing,+ );+ return ` Fetched search volume, difficulty and CPC for ${updated} keyword${updated === 1 ? "" : "s"}.`;+ } catch (error) {+ const code = asAppError(error)?.code;+ if (code !== "PAYMENT_REQUIRED" && code !== "INSUFFICIENT_CREDITS") {+ throw error;+ }+ return ` Search volume was not fetched (${code}).`;+ }+}+export const addRankTrackingKeywordsTool = {name: "add_rank_tracking_keywords",config: {title: "Add rank tracking keywords",description:- "Add keywords to an existing rank tracker. The mutation itself uses no credits and does not start a check or fetch metrics, but scheduled trackers will spend credits on future recurring public Google searches. For a scheduled tracker, call estimate_rank_tracker_cost with additionalKeywords, show the recurring estimate to the user, and pass the approved per-check estimate as maxEstimatedScheduledCheckCredits. The estimate is the most a check can cost, including retries. Existing and repeated keywords are skipped, and `added` is the number actually inserted.",+ "Add keywords to an existing rank tracker. It also fetches search volume, difficulty and CPC for the tracker's keywords, which uses credits like get_keyword_metrics. It does not start a check, but scheduled trackers will spend credits on future recurring public Google searches. For a scheduled tracker, call estimate_rank_tracker_cost with additionalKeywords, show the recurring estimate to the user, and pass the approved per-check estimate as maxEstimatedScheduledCheckCredits. The estimate is the most a check can cost, including retries. Existing and repeated keywords are skipped, and `added` is the number actually inserted.",inputSchema,outputSchema: z.object({@@ -81,8 +105,10 @@ export const addRankTrackingKeywordsTool = {args.matchCase,);const requested = args.keywords.length;+ const metricsNote =+ result.added > 0 ? await fetchKeywordMetrics(args, context.billing) : "";return mcpResponse({- text: `Added ${result.added} of ${requested} requested keyword${requested === 1 ? "" : "s"} to tracker ${args.trackerId}. No check was started and no credits were used.${result.scheduledEstimate ? ` Future ${result.scheduledEstimate.scheduleInterval} checks cost at most ${result.scheduledEstimate.costCredits} credits each, including retries (up to ~${result.scheduledEstimate.monthlyCostCredits} credits/month).` : ""}`,+ text: `Added ${result.added} of ${requested} requested keyword${requested === 1 ? "" : "s"} to tracker ${args.trackerId}. No check was started.${metricsNote}${result.scheduledEstimate ? ` Future ${result.scheduledEstimate.scheduleInterval} checks cost at most ${result.scheduledEstimate.costCredits} credits each, including retries (up to ~${result.scheduledEstimate.monthlyCostCredits} credits/month).` : ""}`,meta: buildProjectMeta(context,args.projectId,diff --git a/src/server/mcp/tools/rank-tracking-management-tools.test.ts b/src/server/mcp/tools/rank-tracking-management-tools.test.tsindex 358f8e17..1a84a0c9 100644--- a/src/server/mcp/tools/rank-tracking-management-tools.test.ts+++ b/src/server/mcp/tools/rank-tracking-management-tools.test.ts@@ -1,5 +1,6 @@import { beforeEach, describe, expect, it, vi } from "vitest";import { z } from "zod";+import { AppError } from "@/server/lib/errors";import { addRankTrackingKeywordsTool } from "./add-rank-tracking-keywords";import { createRankTrackerTool } from "./create-rank-tracker";import { getRankTrackerTool } from "./get-rank-tracker";@@ -11,6 +12,7 @@ const mocks = vi.hoisted(() => ({createConfig: vi.fn(),getTracker: vi.fn(),addKeywords: vi.fn(),+ refreshKeywordMetrics: vi.fn(),triggerCheck: vi.fn(),captureServerEvent: vi.fn(),waitUntil: vi.fn(),@@ -30,6 +32,7 @@ vi.mock("@/server/features/rank-tracking/services/RankTrackingService", () => ({createConfig: mocks.createConfig,getTracker: mocks.getTracker,addKeywords: mocks.addKeywords,+ refreshKeywordMetrics: mocks.refreshKeywordMetrics,triggerCheck: mocks.triggerCheck,},}));@@ -59,6 +62,7 @@ describe("rank tracking management MCP tools", () => {languageCode: "en",});mocks.captureServerEvent.mockResolvedValue(undefined);+ mocks.refreshKeywordMetrics.mockResolvedValue({ updated: 1 });});it("creates a manual tracker from project defaults without spending credits", async () => {@@ -141,6 +145,9 @@ describe("rank tracking management MCP tools", () => {toolContext,);expect(textContent(added)).toContain("Added 1 of 3 requested");+ expect(textContent(added)).toContain(+ "Fetched search volume, difficulty and CPC for 1 keyword.",+ );expect(added.structuredContent).toMatchObject({ requested: 3, added: 1 });expect(mocks.addKeywords).toHaveBeenCalledWith(trackerId,@@ -154,6 +161,23 @@ describe("rank tracking management MCP tools", () => {);});+ it("keeps the add successful when a billing refusal stops the metrics fetch", async () => {+ mocks.addKeywords.mockResolvedValue({ added: 1, addedIds: [keywordId] });+ mocks.refreshKeywordMetrics.mockRejectedValue(+ new AppError("INSUFFICIENT_CREDITS"),+ );++ const added = await addRankTrackingKeywordsTool.handler(+ { projectId, trackerId, keywords: ["seo"] },+ toolContext,+ );++ expect(added.structuredContent).toMatchObject({ added: 1 });+ expect(textContent(added)).toContain(+ "Search volume was not fetched (INSUFFICIENT_CREDITS).",+ );+ });+it("returns the created run ID and emits the telemetry contract, but not for an already-running tracker", async () => {mocks.triggerCheck.mockResolvedValue({ ok: true, runId: "run_1" });const started = await runRankTrackerTool.handler(