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 content opportunities through MCP tools and REST endpoints (#74)
Baqirrizvidev5f3304e9a76d
diff --git a/web/src/app/api/mcp/content-opportunities/[id]/route.ts b/web/src/app/api/mcp/content-opportunities/[id]/route.tsnew file mode 100644index 000000000..db0fcb679--- /dev/null+++ b/web/src/app/api/mcp/content-opportunities/[id]/route.ts@@ -0,0 +1,31 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { getContentOpportunityFor } from '@/lib/mcp/data';++export async function GET(+ req: Request,+ { params }: { params: Promise<{ id: string }> },+) {+ const auth = await authenticateMcpRequest(req);+ if (auth instanceof NextResponse) return auth;++ const resolvedParams = await params;+ const opportunityId = resolvedParams.id;+ if (!opportunityId) {+ return NextResponse.json({ error: 'id is required' }, { status: 400 });+ }++ try {+ const opportunity = await getContentOpportunityFor(auth, opportunityId);+ if (!opportunity) {+ return NextResponse.json(+ { error: 'Content opportunity not found' },+ { status: 404 },+ );+ }+ return NextResponse.json({ opportunity });+ } catch (err) {+ const message = err instanceof Error ? err.message : 'Failed';+ return NextResponse.json({ error: message }, { status: 500 });+ }+}diff --git a/web/src/app/api/mcp/content-opportunities/route.ts b/web/src/app/api/mcp/content-opportunities/route.tsnew file mode 100644index 000000000..813f9bc71--- /dev/null+++ b/web/src/app/api/mcp/content-opportunities/route.ts@@ -0,0 +1,59 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { listContentOpportunitiesFor } from '@/lib/mcp/data';++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 statusRaw = url.searchParams.get('status');+ const impactRaw = url.searchParams.get('impact');+ const typeRaw = url.searchParams.get('type');+ const limitRaw = url.searchParams.get('limit');++ const status =+ statusRaw === 'new' ||+ statusRaw === 'sent' ||+ statusRaw === 'in_progress' ||+ statusRaw === 'done' ||+ statusRaw === 'dismissed'+ ? statusRaw+ : undefined;++ const impact =+ impactRaw === 'high' || impactRaw === 'medium' || impactRaw === 'low'+ ? impactRaw+ : undefined;++ const type =+ typeRaw === 'owned' || typeRaw === 'earned'+ ? typeRaw+ : undefined;++ const limit = limitRaw ? Number.parseInt(limitRaw, 10) : undefined;++ try {+ const opportunities = await listContentOpportunitiesFor(auth, {+ brandId,+ status,+ impact,+ type,+ limit: Number.isFinite(limit) ? limit : undefined,+ });++ if (opportunities === null) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });+ }++ return NextResponse.json({ opportunities });+ } 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 bb588d119..6f6c377fc 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -321,3 +321,166 @@ export async function listPromptsFor(};});}++// ── Content Opportunities ───────────────────────────────────────────────────++export interface ContentOpportunityRow {+ id: string;+ title: string;+ description: string | null;+ type: string;+ impact: string;+ opportunity_score: number;+ status: string;+ prompt_id: string | null;+ prompt_text: string | null;+ has_brief: boolean;+ created_at: string;+ updated_at: string;+}++export interface ListContentOpportunitiesParams {+ brandId: string;+ status?: 'new' | 'sent' | 'in_progress' | 'done' | 'dismissed';+ impact?: 'high' | 'medium' | 'low';+ type?: 'owned' | 'earned';+ limit?: number;+}++export async function listContentOpportunitiesFor(+ auth: McpAuthContext,+ params: ListContentOpportunitiesParams,+): Promise<ContentOpportunityRow[] | null> {+ if (!auth.organizationId) return null;++ // Ownership check+ const { data: brand } = await supabaseAdmin+ .from('brands')+ .select('id')+ .eq('id', params.brandId)+ .eq('organization_id', auth.organizationId)+ .maybeSingle();+ if (!brand) return null;++ const limit = Math.min(Math.max(params.limit ?? 50, 1), 200);++ let query = supabaseAdmin+ .from('content_opportunities')+ .select(+ 'id, title, description, type, impact, opportunity_score, status, prompt_id, created_at, updated_at, brief, prompts(text)',+ )+ .eq('brand_id', params.brandId)+ .order('opportunity_score', { ascending: false })+ .order('created_at', { ascending: false })+ .limit(limit);++ if (params.status) query = query.eq('status', params.status);+ if (params.impact) query = query.eq('impact', params.impact);+ if (params.type) query = query.eq('type', params.type);++ const { data, error } = await query;+ if (error) throw new Error(error.message);++ const rows =+ (data as unknown as Array<{+ id: string;+ title: string;+ description: string | null;+ type: string;+ impact: string;+ opportunity_score: number | null;+ status: string;+ prompt_id: string | null;+ created_at: string | null;+ updated_at: string | null;+ brief: any | null;+ prompts: Array<{ text: string }> | { text: string } | null;+ }> | null) ?? [];++ return rows.map((r) => {+ const prompt = Array.isArray(r.prompts) ? r.prompts[0] ?? null : r.prompts;+ return {+ id: r.id,+ title: r.title,+ description: r.description,+ type: r.type,+ impact: r.impact,+ opportunity_score: Number(r.opportunity_score ?? 0),+ status: r.status,+ prompt_id: r.prompt_id,+ prompt_text: prompt?.text ?? null,+ has_brief: r.brief !== null,+ created_at: r.created_at ?? '',+ updated_at: r.updated_at ?? '',+ };+ });+}++export interface ContentOpportunityDetail {+ id: string;+ title: string;+ description: string | null;+ type: string;+ impact: string;+ opportunity_score: number;+ status: string;+ prompt_id: string | null;+ prompt_text: string | null;+ source_data: Record<string, any> | null;+ brief: Record<string, any> | null;+ created_at: string;+ updated_at: string;+}++export async function getContentOpportunityFor(+ auth: McpAuthContext,+ opportunityId: string,+): Promise<ContentOpportunityDetail | null> {+ if (!auth.organizationId) return null;++ const { data, error } = await supabaseAdmin+ .from('content_opportunities')+ .select(+ 'id, title, description, type, impact, opportunity_score, status, prompt_id, created_at, updated_at, source_data, brief, prompts(text), brands!inner(organization_id)',+ )+ .eq('id', opportunityId)+ .eq('brands.organization_id', auth.organizationId)+ .maybeSingle();++ if (error) throw new Error(error.message);+ if (!data) return null;++ const r = data as unknown as {+ id: string;+ title: string;+ description: string | null;+ type: string;+ impact: string;+ opportunity_score: number | null;+ status: string;+ prompt_id: string | null;+ created_at: string | null;+ updated_at: string | null;+ source_data: any | null;+ brief: any | null;+ prompts: Array<{ text: string }> | { text: string } | null;+ };++ const prompt = Array.isArray(r.prompts) ? r.prompts[0] ?? null : r.prompts;++ return {+ id: r.id,+ title: r.title,+ description: r.description,+ type: r.type,+ impact: r.impact,+ opportunity_score: Number(r.opportunity_score ?? 0),+ status: r.status,+ prompt_id: r.prompt_id,+ prompt_text: prompt?.text ?? null,+ source_data: r.source_data ?? null,+ brief: r.brief ?? null,+ created_at: r.created_at ?? '',+ updated_at: r.updated_at ?? '',+ };+}diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex 5f1246be9..535d2b4fd 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -3,8 +3,10 @@ import { z } from 'zod';import type { McpAuthContext } from '@/lib/mcp-auth';import {+ getContentOpportunityFor,getVisibilitySummaryFor,listBrandsFor,+ listContentOpportunitiesFor,listPromptsFor,listTopicsFor,} from './data';@@ -176,5 +178,88 @@ export function createMcpServer(auth: McpAuthContext): McpServer {},);+ server.registerTool(+ 'list_content_opportunities',+ {+ description:+ 'List content opportunities / gaps for a brand, showing which prompts represent the highest-impact areas where the brand is currently losing visibility. Sorts by opportunity score descending by default. Use this to audit open gaps, see what content needs to be written, or list open strategy priorities.',+ inputSchema: {+ brand_id: z+ .string()+ .uuid()+ .describe('Brand UUID, from list_brands.'),+ status: z+ .enum(['new', 'sent', 'in_progress', 'done', 'dismissed'])+ .optional()+ .describe('Filter by progress status of the opportunity.'),+ impact: z+ .enum(['high', 'medium', 'low'])+ .optional()+ .describe('Filter by estimated AEO visibility impact level.'),+ type: z+ .enum(['owned', 'earned'])+ .optional()+ .describe(+ 'Filter by channel type: owned (e.g. self-published blogs/pages) vs earned (e.g. PR/affiliate sites).',+ ),+ limit: z+ .number()+ .int()+ .min(1)+ .max(200)+ .optional()+ .describe('Row cap limit (default 50, max 200).'),+ },+ },+ async (args) => {+ const opportunities = await listContentOpportunitiesFor(auth, {+ brandId: args.brand_id,+ status: args.status,+ impact: args.impact,+ type: args.type,+ limit: args.limit,+ });+ if (opportunities === null) {+ return {+ content: [{ type: 'text', text: 'Brand not found' }],+ isError: true,+ };+ }+ return {+ content: [+ { type: 'text', text: JSON.stringify(opportunities, null, 2) },+ ],+ };+ },+ );++ server.registerTool(+ 'get_content_opportunity',+ {+ description:+ 'Get full details of a specific content opportunity, including raw AI visibility gap metrics, intent, competitor references, and the generated content brief if one already exists. Use this when the user picks a specific opportunity from the list and wants to inspect it further or start writing.',+ inputSchema: {+ opportunity_id: z+ .string()+ .uuid()+ .describe('Content opportunity UUID, from list_content_opportunities.'),+ },+ },+ async (args) => {+ const opportunity = await getContentOpportunityFor(auth, args.opportunity_id);+ if (!opportunity) {+ return {+ content: [{ type: 'text', text: 'Content opportunity not found' }],+ isError: true,+ };+ }+ return {+ content: [+ { type: 'text', text: JSON.stringify(opportunity, null, 2) },+ ],+ };+ },+ );+return server;}