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_competitor_comparison tool (with share of voice) + REST endpoint (#116)
Gökhan Geyik3ced37640fc3
diff --git a/web/src/app/api/mcp/competitor-comparison/route.ts b/web/src/app/api/mcp/competitor-comparison/route.tsnew file mode 100644index 000000000..a5ae7d0c0--- /dev/null+++ b/web/src/app/api/mcp/competitor-comparison/route.ts@@ -0,0 +1,39 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { getCompetitorComparisonFor } from '@/lib/mcp/data';++/**+ * GET /api/mcp/competitor-comparison+ *+ * Parallel REST surface for the `get_competitor_comparison` MCP tool — same+ * data-layer function, same ownership guarantee. Query params mirror the MCP+ * tool's args: brand_id (required), date_from, date_to, 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 });+ }++ try {+ const result = await getCompetitorComparisonFor(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,+ });+ 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 1535c41a4..aaeb01159 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -615,3 +615,176 @@ export async function updateOpportunityStatusFor(updated_at: data.updated_at ?? updatedAt,};}++// ── Competitor comparison + share of voice ───────────────────────────────────++export interface CompetitorComparisonParams {+ brandId: string;+ model?: string;+ region?: string;+ dateFrom?: string;+ dateTo?: string;+ topicId?: string;+}++export interface CompetitorComparisonOutput {+ brand: {+ id: string;+ name: string;+ avg_visibility_score: number;+ total_mentions: number;+ total_citations: number;+ appearance_count: number;+ };+ competitors: Array<{+ competitor_id: string;+ name: string;+ avg_visibility_score: number;+ total_mentions: number;+ total_citations: number;+ appearance_count: number;+ }>;+ share_of_voice: {+ overall_sov_pct: number;+ total_brand_mentions: number;+ total_competitor_mentions: number;+ by_platform: Array<{+ model_used: string | null;+ platform: string | null;+ brand_mentions: number;+ competitor_mentions: number;+ sov_pct: number;+ }>;+ };+}++interface CompetitorAggRpc {+ brand_row_count: number;+ brand_sum_visibility: number;+ brand_total_mentions: number;+ brand_total_citations: number;+ by_competitor: Array<{+ competitor_id: string;+ name: string | null;+ sum_visibility: number;+ row_count: number;+ total_mentions: number;+ total_citations: number;+ }>;+}++interface SoVAggRpc {+ total_brand_mentions: number;+ total_competitor_mentions: number;+ by_platform: Array<{+ model_used: string | null;+ platform: string | null;+ brand_mentions: number;+ competitor_mentions: number;+ }>;+}++/**+ * Return a brand's competitor benchmark + share of voice for a window. Combines+ * two existing RPCs (`competitor_aggregates`, `share_of_voice_aggregates`) so the+ * MCP tool and REST surface answer "how do I compare?" / "who's gaining share of+ * voice?" in one round trip.+ *+ * Ownership-check first — wrong-org or missing brand returns null (→ 404+ * upstream) before either RPC fires. Deltas vs a previous window are out of+ * scope for V1 (matches the snapshot-shaped existing MCP tools); a caller that+ * wants a delta can issue a second tool call for the prior period.+ */+export async function getCompetitorComparisonFor(+ auth: McpAuthContext,+ params: CompetitorComparisonParams,+): Promise<CompetitorComparisonOutput | null> {+ if (!auth.organizationId) return null;++ // Ownership check + grab brand name in one query.+ const { data: brand } = await supabaseAdmin+ .from('brands')+ .select('id, name')+ .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 rpcArgs = {+ p_brand_id: params.brandId,+ p_platform: null as string | 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: params.dateTo ?? null,+ p_prompt_id: null as string | null,+ p_topic_id: params.topicId ?? null,+ };++ // 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([+ supabaseAdmin.rpc('competitor_aggregates', rpcArgs),+ supabaseAdmin.rpc('share_of_voice_aggregates', rpcArgs),+ ]);+ if (compRes.error) throw new Error(compRes.error.message);+ if (sovRes.error) throw new Error(sovRes.error.message);++ const comp = compRes.data as unknown as CompetitorAggRpc;+ const sov = sovRes.data as unknown as SoVAggRpc;++ const brandAvg =+ comp.brand_row_count > 0 ? Math.round(comp.brand_sum_visibility / comp.brand_row_count) : 0;++ const competitors = comp.by_competitor.map((c) => ({+ competitor_id: c.competitor_id,+ name: c.name && c.name.trim() !== '' ? c.name : c.competitor_id,+ avg_visibility_score: c.row_count > 0 ? Math.round(Number(c.sum_visibility) / c.row_count) : 0,+ total_mentions: Number(c.total_mentions),+ total_citations: Number(c.total_citations),+ appearance_count: c.row_count,+ }));++ const totalBrandMentions = Number(sov.total_brand_mentions);+ const totalCompMentions = Number(sov.total_competitor_mentions);+ const totalAll = totalBrandMentions + totalCompMentions;+ const overallSovPct = totalAll > 0 ? Math.round((totalBrandMentions / totalAll) * 1000) / 10 : 0;++ const byPlatform = sov.by_platform.map((bp) => {+ const brandM = Number(bp.brand_mentions);+ const compM = Number(bp.competitor_mentions);+ const total = brandM + compM;+ return {+ model_used: bp.model_used,+ platform: bp.platform,+ brand_mentions: brandM,+ competitor_mentions: compM,+ sov_pct: total > 0 ? Math.round((brandM / total) * 1000) / 10 : 0,+ };+ });++ return {+ brand: {+ id: brand.id,+ name: brand.name,+ avg_visibility_score: brandAvg,+ total_mentions: Number(comp.brand_total_mentions),+ total_citations: Number(comp.brand_total_citations),+ appearance_count: comp.brand_row_count,+ },+ competitors,+ share_of_voice: {+ overall_sov_pct: overallSovPct,+ total_brand_mentions: totalBrandMentions,+ total_competitor_mentions: totalCompMentions,+ by_platform: byPlatform,+ },+ };+}diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex 7c1b794cb..f47f43877 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -5,6 +5,7 @@ import type { McpAuthContext } from '@/lib/mcp-auth';import {CONTENT_OPPORTUNITY_STATUSES,generateBriefFor,+ getCompetitorComparisonFor,getContentOpportunityFor,getVisibilitySummaryFor,listBrandsFor,@@ -281,5 +282,52 @@ export function createMcpServer(auth: McpAuthContext): McpServer {},);+ server.registerTool(+ 'get_competitor_comparison',+ {+ description:+ 'Get a brand\'s competitor benchmark and share of voice for a window. Returns the brand and every tracked competitor with avg visibility score (0-100), total mentions, total citations, and how many tracked prompt results each appeared in. Also returns overall share-of-voice as a percentage (brand mentions / (brand + competitor mentions)) and the same split per (model_used, platform). Use this for "how do I compare to my competitors?" or "who is gaining share of voice?" style questions. This is a snapshot for the given window — call again with an earlier window to compute a delta.',+ 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.'),+ 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 getCompetitorComparisonFor(auth, {+ brandId: args.brand_id,+ dateFrom: args.date_from,+ dateTo: args.date_to,+ model: args.model,+ region: args.region,+ topicId: args.topic_id,+ });+ if (!result) {+ return {+ content: [{ type: 'text', text: 'Brand not found' }],+ isError: true,+ };+ }+ return {+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],+ };+ },+ );+return server;}