Skip to content

Open source alternative to Semrush and Ahrefs

39.6 KB
Raw Blame
/* eslint-disable max-lines */
import { firstBy, sort } from "remeda";
import { z } from "zod";
import {
  createDataforseoClient,
  fetchKeywordMetricsForList,
  type KeywordMetricRow,
} from "@/server/lib/dataforseo";
import { buildProjectMeta } from "@/server/mcp/context";
import { mcpResponse } from "@/server/mcp/formatters";
import {
  looseObjectOutputSchema,
  optionalMetaOutputSchema,
} from "@/server/mcp/output-schemas";
import { withMcpProjectAuth } from "@/server/mcp/project-auth";
import {
  formatMcpCell,
  formatMcpTable,
  readPath,
  truncatedCell,
  type McpTableColumn,
} from "@/server/mcp/table";
import {
  businessIdentifierInputSchema,
  businessIdentifierKeyword,
  formatBusinessDataCoordinate,
  formatCoordinate,
  formatLocalSerpCoordinate,
  pickRowFields,
  resolveBusinessIdentifier,
} from "@/server/mcp/tools/local-seo-shared";
import { resolveLabsMarket, resolveMarket } from "@/shared/keyword-locations";
import {
  assertLabsLocationCode,
  assertLanguageForLocation,
} from "@/server/lib/market";
import {
  DEFAULT_LOCATION_CODE,
  languageCodeSchema,
  locationCodeSchema,
  projectIdSchema,
} from "@/server/mcp/schemas";
import { assertFilterConditionBudget } from "@/server/lib/dataforseo/filters";
import {
  buildRankedKeywordsScopeFilter,
  type ScopeFilter,
} from "@/server/lib/dataforseo/researchScopeFilters";
import { parseResearchTargetOrThrow } from "@/server/lib/domainUtils";
import {
  RESEARCH_SCOPE_PARAM_DESCRIPTION,
  researchScopeSchema,
} from "@/shared/researchScope";

const rankedResultTypeSchema = z.enum([
  "organic",
  "paid",
  "featured_snippet",
  "local_pack",
  "ai_overview_reference",
]);

const serpCompetitorResultTypeSchema = z.enum([
  "organic",
  "paid",
  "featured_snippet",
  "local_pack",
]);

const marketSchema = z
  .object({
    country: z
      .enum(["US", "USA", "United States", "United States of America"])
      .optional()
      .describe(
        "Country selector. Only the United States can be selected explicitly.",
      ),
  })
  .optional()
  .describe(
    "Legacy US selector. Prefer locationCode/languageCode for any Labs market. Explicit locationCode takes precedence; otherwise omitted = the project's default market.",
  );

const nearSchema = z
  .object({
    latitude: z
      .number()
      .min(-90)
      .max(90)
      .describe("Latitude of the search center."),
    longitude: z
      .number()
      .min(-180)
      .max(180)
      .describe("Longitude of the search center."),
    radiusKm: z
      .number()
      .min(1)
      .max(100000)
      .describe(
        "Search radius around the center, in whole kilometers (fractions are rounded).",
      ),
  })
  .describe("Coordinate and radius to search around.");

const localSerpNearSchema = z
  .object({
    latitude: z
      .number()
      .min(-90)
      .max(90)
      .describe("Latitude the SERP is fetched from."),
    longitude: z
      .number()
      .min(-180)
      .max(180)
      .describe("Longitude the SERP is fetched from."),
    zoom: z
      .number()
      .int()
      .min(4)
      .max(18)
      .optional()
      .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)
  .max(255)
  .refine(
    (value) =>
      /^(?!https?:\/\/)(?!www\.)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(
        value,
      ),
    "Use a domain or subdomain without protocol and without www.",
  );

const rankedTargetSchema = z
  .string()
  .min(1)
  .max(2048)
  .refine(
    (value) =>
      /^https?:\/\/\S+$/.test(value) ||
      domainTargetSchema.safeParse(value).success,
    "Use a domain without protocol/www or an absolute page URL.",
  );

const getRankedKeywordsInputSchema = {
  projectId: projectIdSchema,
  target: rankedTargetSchema.describe(
    "Domain (no protocol/www) or absolute page URL to list ranked keywords for.",
  ),
  scope: researchScopeSchema
    .optional()
    .describe(RESEARCH_SCOPE_PARAM_DESCRIPTION),
  market: marketSchema,
  locationCode: locationCodeSchema
    .optional()
    .describe(
      "Country-level DataForSEO Labs location code. Defaults to the project's market; takes precedence over the legacy market object.",
    ),
  languageCode: languageCodeSchema
    .optional()
    .describe(
      "Language for locationCode. Defaults to that location's primary language when locationCode overrides the project market.",
    ),
  resultTypes: z
    .array(rankedResultTypeSchema)
    .min(1)
    .max(5)
    .optional()
    .describe("SERP result types to include. Defaults to organic and paid."),
  includeSubdomains: z
    .boolean()
    .optional()
    .describe("Deprecated: use scope ('subdomains' or 'domain') instead."),
  minSearchVolume: z
    .number()
    .int()
    .min(0)
    .optional()
    .describe("Only return keywords with at least this monthly search volume."),
  maxRank: z
    .number()
    .int()
    .min(1)
    .max(100)
    .optional()
    .describe("Only return keywords ranking at this position or better."),
  excludeBrandTerms: z
    .array(z.string().min(1).max(80))
    .min(1)
    .max(10)
    .optional()
    .describe("Exclude keywords containing any of these brand terms."),
  sortBy: z
    .enum(["rank", "search_volume", "traffic_estimate", "cpc"])
    .optional()
    .describe("Sort order for returned rows. Defaults to search_volume."),
  limit: z
    .number()
    .int()
    .min(1)
    .max(100)
    .optional()
    .describe("Maximum rows to return (1-100). Defaults to 50."),
  offset: z
    .number()
    .int()
    .min(0)
    .max(1000)
    .optional()
    .describe("Rows to skip for pagination."),
} as const;

const searchLocalBusinessesInputSchema = {
  projectId: projectIdSchema,
  query: z
    .string()
    .min(1)
    .max(200)
    .optional()
    .describe("Business name or title text to match."),
  near: nearSchema,
  categories: z
    .array(z.string().min(1).max(120))
    .min(1)
    .max(10)
    .optional()
    .describe("Business categories to filter by (e.g. 'pizza_restaurant')."),
  minRating: z
    .number()
    .min(1)
    .max(5)
    .optional()
    .describe("Only return businesses rated at least this (1-5)."),
  minReviews: z
    .number()
    .int()
    .min(0)
    .optional()
    .describe("Only return businesses with at least this many Google reviews."),
  isClaimed: z
    .boolean()
    .optional()
    .describe(
      "Filter by whether the listing is claimed by its owner. false surfaces unclaimed listings (outreach prospects).",
    ),
  sortBy: z
    .enum(["relevance", "rating", "reviews"])
    .optional()
    .describe("Sort order for returned rows. Defaults to relevance."),
  limit: z
    .number()
    .int()
    .min(1)
    .max(50)
    .optional()
    .describe("Maximum businesses to return (1-50). Defaults to 20."),
  offset: z
    .number()
    .int()
    .min(0)
    .max(1000)
    .optional()
    .describe("Rows to skip for pagination."),
} as const;

const localSearchTypeSchema = z.enum(["maps", "local_finder"]);

const getLocalSerpResultsInputSchema = {
  projectId: projectIdSchema,
  keyword: z
    .string()
    .min(1)
    .max(120)
    .describe("Search query to run on Google Maps or Local Finder."),
  near: localSerpNearSchema,
  searchType: localSearchTypeSchema
    .optional()
    .describe("Which local SERP to fetch. Defaults to maps."),
  device: z
    .enum(["desktop", "mobile"])
    .optional()
    .describe(
      "Device the SERP is rendered for. Defaults to mobile, matching get_local_rank_grid.",
    ),
  depth: z
    .number()
    .int()
    .min(1)
    .max(100)
    .optional()
    .describe("Number of results to fetch (1-100). Defaults to 20."),
  languageCode: languageCodeSchema.optional(),
} as const;

const getGoogleBusinessQuestionsInputSchema = {
  projectId: projectIdSchema,
  ...businessIdentifierInputSchema,
  near: nearSchema,
  depth: z
    .number()
    .int()
    .min(1)
    .max(100)
    .optional()
    .describe("Maximum Q&A rows to fetch (1-100). Defaults to 20."),
  languageCode: languageCodeSchema.optional(),
} as const;

const findSerpCompetitorsInputSchema = {
  projectId: projectIdSchema,
  keywords: z
    .array(z.string().min(1).max(120))
    .min(1)
    .max(100)
    .describe("Keywords whose SERPs are compared (1-100)."),
  market: marketSchema,
  locationCode: locationCodeSchema
    .optional()
    .describe(
      "Country-level DataForSEO Labs location code. Defaults to the project's market; takes precedence over the legacy market object.",
    ),
  languageCode: languageCodeSchema
    .optional()
    .describe(
      "Language for locationCode. Defaults to that location's primary language when locationCode overrides the project market.",
    ),
  resultTypes: z
    .array(serpCompetitorResultTypeSchema)
    .min(1)
    .max(4)
    .optional()
    .describe(
      "SERP result types to include. Defaults to organic and local_pack.",
    ),
  excludeDomains: z
    .array(domainTargetSchema)
    .min(1)
    .max(50)
    .optional()
    .describe("Domains to exclude from results (e.g. the user's own site)."),
  includeSubdomains: z
    .boolean()
    .optional()
    .describe("Count subdomains as part of the same competitor domain."),
  sortBy: z
    .enum(["visibility", "traffic_estimate", "avg_position", "keyword_count"])
    .optional()
    .describe("Sort order for returned competitors. Defaults to visibility."),
  limit: z
    .number()
    .int()
    .min(1)
    .max(100)
    .optional()
    .describe("Maximum competitors to return (1-100). Defaults to 50."),
  offset: z
    .number()
    .int()
    .min(0)
    .max(1000)
    .optional()
    .describe("Rows to skip for pagination."),
} as const;

const keywordMetricsSortSchema = z.enum([
  "search_volume",
  "keyword_difficulty",
  "cpc",
  "competition",
]);

const getKeywordMetricsInputSchema = {
  projectId: projectIdSchema,
  keywords: z
    .array(z.string().min(1).max(80))
    .min(1)
    .max(700)
    .describe("Keywords to fetch metrics for (1-700)."),
  locationCode: locationCodeSchema.optional(),
  languageCode: languageCodeSchema.optional(),
  includeMonthlyTrends: z
    .boolean()
    .optional()
    .describe("Include monthly search-volume trend rows. Defaults to true."),
  includeClickstreamData: z
    .boolean()
    .optional()
    .describe(
      "Refine search volumes with clickstream data, which disaggregates Google Ads' grouped close-variant volumes (plurals/misspellings). DOUBLES the credit cost of the call. Default false. No effect for countries served from Google Ads data.",
    ),
  sortBy: keywordMetricsSortSchema
    .optional()
    .describe("Sort order for returned rows. Defaults to search_volume."),
} as const;

type Market = z.infer<typeof marketSchema>;
type GetRankedKeywordsArgs = z.infer<
  z.ZodObject<typeof getRankedKeywordsInputSchema>
>;
type FindSerpCompetitorsArgs = z.infer<
  z.ZodObject<typeof findSerpCompetitorsInputSchema>
>;
type GetKeywordMetricsArgs = z.infer<
  z.ZodObject<typeof getKeywordMetricsInputSchema>
>;
type SearchLocalBusinessesArgs = z.infer<
  z.ZodObject<typeof searchLocalBusinessesInputSchema>
>;
type GetLocalSerpResultsArgs = z.infer<
  z.ZodObject<typeof getLocalSerpResultsInputSchema>
>;
type GetGoogleBusinessQuestionsArgs = z.infer<
  z.ZodObject<typeof getGoogleBusinessQuestionsInputSchema>
>;

/**
 * Resolves a Labs location + language. Explicit location/language fields win,
 * followed by the legacy explicit-US selector; omitted fields inherit the
 * project's default via resolveLabsMarket, which keeps these Labs-only tools
 * off an Ads-served project market. Validate before starting a paid request.
 */
function resolveMarketSelector(
  selector: {
    market?: Market;
    locationCode?: number;
    languageCode?: string;
  },
  project: { locationCode: number; languageCode: string },
): { locationCode: number; languageCode: string } {
  let resolved: { locationCode: number; languageCode: string };
  if (selector.locationCode != null || selector.languageCode != null) {
    resolved = resolveLabsMarket(
      {
        locationCode: selector.locationCode,
        languageCode: selector.languageCode,
      },
      project,
    );
  } else if (selector.market?.country != null) {
    // The Zod enum already restricts explicit values to United States variants.
    resolved = { locationCode: DEFAULT_LOCATION_CODE, languageCode: "en" };
  } else {
    resolved = resolveLabsMarket({}, project);
  }
  assertLabsLocationCode(resolved.locationCode);
  assertLanguageForLocation(resolved.locationCode, resolved.languageCode);
  return resolved;
}

function formatBusinessLocationCoordinate(near: z.infer<typeof nearSchema>) {
  // Business Listings rejects fractional radii ("Invalid Field:
  // 'location_coordinate'"), unlike the meter-based business_data radius.
  const radiusKm = Math.max(1, Math.round(near.radiusKm));
  return `${formatCoordinate(near.latitude)},${formatCoordinate(near.longitude)},${radiusKm}`;
}

function sortOrderByRankedMode(
  sortBy: GetRankedKeywordsArgs["sortBy"] = "search_volume",
): string[] {
  switch (sortBy) {
    case "rank":
      return ["ranked_serp_element.serp_item.rank_absolute,asc"];
    case "traffic_estimate":
      return ["ranked_serp_element.serp_item.etv,desc"];
    case "cpc":
      return ["keyword_data.keyword_info.cpc,desc"];
    case "search_volume":
      return ["keyword_data.keyword_info.search_volume,desc"];
  }
}

function pushAnd(filters: unknown[], condition: unknown[]) {
  if (filters.length > 0) filters.push("and");
  filters.push(condition);
}

function buildRankedKeywordFilters(
  args: {
    minSearchVolume?: number;
    maxRank?: number;
    excludeBrandTerms?: string[];
  },
  scopeFilter?: ScopeFilter,
) {
  const filters: unknown[] = [];
  let conditionCount = 0;
  if (scopeFilter) {
    for (const clause of scopeFilter.clauses) pushAnd(filters, clause);
    conditionCount += scopeFilter.conditionCount;
  }
  if (args.minSearchVolume != null) {
    pushAnd(filters, [
      "keyword_data.keyword_info.search_volume",
      ">=",
      args.minSearchVolume,
    ]);
    conditionCount += 1;
  }
  if (args.maxRank != null) {
    pushAnd(filters, [
      "ranked_serp_element.serp_item.rank_absolute",
      "<=",
      args.maxRank,
    ]);
    conditionCount += 1;
  }
  if (args.excludeBrandTerms != null) {
    for (const term of args.excludeBrandTerms) {
      pushAnd(filters, ["keyword_data.keyword", "not_ilike", `%${term}%`]);
    }
    conditionCount += args.excludeBrandTerms.length;
  }
  assertFilterConditionBudget(conditionCount);
  return filters.length > 0 ? filters : undefined;
}

function buildLocalBusinessFilters(args: {
  minRating?: number;
  minReviews?: number;
}) {
  const filters: unknown[] = [];
  if (args.minRating != null) {
    pushAnd(filters, ["rating.value", ">=", args.minRating]);
  }
  if (args.minReviews != null) {
    pushAnd(filters, ["rating.votes_count", ">=", args.minReviews]);
  }
  return filters.length > 0 ? filters : undefined;
}

function localBusinessOrderBy(
  sortBy: SearchLocalBusinessesArgs["sortBy"],
): string[] | undefined {
  switch (sortBy) {
    case "rating":
      return ["rating.value,desc"];
    case "reviews":
      return ["rating.votes_count,desc"];
    default:
      return undefined;
  }
}

function sortCompetitors(
  items: Record<string, unknown>[],
  sortBy: FindSerpCompetitorsArgs["sortBy"],
) {
  const field =
    sortBy === "avg_position"
      ? "avg_position"
      : sortBy === "keyword_count"
        ? "keywords_count"
        : sortBy === "traffic_estimate"
          ? "etv"
          : "visibility";
  const direction = sortBy === "avg_position" ? 1 : -1;
  return sort(items, (a, b) => {
    const aValue = typeof a[field] === "number" ? a[field] : 0;
    const bValue = typeof b[field] === "number" ? b[field] : 0;
    return (aValue - bValue) * direction;
  });
}

// Project the shared canonical metric row onto this tool's snake_case API
// shape (kept stable for MCP clients); an absent trend stays null as before.
function toMcpKeywordMetricRow(row: KeywordMetricRow) {
  return {
    keyword: row.keyword,
    search_volume: row.searchVolume,
    keyword_difficulty: row.keywordDifficulty,
    main_intent: row.intent,
    cpc: row.cpc,
    competition: row.competition,
    competition_level: row.competitionLevel,
    monthly_searches: row.monthlySearches.length
      ? row.monthlySearches.map((entry) => ({
          year: entry.year,
          month: entry.month,
          search_volume: entry.searchVolume,
        }))
      : null,
  };
}

type McpKeywordMetricRow = ReturnType<typeof toMcpKeywordMetricRow>;

function sortKeywordMetricRows(
  rows: McpKeywordMetricRow[],
  sortBy: NonNullable<GetKeywordMetricsArgs["sortBy"]> = "search_volume",
) {
  return sort(rows, (a, b) => {
    const aValue = a[sortBy];
    const bValue = b[sortBy];
    const aNum = typeof aValue === "number" ? aValue : 0;
    const bNum = typeof bValue === "number" ? bValue : 0;
    return bNum - aNum;
  });
}

function hostMatchesDomain(host: string, domain: string): boolean {
  const normalizedHost = host.replace(/^www\./, "").toLowerCase();
  const normalizedDomain = domain.replace(/^www\./, "").toLowerCase();
  return (
    normalizedHost === normalizedDomain ||
    normalizedHost.endsWith(`.${normalizedDomain}`)
  );
}

// Provider rows ship in full in structuredContent; these tables render every
// row into the text content block so text-only MCP clients see the data, not
// just a count. Loose rows are read positionally via readPath.

type RankedKeywordRow = {
  keyword: unknown;
  rank: unknown;
  volume: unknown;
  kd: unknown;
  intent: unknown;
  cpc: unknown;
  traffic: unknown;
  url: unknown;
};

function toRankedKeywordRow(item: unknown): RankedKeywordRow {
  return {
    keyword:
      readPath(item, "keyword_data", "keyword") ?? readPath(item, "keyword"),
    rank:
      readPath(item, "ranked_serp_element", "serp_item", "rank_absolute") ??
      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"),
  };
}

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 },
];

// Full Business Listings rows are ~9KB each (popular_times for every day,
// attribute trees, photo URLs) — 10 of them overflow MCP clients' tool-result
// budgets. Return only the fields a candidate list needs; get_business_profile
// serves the full shape for one business.
const LOCAL_BUSINESS_ROW_FIELDS = [
  "title",
  "description",
  "category",
  "additional_categories",
  "address",
  "phone",
  "url",
  "domain",
  "rating",
  "is_claimed",
  "cid",
  "place_id",
  "latitude",
  "longitude",
  "total_photos",
  "check_url",
] as const;

// Maps SERP rows likewise ship image CDN URLs, feature ids, and contributor
// links no consumer reads; keep identity, rank, rating, categories, and hours.
const LOCAL_SERP_ROW_FIELDS = [
  "rank_group",
  "rank_absolute",
  "title",
  "domain",
  "url",
  "contact_url",
  "address",
  "address_info",
  "phone",
  "category",
  "additional_categories",
  "rating",
  "rating_distribution",
  "price_level",
  "is_claimed",
  "cid",
  "place_id",
  "latitude",
  "longitude",
  "total_photos",
  "work_hours",
  "local_justifications",
] as const;

const LOCAL_BUSINESS_COLUMNS: McpTableColumn<unknown>[] = [
  { header: "title", value: (row) => readPath(row, "title") },
  { 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>[] = [
  {
    header: "rank",
    value: (row) =>
      readPath(row, "rank_absolute") ?? readPath(row, "rank_group"),
  },
  { header: "title", value: (row) => readPath(row, "title") },
  { header: "rating", value: (row) => readPath(row, "rating", "value") },
  { 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
// question AND every nested answer; keep the text, author, and timing.
const BUSINESS_QUESTION_ROW_FIELDS = [
  "rank_absolute",
  "question_id",
  "question_text",
  "original_question_text",
  "profile_name",
  "time_ago",
  "timestamp",
] as const;

const BUSINESS_ANSWER_ROW_FIELDS = [
  "answer_id",
  "answer_text",
  "original_answer_text",
  "profile_name",
  "time_ago",
  "timestamp",
] as const;

function trimBusinessQuestionRow(row: unknown): Record<string, unknown> {
  const trimmed = pickRowFields(row, BUSINESS_QUESTION_ROW_FIELDS);
  const answers = readPath(row, "items");
  trimmed.items = Array.isArray(answers)
    ? answers.map((answer) => pickRowFields(answer, BUSINESS_ANSWER_ROW_FIELDS))
    : null;
  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") ?? readPath(row, "original_question_text"),
  },
  { header: "asked by", value: (row) => readPath(row, "profile_name") },
  { header: "when", value: (row) => readPath(row, "time_ago") },
  {
    header: "answers",
    value: (row) => {
      const answers = readPath(row, "items");
      return Array.isArray(answers) ? answers.length : 0;
    },
  },
  {
    header: "latest answer",
    value: latestAnswerText,
    format: truncatedCell(160),
  },
];

const SERP_COMPETITOR_COLUMNS: McpTableColumn<unknown>[] = [
  { header: "domain", value: (row) => readPath(row, "domain") },
  { header: "keywords", value: (row) => readPath(row, "keywords_count") },
  { header: "avg pos", value: (row) => readPath(row, "avg_position") },
  { header: "median pos", value: (row) => readPath(row, "median_position") },
  { header: "visibility", value: (row) => readPath(row, "visibility") },
  { 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") },
  { header: "intent", value: (row) => readPath(row, "main_intent") },
];

export const getRankedKeywordsTool = {
  name: "get_ranked_keywords",
  config: {
    title: "Get ranked keywords",
    description:
      "Returns market-specific keyword, URL, rank, search volume, CPC, intent, and traffic rows for a domain or page. Accepts country-level DataForSEO Labs location/language codes. Use this for strategy evidence; use get_domain_overview for aggregate domain footprint. Charges credits.",
    inputSchema: getRankedKeywordsInputSchema,
    outputSchema: z.looseObject({
      keywords: z.array(looseObjectOutputSchema),
      totalCount: z.number().nullable(),
      target: z.string().optional(),
      scope: researchScopeSchema.optional(),
      ...optionalMetaOutputSchema,
    }),
    annotations: {
      readOnlyHint: false,
      openWorldHint: true,
      destructiveHint: false,
    },
  },
  handler: withMcpProjectAuth(async (args: GetRankedKeywordsArgs, context) => {
    const client = createDataforseoClient(context.billing);
    // Legacy includeSubdomains only ever selected between whole-host scopes
    // for bare domains; for page URLs it meant exact-page results. Mapping it
    // to domain/subdomains for a URL target would silently drop the path.
    const parsedDefault = parseResearchTargetOrThrow(args.target);
    const legacyScope =
      args.includeSubdomains == null
        ? undefined
        : parsedDefault.path === ""
          ? args.includeSubdomains
            ? "subdomains"
            : "domain"
          : "exact_url";
    const requestedScope = args.scope ?? legacyScope;
    const target = requestedScope
      ? parseResearchTargetOrThrow(args.target, requestedScope)
      : parsedDefault;
    const scopeFilter = buildRankedKeywordsScopeFilter(target);
    const market = resolveMarketSelector(args, context.project);
    const keywords = await client.domain.rankedKeywords({
      target: target.hostname,
      locationCode: market.locationCode,
      languageCode: market.languageCode,
      limit: args.limit ?? 50,
      offset: args.offset,
      orderBy: sortOrderByRankedMode(args.sortBy),
      filters: buildRankedKeywordFilters(
        {
          minSearchVolume: args.minSearchVolume,
          maxRank: args.maxRank,
          excludeBrandTerms: args.excludeBrandTerms,
        },
        scopeFilter,
      ),
      itemTypes: args.resultTypes,
    });

    const rankedRows = keywords.items.map(toRankedKeywordRow);
    const targetLabel = `${target.display} (scope: ${target.scope})`;
    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)` : ""}. 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(
        context,
        args.projectId,
        `/p/${args.projectId}/domain`,
        { domain: target.display, scope: target.scope },
      ),
      structuredContent: {
        keywords: keywords.items,
        totalCount: keywords.totalCount,
        target: target.display,
        scope: target.scope,
      },
    });
  }),
};

export const searchLocalBusinessesTool = {
  name: "search_local_businesses",
  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 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),
      ...optionalMetaOutputSchema,
    }),
    annotations: {
      readOnlyHint: false,
      openWorldHint: true,
      destructiveHint: false,
    },
  },
  handler: withMcpProjectAuth(
    async (args: SearchLocalBusinessesArgs, context) => {
      const client = createDataforseoClient(context.billing);
      const rows = await client.business.businessListings({
        categories: args.categories,
        title: args.query,
        locationCoordinate: formatBusinessLocationCoordinate(args.near),
        isClaimed: args.isClaimed,
        filters: buildLocalBusinessFilters(args),
        orderBy: localBusinessOrderBy(args.sortBy),
        limit: args.limit ?? 20,
        offset: args.offset,
      });
      const businesses = rows.map((row) =>
        pickRowFields(row, LOCAL_BUSINESS_ROW_FIELDS),
      );

      const header = `Found ${businesses.length} local business rows${args.query ? ` for ${args.query}` : ""}.`;
      return mcpResponse({
        text:
          businesses.length === 0
            ? header
            : `${header}\n${formatMcpTable(businesses, LOCAL_BUSINESS_COLUMNS)}`,
        meta: buildProjectMeta(context, args.projectId, `/p/${args.projectId}`),
        structuredContent: { businesses },
      });
    },
  ),
};

export const getLocalSerpResultsTool = {
  name: "get_local_serp_results",
  config: {
    title: "Get local SERP results",
    description:
      "Fetches one Google Maps or Local Finder SERP near a coordinate. Returns trimmed provider rows (identity, rank, rating, categories, hours) with rank fields intact; callers decide how to match a target business. Charges credits.",
    inputSchema: getLocalSerpResultsInputSchema,
    outputSchema: z.looseObject({
      results: z.array(looseObjectOutputSchema),
      ...optionalMetaOutputSchema,
    }),
    annotations: {
      readOnlyHint: false,
      openWorldHint: true,
      destructiveHint: false,
    },
  },
  handler: withMcpProjectAuth(
    async (args: GetLocalSerpResultsArgs, context) => {
      const client = createDataforseoClient(context.billing);
      const rows = await client.serp.local({
        keyword: args.keyword,
        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",
        depth: args.depth ?? 20,
        searchPlaces: false,
      });
      const results = rows.map((row) =>
        pickRowFields(row, LOCAL_SERP_ROW_FIELDS),
      );

      const header = `Fetched ${results.length} local SERP rows for "${args.keyword}".`;
      return mcpResponse({
        text:
          results.length === 0
            ? header
            : `${header}\n${formatMcpTable(results, LOCAL_SERP_COLUMNS)}`,
        meta: buildProjectMeta(context, args.projectId, `/p/${args.projectId}`),
        structuredContent: { results },
      });
    },
  ),
};

export const getGoogleBusinessQuestionsTool = {
  name: "get_google_business_questions",
  config: {
    title: "Get Google business questions",
    description:
      "Fetches Google Business Profile questions and answers for one business (by businessName, cid, or placeId) near a coordinate. Run this only when Q&A evidence is needed. Charges credits.",
    inputSchema: getGoogleBusinessQuestionsInputSchema,
    outputSchema: z.looseObject({
      questions: z.array(looseObjectOutputSchema),
      ...optionalMetaOutputSchema,
    }),
    annotations: {
      readOnlyHint: false,
      openWorldHint: true,
      destructiveHint: false,
    },
  },
  handler: withMcpProjectAuth(
    async (args: GetGoogleBusinessQuestionsArgs, context) => {
      const identifier = resolveBusinessIdentifier(args);
      const client = createDataforseoClient(context.billing);
      const rows = await client.business.questionsAnswers({
        // The questions endpoint shares the cid:/place_id: keyword prefixes.
        keyword: businessIdentifierKeyword(identifier),
        locationCoordinate: formatBusinessDataCoordinate(args.near),
        languageCode: args.languageCode ?? context.project.languageCode,
        depth: args.depth ?? 20,
      });
      const questions = rows.map(trimBusinessQuestionRow);

      const header = `Fetched ${questions.length} Google Business Q&A rows for ${businessIdentifierKeyword(identifier)}.`;
      return mcpResponse({
        text:
          questions.length === 0
            ? header
            : `${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 },
      });
    },
  ),
};

export const findSerpCompetitorsTool = {
  name: "find_serp_competitors",
  config: {
    title: "Find SERP competitors",
    description:
      "Compares domains competing in Google results for a supplied keyword set in a country-level DataForSEO Labs market. Accepts location/language codes; not radius-based local SEO. Charges credits.",
    inputSchema: findSerpCompetitorsInputSchema,
    outputSchema: z.looseObject({
      competitors: z.array(looseObjectOutputSchema),
      ...optionalMetaOutputSchema,
    }),
    annotations: {
      readOnlyHint: false,
      openWorldHint: true,
      destructiveHint: false,
    },
  },
  handler: withMcpProjectAuth(
    async (args: FindSerpCompetitorsArgs, context) => {
      const client = createDataforseoClient(context.billing);
      const market = resolveMarketSelector(args, context.project);
      const competitors = await client.labs.serpCompetitors({
        keywords: args.keywords,
        locationCode: market.locationCode,
        languageCode: market.languageCode,
        itemTypes: args.resultTypes ?? ["organic", "local_pack"],
        includeSubdomains: args.includeSubdomains,
        limit: args.limit ?? 50,
        offset: args.offset,
      });
      const excludedDomains = args.excludeDomains ?? [];
      const filtered =
        excludedDomains.length === 0
          ? competitors
          : competitors.filter((item) => {
              const domain = typeof item.domain === "string" ? item.domain : "";
              return !excludedDomains.some((excludedDomain) =>
                hostMatchesDomain(domain, excludedDomain),
              );
            });
      const sorted = sortCompetitors(filtered, args.sortBy ?? "visibility");

      const header = `Found ${sorted.length} SERP competitors across ${args.keywords.length} keywords.`;
      return mcpResponse({
        text:
          sorted.length === 0
            ? header
            : `${header}\n${formatMcpTable(sorted, SERP_COMPETITOR_COLUMNS)}`,
        meta: buildProjectMeta(
          context,
          args.projectId,
          `/p/${args.projectId}/domain`,
        ),
        structuredContent: { competitors: sorted },
      });
    },
  ),
};

export const getKeywordMetricsTool = {
  name: "get_keyword_metrics",
  config: {
    title: "Get keyword metrics",
    description:
      "Hydrate up to 700 known keywords with search volume, keyword difficulty (KD), search intent, CPC, competition, and monthly trends in a single call. Use it to score candidate or known keywords — including Search Console striking-distance queries — by real demand and ranking difficulty. For countries served from Google Ads data (e.g. Iceland), KD and intent are null. Charges credits.",
    inputSchema: getKeywordMetricsInputSchema,
    outputSchema: z.looseObject({
      keywords: z.array(looseObjectOutputSchema),
      ...optionalMetaOutputSchema,
    }),
    annotations: {
      readOnlyHint: false,
      openWorldHint: true,
      destructiveHint: false,
    },
  },
  handler: withMcpProjectAuth(async (args: GetKeywordMetricsArgs, context) => {
    const { locationCode, languageCode } = resolveMarket(args, context.project);
    // Assert against the RESOLVED pair: an explicit language with an omitted
    // location must validate against the project's default location.
    assertLanguageForLocation(locationCode, languageCode);
    const client = createDataforseoClient(context.billing);
    const metrics = await fetchKeywordMetricsForList(client, {
      keywords: args.keywords,
      locationCode,
      languageCode,
      includeClickstreamData: args.includeClickstreamData ?? false,
      creditFeature: "keyword_research",
    });
    const rows = sortKeywordMetricRows(
      metrics.map(toMcpKeywordMetricRow),
      args.sortBy ?? "search_volume",
    ).map((row) =>
      args.includeMonthlyTrends === false
        ? Object.fromEntries(
            Object.entries(row).filter(([key]) => key !== "monthly_searches"),
          )
        : row,
    );

    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
          ? header
          : `${header}\n${formatMcpTable(rows, KEYWORD_METRIC_COLUMNS)}`,
      meta: buildProjectMeta(
        context,
        args.projectId,
        `/p/${args.projectId}/keywords`,
      ),
      structuredContent: { keywords: rows },
    });
  }),
};