Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(metrics): AI visibility score on MCP, public API, Looker, breakdown sheet and pulse movers (#575)

Gökhan Geyik3e1f7d00a239
diff --git a/docs/api-reference/metrics.mdx b/docs/api-reference/metrics.mdx
index f252a62e5..a5d8953a0 100644
--- a/docs/api-reference/metrics.mdx
+++ b/docs/api-reference/metrics.mdx
@@ -68,6 +68,7 @@ Time-bucketed visibility for charting — the endpoint to join against GA4 date
{
"date": "2026-06-01",
"result_count": 24,
+ "ai_visibility_score": 21.4,
"avg_visibility_score": 47,
"total_mentions": 31,
"total_citations": 12,
@@ -77,6 +78,8 @@ Time-bucketed visibility for charting — the endpoint to join against GA4 date
}
```
+`ai_visibility_score` is the dashboard's headline Visibility number (0-100): `0.6 × mention rate + 0.25 × citation rate + 0.15 × position factor` over the day's answers. It is only populated for `day` granularity. `avg_visibility_score` and `avg_competitor_score` are legacy intensity averages kept for compatibility — prefer `ai_visibility_score`. The same field also appears on `/api/v1/visibility-summary` (`totals.aiVisibilityScore`, with `mentionAnswers` / `citationAnswers` / `positionFactor` components) and `/api/v1/competitor-comparison` (`ai_visibility_score` on the brand row and every competitor row).
+
### Competitor comparison & share of voice
```http
diff --git a/integrations/looker-studio/Code.js b/integrations/looker-studio/Code.js
index 6664b27bc..57f0f99c5 100644
--- a/integrations/looker-studio/Code.js
+++ b/integrations/looker-studio/Code.js
@@ -187,6 +187,12 @@ function getFieldsFor(reportType) {
.setId("date")
.setName("Date")
.setType(types.YEAR_MONTH_DAY);
+ fields
+ .newMetric()
+ .setId("ai_visibility_score")
+ .setName("Visibility (AI Visibility Score)")
+ .setType(types.NUMBER)
+ .setAggregation(aggregations.AVG);
fields
.newMetric()
.setId("avg_visibility_score")
@@ -308,6 +314,7 @@ function fetchRowObjects(reportType, brandId, dateFrom, dateTo) {
return (trend.buckets || []).map(function (bucket) {
return {
date: bucket.date.replace(/-/g, ""),
+ ai_visibility_score: bucket.ai_visibility_score,
avg_visibility_score: bucket.avg_visibility_score,
total_mentions: bucket.total_mentions,
total_citations: bucket.total_citations,
diff --git a/server/src/lib/pulse/metrics.js b/server/src/lib/pulse/metrics.js
index d31139bdd..b239118b5 100644
--- a/server/src/lib/pulse/metrics.js
+++ b/server/src/lib/pulse/metrics.js
@@ -123,18 +123,24 @@ async function competitorRates(brandId, from, to) {
return { brandRate, competitors };
}
-async function promptAverages(brandId, from, to) {
- const rows = await rpc('prompt_performance_aggregates', {
+/** Per-prompt AI Visibility Score over a window (movers highlight). */
+async function promptScores(brandId, from, to) {
+ const rows = await rpc('prompt_visibility_summaries', {
p_brand_id: brandId,
p_date_from: from.toISOString(),
p_date_to: to.toISOString(),
});
const map = new Map();
for (const row of rows ?? []) {
- if (!row.result_count) continue;
+ if (!row.runs) continue;
map.set(row.prompt_id, {
- text: row.prompt_text,
- avg: round1((row.sum_visibility ?? 0) / row.result_count),
+ score:
+ computeAiVisibilityScore({
+ answers: Number(row.runs),
+ mentionAnswers: Number(row.mention_answers ?? 0),
+ citationAnswers: Number(row.citation_answers ?? 0),
+ positionFactor: row.position_factor ?? null,
+ }) ?? 0,
});
}
return map;
@@ -331,8 +337,8 @@ export async function computePulseMetrics(brandId, { windowDays = 1, now = new D
insightsWindow(brandId, prevFrom, curFrom),
competitorRates(brandId, weekFrom, now),
competitorRates(brandId, twoWeekFrom, weekFrom),
- promptAverages(brandId, weekFrom, now),
- promptAverages(brandId, twoWeekFrom, weekFrom),
+ promptScores(brandId, weekFrom, now),
+ promptScores(brandId, twoWeekFrom, weekFrom),
firstTimeCitations(promptById, curFrom),
newEngineAppearances(brandId, curFrom),
lostCitationPrompts(brandId, promptById, now),
@@ -371,8 +377,10 @@ export async function computePulseMetrics(brandId, { windowDays = 1, now = new D
for (const [promptId, cur] of weekPromptAvg) {
const prev = prevWeekPromptAvg.get(promptId);
if (!prev) continue;
- const gain = round1(cur.avg - prev.avg);
- if (gain >= MOVER_MIN_GAIN) movers.push({ promptId, text: cur.text, gain });
+ const gain = round1(cur.score - prev.score);
+ if (gain >= MOVER_MIN_GAIN) {
+ movers.push({ promptId, text: promptById.get(promptId)?.text ?? '', gain });
+ }
}
movers.sort((a, b) => b.gain - a.gain);
for (const mover of movers.slice(0, MOVER_LIMIT)) {
diff --git a/supabase/migrations/00041_prompt_visibility_summary_date_to.sql b/supabase/migrations/00041_prompt_visibility_summary_date_to.sql
new file mode 100644
index 000000000..c9ba83422
--- /dev/null
+++ b/supabase/migrations/00041_prompt_visibility_summary_date_to.sql
@@ -0,0 +1,61 @@
+-- Add an upper bound to prompt_visibility_summaries.
+--
+-- The Daily Pulse "top prompt movers" highlight needs per-prompt score
+-- components over two adjacent windows (last 7 days vs the 7 before), and
+-- the function only accepted a lower bound. p_date_to defaults to NULL, so
+-- every existing caller keeps its behavior.
+--
+-- The argument list changes, so the old signature must be dropped first.
+
+DROP FUNCTION public.prompt_visibility_summaries(uuid, timestamptz);
+
+CREATE FUNCTION public.prompt_visibility_summaries(
+ p_brand_id uuid,
+ p_date_from timestamptz DEFAULT NULL,
+ p_date_to timestamptz DEFAULT NULL
+)
+RETURNS TABLE (
+ prompt_id uuid,
+ avg_visibility double precision,
+ avg_visibility_visible double precision,
+ total_mentions bigint,
+ total_citations bigint,
+ runs bigint,
+ visible_runs bigint,
+ mention_answers bigint,
+ citation_answers bigint,
+ position_factor double precision,
+ last_run_at timestamptz
+)
+LANGUAGE sql
+STABLE
+SECURITY INVOKER
+SET search_path = public
+AS $$
+ SELECT pr.prompt_id,
+ AVG(COALESCE(pr.visibility_score, 0))::double precision AS avg_visibility,
+ AVG(COALESCE(pr.visibility_score, 0))
+ FILTER (WHERE pr.mention_count > 0 OR pr.citation_count > 0)
+ ::double precision AS avg_visibility_visible,
+ COALESCE(SUM(pr.mention_count), 0)::bigint AS total_mentions,
+ COALESCE(SUM(pr.citation_count), 0)::bigint AS total_citations,
+ COUNT(*)::bigint AS runs,
+ COUNT(*) FILTER (WHERE pr.mention_count > 0 OR pr.citation_count > 0)::bigint
+ AS visible_runs,
+ COUNT(*) FILTER (WHERE pr.mention_count > 0)::bigint AS mention_answers,
+ COUNT(*) FILTER (WHERE pr.citation_count > 0)::bigint AS citation_answers,
+ AVG(1.0 / pr.mention_position)
+ FILTER (WHERE pr.mention_position IS NOT NULL)
+ ::double precision AS position_factor,
+ MAX(pr.created_at) AS last_run_at
+ FROM public.prompt_results pr
+ WHERE pr.brand_id = p_brand_id
+ AND pr.prompt_id IS NOT NULL
+ AND pr.platform <> 'chatgpt-shopping' -- #155 - isolate from analytics
+ AND (p_date_from IS NULL OR pr.created_at >= p_date_from)
+ AND (p_date_to IS NULL OR pr.created_at <= p_date_to)
+ GROUP BY pr.prompt_id
+$$;
+
+GRANT EXECUTE ON FUNCTION public.prompt_visibility_summaries(uuid, timestamptz, timestamptz)
+ TO authenticated;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index f43b870bd..08ff3cdd6 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -4642,3 +4642,68 @@ $$;
GRANT EXECUTE ON FUNCTION public.visibility_rate_trend(uuid, text, text[], text, timestamptz, timestamptz, uuid)
TO authenticated;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00041_prompt_visibility_summary_date_to.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Add an upper bound to prompt_visibility_summaries.
+--
+-- The Daily Pulse "top prompt movers" highlight needs per-prompt score
+-- components over two adjacent windows (last 7 days vs the 7 before), and
+-- the function only accepted a lower bound. p_date_to defaults to NULL, so
+-- every existing caller keeps its behavior.
+--
+-- The argument list changes, so the old signature must be dropped first.
+
+DROP FUNCTION public.prompt_visibility_summaries(uuid, timestamptz);
+
+CREATE FUNCTION public.prompt_visibility_summaries(
+ p_brand_id uuid,
+ p_date_from timestamptz DEFAULT NULL,
+ p_date_to timestamptz DEFAULT NULL
+)
+RETURNS TABLE (
+ prompt_id uuid,
+ avg_visibility double precision,
+ avg_visibility_visible double precision,
+ total_mentions bigint,
+ total_citations bigint,
+ runs bigint,
+ visible_runs bigint,
+ mention_answers bigint,
+ citation_answers bigint,
+ position_factor double precision,
+ last_run_at timestamptz
+)
+LANGUAGE sql
+STABLE
+SECURITY INVOKER
+SET search_path = public
+AS $$
+ SELECT pr.prompt_id,
+ AVG(COALESCE(pr.visibility_score, 0))::double precision AS avg_visibility,
+ AVG(COALESCE(pr.visibility_score, 0))
+ FILTER (WHERE pr.mention_count > 0 OR pr.citation_count > 0)
+ ::double precision AS avg_visibility_visible,
+ COALESCE(SUM(pr.mention_count), 0)::bigint AS total_mentions,
+ COALESCE(SUM(pr.citation_count), 0)::bigint AS total_citations,
+ COUNT(*)::bigint AS runs,
+ COUNT(*) FILTER (WHERE pr.mention_count > 0 OR pr.citation_count > 0)::bigint
+ AS visible_runs,
+ COUNT(*) FILTER (WHERE pr.mention_count > 0)::bigint AS mention_answers,
+ COUNT(*) FILTER (WHERE pr.citation_count > 0)::bigint AS citation_answers,
+ AVG(1.0 / pr.mention_position)
+ FILTER (WHERE pr.mention_position IS NOT NULL)
+ ::double precision AS position_factor,
+ MAX(pr.created_at) AS last_run_at
+ FROM public.prompt_results pr
+ WHERE pr.brand_id = p_brand_id
+ AND pr.prompt_id IS NOT NULL
+ AND pr.platform <> 'chatgpt-shopping' -- #155 - isolate from analytics
+ AND (p_date_from IS NULL OR pr.created_at >= p_date_from)
+ AND (p_date_to IS NULL OR pr.created_at <= p_date_to)
+ GROUP BY pr.prompt_id
+$$;
+
+GRANT EXECUTE ON FUNCTION public.prompt_visibility_summaries(uuid, timestamptz, timestamptz)
+ TO authenticated;
+
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_metric-breakdown-sheet.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_metric-breakdown-sheet.tsx
index 0d11ae1d5..a17403066 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_metric-breakdown-sheet.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_metric-breakdown-sheet.tsx
@@ -24,7 +24,7 @@ import { sortBreakdownRowsForDisplay } from './breakdown-display';
const METRIC_TITLE: Record<BreakdownMetric, string> = {
mentions: 'Mentions',
- visibility: 'Visibility Score',
+ visibility: 'Visibility',
};
const METRIC_UNIT: Record<BreakdownMetric, string> = {
diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.ts
index 3f8c633fb..b9de11d90 100644
--- a/web/src/lib/actions/tracking.ts
+++ b/web/src/lib/actions/tracking.ts
@@ -2525,15 +2525,37 @@ export interface InsightsBreakdown {
function aggregateMetric(
rows: Array<{
mention_count: number;
+ citation_count?: number;
visibility_score: number;
+ mention_position?: number | null;
}>,
metric: BreakdownMetric,
): { value: number; runs: number } {
if (metric === 'visibility') {
if (rows.length === 0) return { value: 0, runs: 0 };
- const sum = rows.reduce((s, r) => s + (r.visibility_score ?? 0), 0);
+ // AI Visibility Score over the group's answers — the drill-down explains
+ // the same number the KPI card shows, per prompt/platform/topic.
+ let mentionAnswers = 0;
+ let citationAnswers = 0;
+ let posSum = 0;
+ let posN = 0;
+ for (const r of rows) {
+ if ((r.mention_count ?? 0) > 0) mentionAnswers++;
+ if ((r.citation_count ?? 0) > 0) citationAnswers++;
+ const pos = r.mention_position;
+ if (pos !== null && pos !== undefined && pos > 0) {
+ posSum += 1 / pos;
+ posN++;
+ }
+ }
return {
- value: Math.round((sum / rows.length) * 10) / 10,
+ value:
+ computeAiVisibilityScore({
+ answers: rows.length,
+ mentionAnswers,
+ citationAnswers,
+ positionFactor: posN > 0 ? posSum / posN : null,
+ }) ?? 0,
runs: rows.length,
};
}
@@ -2616,7 +2638,9 @@ export async function getInsightsBreakdown(
prompt_id: string;
platform: string;
mention_count: number;
+ citation_count: number;
visibility_score: number;
+ mention_position: number | null;
};
const curRows = (curRes.data ?? []) as unknown as Row[];
const prevRows = (prevRes.data ?? []) as unknown as Row[];
diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.ts
index 567f5b7f5..b1e8ab979 100644
--- a/web/src/lib/mcp/data.ts
+++ b/web/src/lib/mcp/data.ts
@@ -10,6 +10,7 @@ import {
} from '@/lib/citations/classify';
import { classifyArticleType } from '@/lib/citations/article-type';
import { expandDateToEndOfDay } from '@/lib/dates';
+import { computeAiVisibilityScore } from '@/lib/visibility-score';
import { API_BASE_URL } from '@/config/api';
/**
@@ -53,6 +54,7 @@ export interface VisibilitySummary {
brand: { id: string; name: string };
totals: {
resultCount: number;
+ /** DEPRECATED — all-answers average of the legacy 0-100 intensity score. */
avgVisibility: number;
totalMentions: number;
totalCitations: number;
@@ -61,21 +63,30 @@ export interface VisibilitySummary {
/** Distinct prompts that produced results (shopping excluded). */
promptCount: number;
/**
- * Headline metric: visiblePrompts / promptCount × 100, rounded to one decimal.
- * Matches the Insights KPI card. Use this to describe how visible the brand is.
+ * DEPRECATED as the headline — coverage: visiblePrompts / promptCount ×
+ * 100. Kept for compatibility; prefer aiVisibilityScore.
*/
visibilityRatePct: number;
+ /**
+ * HEADLINE metric (0-100): 0.6 × mention rate + 0.25 × citation rate +
+ * 0.15 × position factor over the filtered answers. Matches the
+ * dashboard's Visibility number everywhere. Null when no answers.
+ */
+ aiVisibilityScore: number | null;
+ /** Answers mentioning the brand (score component). */
+ mentionAnswers: number;
+ /** Answers citing the brand's own domain (score component). */
+ citationAnswers: number;
+ /** Mean of 1/position over mentioning answers; null when never mentioned. */
+ positionFactor: number | null;
};
topCompetitors: Array<{
name: string;
mentions: number;
- /**
- * Average visibility score divided by the same denominator as the brand
- * (every filtered result row, not just rows where the competitor appeared).
- * This prevents inflated scores from competitors that only appear in their
- * best runs.
- */
+ /** DEPRECATED — legacy average intensity over the shared denominator. */
avgVisibility: number;
+ /** AI Visibility Score over the brand's answers (shared denominator). */
+ score: number | null;
}>;
}
@@ -146,15 +157,17 @@ export async function getVisibilitySummaryFor(
: query.eq('model_used', p_models_arg[0]);
}
- const [{ data: rows, error }, visibleRes, promptCountRes] = await Promise.all([
+ const [{ data: rows, error }, visibleRes, promptCountRes, aiVisRes] = await Promise.all([
query,
supabaseAdmin.rpc('visible_prompt_stats', rpcBaseArgs),
supabaseAdmin.rpc('tracked_prompt_count', rpcBaseArgs),
+ supabaseAdmin.rpc('ai_visibility_aggregates', rpcBaseArgs),
]);
if (error) throw new Error(error.message);
if (visibleRes.error) throw new Error(visibleRes.error.message);
if (promptCountRes.error) throw new Error(promptCountRes.error.message);
+ if (aiVisRes.error) throw new Error(aiVisRes.error.message);
const results = (rows ?? []) as Array<{
visibility_score: number;
@@ -176,6 +189,43 @@ export async function getVisibilitySummaryFor(
const visibilityRatePct =
promptCount > 0 ? Math.round((visiblePrompts / promptCount) * 1000) / 10 : 0;
+ // AI Visibility Score — the same blend every dashboard surface shows.
+ const aiVis = (aiVisRes.data ?? {}) as {
+ answers?: number;
+ mention_answers?: number;
+ citation_answers?: number;
+ position_factor?: number | null;
+ by_competitor?: Array<{
+ name: string | null;
+ mention_answers?: number;
+ citation_answers?: number;
+ position_factor?: number | null;
+ }>;
+ };
+ const aiAnswers = Number(aiVis.answers ?? 0);
+ const mentionAnswers = Number(aiVis.mention_answers ?? 0);
+ const citationAnswers = Number(aiVis.citation_answers ?? 0);
+ const positionFactor = aiVis.position_factor ?? null;
+ const aiVisibilityScore = computeAiVisibilityScore({
+ answers: aiAnswers,
+ mentionAnswers,
+ citationAnswers,
+ positionFactor,
+ });
+ const compScoreByName = new Map<string, number | null>();
+ for (const c of aiVis.by_competitor ?? []) {
+ if (!c.name) continue;
+ compScoreByName.set(
+ c.name,
+ computeAiVisibilityScore({
+ answers: aiAnswers,
+ mentionAnswers: Number(c.mention_answers ?? 0),
+ citationAnswers: Number(c.citation_answers ?? 0),
+ positionFactor: c.position_factor ?? null,
+ }),
+ );
+ }
+
if (results.length === 0) {
return {
brand: { id: brand.id, name: brand.name },
@@ -187,6 +237,10 @@ export async function getVisibilitySummaryFor(
visiblePrompts,
promptCount,
visibilityRatePct,
+ aiVisibilityScore,
+ mentionAnswers,
+ citationAnswers,
+ positionFactor,
},
topCompetitors: [],
};
@@ -223,6 +277,7 @@ export async function getVisibilitySummaryFor(
name,
mentions: agg.mentions,
avgVisibility: totalRows > 0 ? Math.round((agg.visSum / totalRows) * 10) / 10 : 0,
+ score: compScoreByName.get(name) ?? null,
}))
.sort((a, b) => b.mentions - a.mentions)
.slice(0, 5);
@@ -237,6 +292,10 @@ export async function getVisibilitySummaryFor(
visiblePrompts,
promptCount,
visibilityRatePct,
+ aiVisibilityScore,
+ mentionAnswers,
+ citationAnswers,
+ positionFactor,
},
topCompetitors,
};
@@ -1087,10 +1146,16 @@ export interface CompetitorComparisonOutput {
/** Distinct prompts that produced results (shared denominator for all entries). */
prompt_count: number;
/**
- * Headline metric: visible_prompts / prompt_count × 100.
- * Matches the Insights dashboard leaderboard. Use this for comparisons.
+ * DEPRECATED as the headline — coverage: visible_prompts / prompt_count
+ * × 100. Prefer ai_visibility_score.
*/
visibility_rate_pct: number;
+ /**
+ * HEADLINE metric (0-100): 0.6 × mention rate + 0.25 × citation rate +
+ * 0.15 × position factor over the brand's filtered answers. Matches the
+ * dashboard leaderboard. Null when the window has no answers.
+ */
+ ai_visibility_score: number | null;
};
competitors: Array<{
competitor_id: string;
@@ -1108,6 +1173,8 @@ export interface CompetitorComparisonOutput {
visibility_rate_pct: number;
/** Same prompt_count denominator as the brand for transparency. */
prompt_count: number;
+ /** AI Visibility Score over the brand's answers (shared denominator). */
+ ai_visibility_score: number | null;
}>;
share_of_voice: {
overall_sov_pct: number;
@@ -1201,12 +1268,46 @@ export async function getCompetitorComparisonFor(
// Both RPCs are SECURITY DEFINER per the existing pattern — they trust the
// caller's brand_id, which we've just verified above.
- const [compRes, sovRes] = await Promise.all([
+ const [compRes, sovRes, aiVisRes] = await Promise.all([
supabaseAdmin.rpc('competitor_aggregates', rpcArgs),
supabaseAdmin.rpc('share_of_voice_aggregates', rpcArgs),
+ supabaseAdmin.rpc('ai_visibility_aggregates', rpcArgs),
]);
if (compRes.error) throw new Error(compRes.error.message);
if (sovRes.error) throw new Error(sovRes.error.message);
+ if (aiVisRes.error) throw new Error(aiVisRes.error.message);
+
+ const aiVis = (aiVisRes.data ?? {}) as {
+ answers?: number;
+ mention_answers?: number;
+ citation_answers?: number;
+ position_factor?: number | null;
+ by_competitor?: Array<{
+ competitor_id: string;
+ mention_answers?: number;
+ citation_answers?: number;
+ position_factor?: number | null;
+ }>;
+ };
+ const aiAnswers = Number(aiVis.answers ?? 0);
+ const brandScore = computeAiVisibilityScore({
+ answers: aiAnswers,
+ mentionAnswers: Number(aiVis.mention_answers ?? 0),
+ citationAnswers: Number(aiVis.citation_answers ?? 0),
+ positionFactor: aiVis.position_factor ?? null,
+ });
+ const compScoreById = new Map<string, number | null>();
+ for (const c of aiVis.by_competitor ?? []) {
+ compScoreById.set(
+ c.competitor_id,
+ computeAiVisibilityScore({
+ answers: aiAnswers,
+ mentionAnswers: Number(c.mention_answers ?? 0),
+ citationAnswers: Number(c.citation_answers ?? 0),
+ positionFactor: c.position_factor ?? null,
+ }),
+ );
+ }
const comp = compRes.data as unknown as CompetitorAggRpc;
const sov = sovRes.data as unknown as SoVAggRpc;
@@ -1238,6 +1339,7 @@ export async function getCompetitorComparisonFor(
// directly comparable — matches the leaderboard semantics from PR #490.
visibility_rate_pct: rateOf(c.visible_prompts ?? 0, brandPromptCount),
prompt_count: brandPromptCount,
+ ai_visibility_score: compScoreById.get(c.competitor_id) ?? null,
}));
const totalBrandMentions = Number(sov.total_brand_mentions);
@@ -1269,6 +1371,7 @@ export async function getCompetitorComparisonFor(
visible_prompts: brandVisiblePrompts,
prompt_count: brandPromptCount,
visibility_rate_pct: brandRatePct,
+ ai_visibility_score: brandScore,
},
competitors,
share_of_voice: {
@@ -1640,6 +1743,12 @@ export interface VisibilityTrendOutput {
total_citations: number;
/** Average competitor visibility unwrapped from `competitor_mentions`. */
avg_competitor_score: number | null;
+ /**
+ * AI Visibility Score for the day (0-100) — the dashboard's Visibility
+ * number. Only populated for day granularity; null on week buckets and
+ * on payloads produced before the score shipped.
+ */
+ ai_visibility_score: number | null;
}>;
}
@@ -1690,17 +1799,51 @@ export async function getVisibilityTrendFor(
const granularity: VisibilityTrendGranularity = params.granularity ?? 'day';
- const { data, error } = await supabaseAdmin.rpc('visibility_trend_aggregates', {
- p_brand_id: params.brandId,
- p_models: p_models && p_models.length > 0 ? p_models : null,
- p_region: params.region ?? null,
- p_date_from: params.dateFrom ?? null,
- p_date_to: expandDateToEndOfDay(params.dateTo) ?? null,
- p_topic_id: params.topicId ?? null,
- p_granularity: granularity,
- });
+ const [{ data, error }, scoreRes] = await Promise.all([
+ supabaseAdmin.rpc('visibility_trend_aggregates', {
+ p_brand_id: params.brandId,
+ p_models: p_models && p_models.length > 0 ? p_models : null,
+ p_region: params.region ?? null,
+ p_date_from: params.dateFrom ?? null,
+ p_date_to: expandDateToEndOfDay(params.dateTo) ?? null,
+ p_topic_id: params.topicId ?? null,
+ p_granularity: granularity,
+ }),
+ // Per-day score components (00040); the trend RPC above only carries the
+ // legacy sums. Day buckets merge by date; week buckets keep null.
+ granularity === 'day'
+ ? supabaseAdmin.rpc('visibility_rate_trend', {
+ p_brand_id: params.brandId,
+ p_platform: null,
+ p_models: p_models && p_models.length > 0 ? p_models : null,
+ p_region: params.region ?? null,
+ p_date_from: params.dateFrom ?? null,
+ p_date_to: expandDateToEndOfDay(params.dateTo) ?? null,
+ p_topic_id: params.topicId ?? null,
+ })
+ : Promise.resolve({ data: null, error: null }),
+ ]);
if (error) throw new Error(error.message);
+ const scoreByDay = new Map<string, number | null>();
+ for (const row of (scoreRes.data ?? []) as unknown as Array<{
+ day: string;
+ answers: number;
+ mention_answers: number;
+ citation_answers: number;
+ position_factor: number | null;
+ }>) {
+ scoreByDay.set(
+ row.day,
+ computeAiVisibilityScore({
+ answers: Number(row.answers ?? 0),
+ mentionAnswers: Number(row.mention_answers ?? 0),
+ citationAnswers: Number(row.citation_answers ?? 0),
+ positionFactor: row.position_factor ?? null,
+ }),
+ );
+ }
+
const raw = (data as unknown as VisibilityTrendBucketRpc[]) ?? [];
const buckets = raw.map((b) => ({
date: b.bucket_date,
@@ -1711,6 +1854,7 @@ export async function getVisibilityTrendFor(
total_citations: Number(b.sum_citations),
avg_competitor_score:
b.comp_count > 0 ? Math.round(Number(b.comp_sum_visibility) / Number(b.comp_count)) : null,
+ ai_visibility_score: scoreByDay.get(b.bucket_date) ?? null,
}));
return { granularity, buckets };
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index 2d25d3d59..85af714e1 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -69,13 +69,15 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
{
description:
'Get aggregate visibility metrics for a brand over an optional date range and filter. ' +
- 'The headline metric is visibilityRatePct (totals.visibilityRatePct): the percentage of ' +
- 'tracked prompts the brand appeared in (distinct visible prompts ÷ distinct prompts with ' +
- 'results, shopping excluded). This matches the Insights KPI card — use it when describing ' +
- 'how visible a brand is. Also returns totals.avgVisibility (0-100 intensity score over all ' +
- 'result rows), totals.visiblePrompts, totals.promptCount, total mentions, total citations, ' +
- 'and the top 5 competitors by mention count with avgVisibility divided by the same ' +
- "denominator as the brand (not just the competitor's own appearances). " +
+ 'The HEADLINE metric is totals.aiVisibilityScore (0-100): 0.6 × mention rate + 0.25 × ' +
+ 'citation rate + 0.15 × position factor over the filtered answers — the same Visibility ' +
+ 'number the dashboard shows everywhere; quote it WITHOUT a % sign. Components are ' +
+ 'totals.mentionAnswers, totals.citationAnswers and totals.positionFactor (mean of ' +
+ '1/position over mentioning answers; 1 = always named first). Coverage survives as ' +
+ 'totals.visibilityRatePct (visible prompts ÷ tracked prompts, a percentage) with ' +
+ 'totals.visiblePrompts / totals.promptCount. totals.avgVisibility and the competitors’ ' +
+ 'avgVisibility are DEPRECATED legacy intensity averages — prefer each competitor’s ' +
+ '`score`, which shares the brand’s denominator. ' +
'Use this for "how is my brand doing" / "what changed" style questions.',
inputSchema: {
brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 8d4cfcd41..e95422f89 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -1452,6 +1452,7 @@ export type Database = {
Args: {
p_brand_id: string;
p_date_from?: string | null;
+ p_date_to?: string | null;
};
Returns: {
prompt_id: string;