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.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(mcp): expose get_visibility_trend tool (visibility time-series) + REST endpoint (#118)
Gökhan Geyika6ff5d6ae7db
diff --git a/supabase/migrations/00008_visibility_trend_aggregates.sql b/supabase/migrations/00008_visibility_trend_aggregates.sqlnew file mode 100644index 000000000..880a358a1--- /dev/null+++ b/supabase/migrations/00008_visibility_trend_aggregates.sql@@ -0,0 +1,98 @@+-- DB-side aggregation for the visibility-over-time trend (#96).+--+-- The existing getVisibilityTrend in actions/tracking.ts fetches every+-- prompt_results row in the window and folds by day in JS. That works for+-- one user loading the insights page; it scales badly for an MCP client+-- (e.g. the planned in-product assistant in #94) firing repeated trend+-- queries — each call ships back tens of MB of jsonb rows just to be+-- reduced to a handful of date buckets. This RPC mirrors the structural+-- decisions of 00006 (the insights / competitor / SoV aggregates): one+-- jsonb-shaped return, raw sums + counts, ORDER BY inside jsonb_agg for+-- a stable response, and SECURITY DEFINER for symmetry with the other+-- aggregate RPCs (org-membership enforcement is tracked in #115).+--+-- Granularity is constrained to 'day' or 'week' so the response shape+-- stays predictable for chart-rendering consumers. date_trunc would+-- happily accept 'month' / 'year' too, but exposing those introduces+-- empty-bucket ambiguity at the assistant layer; if a caller wants+-- monthly aggregation today they can group the daily buckets client+-- side.+CREATE OR REPLACE FUNCTION public.visibility_trend_aggregates(+ p_brand_id uuid,+ p_models text[] DEFAULT NULL,+ p_region text DEFAULT NULL,+ p_date_from timestamptz DEFAULT NULL,+ p_date_to timestamptz DEFAULT NULL,+ p_topic_id uuid DEFAULT NULL,+ p_granularity text DEFAULT 'day'+)+RETURNS jsonb+LANGUAGE sql+STABLE+SECURITY DEFINER+SET search_path = public+AS $$+ WITH filtered AS (+ SELECT pr.visibility_score, pr.mention_count, pr.citation_count,+ pr.created_at, pr.competitor_mentions+ FROM public.prompt_results pr+ WHERE pr.brand_id = p_brand_id+ AND (p_models IS NULL OR pr.model_used = ANY (p_models))+ AND (p_region IS NULL OR pr.region = p_region)+ 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)+ AND (p_topic_id IS NULL OR EXISTS (+ SELECT 1 FROM public.prompts p+ WHERE p.id = pr.prompt_id AND p.topic_id = p_topic_id))+ ),+ buckets AS (+ SELECT+ -- Bucket key always stored as YYYY-MM-DD in UTC so callers can sort+ -- lexicographically and so the JS reducer doesn't have to think about+ -- the server's timezone. For weeks, this is the Monday-start ISO week+ -- per Postgres's date_trunc semantics.+ to_char(+ date_trunc(p_granularity, created_at AT TIME ZONE 'UTC'),+ 'YYYY-MM-DD'+ ) AS bucket_date,+ COUNT(*) AS row_count,+ COALESCE(SUM(visibility_score), 0) AS sum_visibility,+ COALESCE(SUM(mention_count), 0)::bigint AS sum_mentions,+ COALESCE(SUM(citation_count), 0)::bigint AS sum_citations,+ -- Competitor mentions are unnested per-row, then summed. We sum inside+ -- a correlated subquery so a row with five competitor entries+ -- contributes once per entry rather than five times to the brand+ -- numbers above.+ COALESCE(SUM((+ SELECT COALESCE(SUM((cm.value->>'visibility_score')::numeric), 0)+ FROM jsonb_array_elements(COALESCE(competitor_mentions, '[]'::jsonb)) cm+ )), 0) AS comp_sum_visibility,+ COALESCE(SUM((+ SELECT COUNT(*)+ FROM jsonb_array_elements(COALESCE(competitor_mentions, '[]'::jsonb)) cm+ )), 0)::bigint AS comp_count+ FROM filtered+ GROUP BY to_char(+ date_trunc(p_granularity, created_at AT TIME ZONE 'UTC'),+ 'YYYY-MM-DD'+ )+ )+ SELECT COALESCE(+ (SELECT jsonb_agg(+ jsonb_build_object(+ 'bucket_date', b.bucket_date,+ 'row_count', b.row_count,+ 'sum_visibility', b.sum_visibility,+ 'sum_mentions', b.sum_mentions,+ 'sum_citations', b.sum_citations,+ 'comp_sum_visibility', b.comp_sum_visibility,+ 'comp_count', b.comp_count+ )+ ORDER BY b.bucket_date)+ FROM buckets b),+ '[]'::jsonb);+$$;++GRANT EXECUTE ON FUNCTION+ public.visibility_trend_aggregates(uuid, text[], text, timestamptz, timestamptz, uuid, text)+ TO authenticated, service_role;diff --git a/web/src/app/api/mcp/visibility-trend/route.ts b/web/src/app/api/mcp/visibility-trend/route.tsnew file mode 100644index 000000000..8cef8818a--- /dev/null+++ b/web/src/app/api/mcp/visibility-trend/route.ts@@ -0,0 +1,50 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { getVisibilityTrendFor, type VisibilityTrendGranularity } from '@/lib/mcp/data';++/**+ * GET /api/mcp/visibility-trend+ *+ * Parallel REST surface for the `get_visibility_trend` MCP tool — same+ * data-layer function, same ownership guarantee. Query params mirror the+ * MCP args: brand_id (required), date_from, date_to, granularity, model,+ * region, topic_id.+ */+export async function GET(req: Request) {+ const auth = await authenticateMcpRequest(req);+ if (auth instanceof NextResponse) return auth;++ const url = new URL(req.url);+ const brandId = url.searchParams.get('brand_id');+ if (!brandId) {+ return NextResponse.json({ error: 'brand_id is required' }, { status: 400 });+ }++ const granularityParam = url.searchParams.get('granularity');+ let granularity: VisibilityTrendGranularity | undefined;+ if (granularityParam !== null) {+ if (granularityParam !== 'day' && granularityParam !== 'week') {+ return NextResponse.json({ error: 'granularity must be "day" or "week"' }, { status: 400 });+ }+ granularity = granularityParam;+ }++ try {+ const result = await getVisibilityTrendFor(auth, {+ brandId,+ dateFrom: url.searchParams.get('date_from') ?? undefined,+ dateTo: url.searchParams.get('date_to') ?? undefined,+ model: url.searchParams.get('model') ?? undefined,+ region: url.searchParams.get('region') ?? undefined,+ topicId: url.searchParams.get('topic_id') ?? undefined,+ granularity,+ });+ if (!result) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });+ }+ return NextResponse.json(result);+ } catch (err) {+ const message = err instanceof Error ? err.message : 'Failed';+ return NextResponse.json({ error: message }, { status: 500 });+ }+}diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.tsindex bd99d44c1..c58851f26 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -1084,3 +1084,105 @@ export async function listCitationsFor(top_urls: topUrls,};}++// ── Visibility trend ────────────────────────────────────────────────────────++export type VisibilityTrendGranularity = 'day' | 'week';++export interface VisibilityTrendParams {+ brandId: string;+ dateFrom?: string;+ dateTo?: string;+ /** Comma-separated model_used slugs (e.g. `gpt-4o,claude-sonnet-4-6`). */+ model?: string;+ region?: string;+ topicId?: string;+ granularity?: VisibilityTrendGranularity;+}++export interface VisibilityTrendOutput {+ granularity: VisibilityTrendGranularity;+ buckets: Array<{+ /** UTC bucket key in `YYYY-MM-DD` (week bucket = the ISO Monday). */+ date: string;+ result_count: number;+ avg_visibility_score: number;+ total_mentions: number;+ total_citations: number;+ /** Average competitor visibility unwrapped from `competitor_mentions`. */+ avg_competitor_score: number | null;+ }>;+}++interface VisibilityTrendBucketRpc {+ bucket_date: string;+ row_count: number;+ sum_visibility: number;+ sum_mentions: number;+ sum_citations: number;+ comp_sum_visibility: number;+ comp_count: number;+}++/**+ * Visibility / mentions / citations over time for a brand, with the+ * competitor average pulled out of `competitor_mentions` per row so a chart+ * can plot brand vs. competitor lines side by side.+ *+ * Aggregates server-side via the `visibility_trend_aggregates` RPC introduced+ * in 00008 — same pattern as the insights / competitor / SoV surfaces from+ * #114. The JS layer only divides and rounds; the row scan stays in+ * Postgres. Designed for the chart-rendering surfaces in the planned+ * in-product assistant (#94), which can fire a lot of these.+ *+ * Ownership-check first; wrong-org or missing brand returns null (→ 404)+ * before the RPC fires.+ */+export async function getVisibilityTrendFor(+ auth: McpAuthContext,+ params: VisibilityTrendParams,+): Promise<VisibilityTrendOutput | null> {+ if (!auth.organizationId) return null;++ const { data: brand } = await supabaseAdmin+ .from('brands')+ .select('id')+ .eq('id', params.brandId)+ .eq('organization_id', auth.organizationId)+ .maybeSingle();+ if (!brand) return null;++ const p_models = params.model+ ? params.model+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean)+ : null;++ 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: params.dateTo ?? null,+ p_topic_id: params.topicId ?? null,+ p_granularity: granularity,+ });+ if (error) throw new Error(error.message);++ const raw = (data as unknown as VisibilityTrendBucketRpc[]) ?? [];+ const buckets = raw.map((b) => ({+ date: b.bucket_date,+ result_count: Number(b.row_count),+ avg_visibility_score:+ b.row_count > 0 ? Math.round(Number(b.sum_visibility) / Number(b.row_count)) : 0,+ total_mentions: Number(b.sum_mentions),+ 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,+ }));++ return { granularity, buckets };+}diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex 50ecfa249..a8b3bffd6 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -8,6 +8,7 @@ import {getCompetitorComparisonFor,getContentOpportunityFor,getVisibilitySummaryFor,+ getVisibilityTrendFor,listBrandsFor,listCitationsFor,listContentOpportunitiesFor,@@ -385,5 +386,57 @@ export function createMcpServer(auth: McpAuthContext): McpServer {},);+ server.registerTool(+ 'get_visibility_trend',+ {+ description:+ 'Get a brand\'s visibility over time for a date range, bucketed by day or week. Returns one bucket per period with result_count, avg_visibility_score (0-100), total_mentions, total_citations, and avg_competitor_score (mean of competitor visibility scores from the same period, or null if no competitors were mentioned). Use this for "how has my visibility changed?" trend questions and to render brand-vs-competitor line charts. Complements get_visibility_summary, which is a single-window snapshot.',+ inputSchema: {+ brand_id: z.string().uuid().describe('Brand UUID, from list_brands.'),+ date_from: z+ .string()+ .optional()+ .describe('ISO timestamp (inclusive) lower bound, e.g. 2026-05-01T00:00:00Z.'),+ date_to: z.string().optional().describe('ISO timestamp (inclusive) upper bound.'),+ granularity: z+ .enum(['day', 'week'])+ .optional()+ .describe('Bucket size — "day" (default) or "week" (ISO Monday-start weeks).'),+ model: z+ .string()+ .optional()+ .describe(+ 'Optional model slug filter, or comma-separated list of slugs to filter a provider family.',+ ),+ region: z.string().optional().describe('Optional region code filter (e.g. "US", "TR").'),+ topic_id: z+ .string()+ .uuid()+ .optional()+ .describe('Optional topic UUID (from list_topics) to restrict to one topic.'),+ },+ },+ async (args) => {+ const result = await getVisibilityTrendFor(auth, {+ brandId: args.brand_id,+ dateFrom: args.date_from,+ dateTo: args.date_to,+ model: args.model,+ region: args.region,+ topicId: args.topic_id,+ granularity: args.granularity,+ });+ if (!result) {+ return {+ content: [{ type: 'text', text: 'Brand not found' }],+ isError: true,+ };+ }+ return {+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],+ };+ },+ );+return server;}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex e8b99b06c..a57aabc74 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -899,6 +899,18 @@ export type Database = {};Returns: Json;};+ visibility_trend_aggregates: {+ Args: {+ p_brand_id: string;+ p_models?: string[] | null;+ p_region?: string | null;+ p_date_from?: string | null;+ p_date_to?: string | null;+ p_topic_id?: string | null;+ p_granularity?: string | null;+ };+ Returns: Json;+ };share_of_voice_aggregates: {Args: {p_brand_id: string;