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): add read-only competitor and report tools (#1156)
Sanjeev Kumar30ff03ae999d
diff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdxindex 8706dc63d..816d8821a 100644--- a/docs/guides/mcp-server.mdx+++ b/docs/guides/mcp-server.mdx@@ -220,7 +220,7 @@ instead.## Available tools-The MCP server exposes **30 tools**. Descriptions below match+The MCP server exposes **33 tools**. Descriptions below match[`web/src/lib/mcp/server.ts`](https://github.com/ansvisor/ansvisor/blob/main/web/src/lib/mcp/server.ts).Tools that change data are marked **writes** — only call them on explicit userintent, not during exploratory queries.@@ -230,6 +230,7 @@ intent, not during exploratory queries.| Tool | What it does | Writes || --- | --- | --- || `list_brands` | List the brands the authenticated user can access (id, name, slug, industry, region). Call first to resolve a `brand_id`. | |+| `list_competitors` | Configured competitors for a brand (id, name, domain); this is not a performance ranking. | |### Visibility & analytics@@ -242,6 +243,13 @@ intent, not during exploratory queries.| `get_ai_traffic` | AI-referral traffic (visits by engine, landing pages, countries) for an optional date range. | || `get_prompt_performance` | Per-prompt performance (visibility, mentions, citations, appearances) over a date range for ranking prompts. | |+### Saved reports++| Tool | What it does | Writes |+| --- | --- | --- |+| `list_reports` | Saved report snapshots for a brand, newest first; returns metadata without the full payload (default 50, max 100 per call). | |+| `get_report` | Full immutable snapshot for one saved report, including its stored payload; does not regenerate it. | |+### Topics & prompts| Tool | What it does | Writes |diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.tsindex c835ad781..87bf72ffa 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -3116,3 +3116,138 @@ export async function createImproveActionFor(taskCount: body.taskCount,};}++// ── Read-only competitor and report tools (#918) ────────────────────────────++export interface McpCompetitorRow {+ id: string;+ name: string;+ domain: string;+}++/**+ * List a brand's competitors only after confirming the brand belongs to the+ * authenticated organization. The joined ownership predicate on the data+ * query prevents a brand reassignment between the check and the read.+ */+export async function listCompetitorsFor(+ auth: McpAuthContext,+ brandId: string,+): Promise<McpCompetitorRow[] | null> {+ if (!auth.organizationId) return null;++ const { data: brand, error: brandError } = await supabaseAdmin+ .from('brands')+ .select('id')+ .eq('id', brandId)+ .eq('organization_id', auth.organizationId)+ .maybeSingle();+ if (brandError) throw new Error(brandError.message);+ if (!brand) return null;++ const { data, error } = await supabaseAdmin+ .from('competitors')+ .select('id, name, domain, brands!inner(organization_id)')+ .eq('brand_id', brandId)+ .eq('brands.organization_id', auth.organizationId)+ .order('created_at', { ascending: true });+ if (error) throw new Error(error.message);++ return (data ?? []).map((row) => ({+ id: row.id as string,+ name: row.name as string,+ domain: (row.domain as string | null) ?? '',+ }));+}++export interface McpReportListItem {+ id: string;+ brand_id: string;+ title: string;+ template: string;+ date_from: string;+ date_to: string;+ created_at: string;+}++/**+ * List saved immutable report snapshots for an organization-owned brand.+ * The database query repeats the ownership predicate to avoid a TOCTOU leak.+ */+export async function listReportsFor(+ auth: McpAuthContext,+ brandId: string,+ requestedLimit = 50,+): Promise<McpReportListItem[] | null> {+ if (!auth.organizationId) return null;++ const { data: brand, error: brandError } = await supabaseAdmin+ .from('brands')+ .select('id')+ .eq('id', brandId)+ .eq('organization_id', auth.organizationId)+ .maybeSingle();+ if (brandError) throw new Error(brandError.message);+ if (!brand) return null;++ const limit = Number.isFinite(requestedLimit)+ ? Math.min(Math.max(Math.trunc(requestedLimit), 1), 100)+ : 50;+ const { data, error } = await supabaseAdmin+ .from('reports')+ .select(+ 'id, brand_id, title, template, date_from, date_to, created_at, brands!inner(organization_id)',+ )+ .eq('brand_id', brandId)+ .eq('brands.organization_id', auth.organizationId)+ .order('created_at', { ascending: false })+ .limit(limit);+ if (error) throw new Error(error.message);++ return (data ?? []).map((row) => ({+ id: row.id as string,+ brand_id: row.brand_id as string,+ title: row.title as string,+ template: row.template as string,+ date_from: row.date_from as string,+ date_to: row.date_to as string,+ created_at: row.created_at as string,+ }));+}++export interface McpReportDetail extends McpReportListItem {+ payload: unknown;+}++/**+ * Read a saved report only if its parent brand belongs to the authenticated+ * organization. The joined ownership predicate is applied in the database.+ */+export async function getReportFor(+ auth: McpAuthContext,+ reportId: string,+): Promise<McpReportDetail | null> {+ if (!auth.organizationId) return null;++ const { data, error } = await supabaseAdmin+ .from('reports')+ .select(+ 'id, brand_id, title, template, date_from, date_to, created_at, payload, brands!inner(organization_id)',+ )+ .eq('id', reportId)+ .eq('brands.organization_id', auth.organizationId)+ .maybeSingle();+ if (error) throw new Error(error.message);+ if (!data) return null;++ return {+ id: data.id as string,+ brand_id: data.brand_id as string,+ title: data.title as string,+ template: data.template as string,+ date_from: data.date_from as string,+ date_to: data.date_to as string,+ created_at: data.created_at as string,+ payload: data.payload,+ };+}diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex fc5789305..8f9aa4a11 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -8,6 +8,9 @@ import {dismissTopicSuggestionFor,generateBriefFor,getCompetitorComparisonFor,+ listCompetitorsFor,+ listReportsFor,+ getReportFor,getContentOpportunityFor,getVisibilitySummaryFor,getVisibilityTrendFor,@@ -264,6 +267,82 @@ export function createMcpServer(auth: McpAuthContext): McpServer {},);+ server.registerTool(+ 'list_competitors',+ {+ description:+ 'List the competitors configured for a brand. Returns only id, name, and domain. Use list_brands first to resolve the brand id. This is the configured competitor list, not a performance ranking.',+ inputSchema: {+ brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),+ },+ },+ async (args) => {+ const competitors = await listCompetitorsFor(auth, args.brand_id);+ if (competitors === null) {+ return {+ content: [{ type: 'text', text: 'Brand not found' }],+ isError: true,+ };+ }+ return {+ content: [{ type: 'text', text: JSON.stringify(competitors, null, 2) }],+ };+ },+ );++ server.registerTool(+ 'list_reports',+ {+ description:+ 'List saved report snapshots for a brand, newest first. Returns report ids, titles, templates, date ranges, and creation timestamps without loading the full report payload. Use get_report to read one report in full.',+ inputSchema: {+ brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),+ limit: z+ .number()+ .int()+ .min(1)+ .max(100)+ .optional()+ .describe('Maximum number of reports to return (default 50, max 100).'),+ },+ },+ async (args) => {+ const reports = await listReportsFor(auth, args.brand_id, args.limit);+ if (reports === null) {+ return {+ content: [{ type: 'text', text: 'Brand not found' }],+ isError: true,+ };+ }+ return {+ content: [{ type: 'text', text: JSON.stringify(reports, null, 2) }],+ };+ },+ );++ server.registerTool(+ 'get_report',+ {+ description:+ 'Get the full saved snapshot for one report, including its stored payload and metrics. This is read-only and does not regenerate the report. Use a report id from list_reports.',+ inputSchema: {+ report_id: relaxedUuid.describe('Saved report UUID, from list_reports.'),+ },+ },+ async (args) => {+ const report = await getReportFor(auth, args.report_id);+ if (!report) {+ return {+ content: [{ type: 'text', text: 'Report not found' }],+ isError: true,+ };+ }+ return {+ content: [{ type: 'text', text: JSON.stringify(report, null, 2) }],+ };+ },+ );+server.registerTool('list_content_opportunities',{