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 topic suggestions via list/accept/dismiss tools (#513)
Patel Dhritc1e64fe0ec11
diff --git a/web/src/app/api/mcp/topic-suggestions/[id]/accept/route.ts b/web/src/app/api/mcp/topic-suggestions/[id]/accept/route.tsnew file mode 100644index 000000000..9777a80c6--- /dev/null+++ b/web/src/app/api/mcp/topic-suggestions/[id]/accept/route.ts@@ -0,0 +1,35 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { acceptTopicSuggestionFor } from '@/lib/mcp/data';++/**+ * POST /api/mcp/topic-suggestions/[id]/accept+ *+ * Parallel REST surface for the `accept_topic_suggestion` MCP tool — same+ * data-layer function, same ownership guarantee, same status = 'new' guard+ * that keeps a repeated accept from creating a second topic.+ */+export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {+ const auth = await authenticateMcpRequest(req);+ if (auth instanceof NextResponse) return auth;++ const resolvedParams = await params;+ const suggestionId = resolvedParams.id;+ if (!suggestionId) {+ return NextResponse.json({ error: 'id is required' }, { status: 400 });+ }++ try {+ const result = await acceptTopicSuggestionFor(auth, suggestionId);+ if (!result) {+ return NextResponse.json(+ { error: 'Suggestion not found, not pending, or already processed' },+ { 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/app/api/mcp/topic-suggestions/[id]/dismiss/route.ts b/web/src/app/api/mcp/topic-suggestions/[id]/dismiss/route.tsnew file mode 100644index 000000000..5c5d52045--- /dev/null+++ b/web/src/app/api/mcp/topic-suggestions/[id]/dismiss/route.ts@@ -0,0 +1,34 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { dismissTopicSuggestionFor } from '@/lib/mcp/data';++/**+ * POST /api/mcp/topic-suggestions/[id]/dismiss+ *+ * Parallel REST surface for the `dismiss_topic_suggestion` MCP tool — same+ * data-layer function, same ownership guarantee.+ */+export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {+ const auth = await authenticateMcpRequest(req);+ if (auth instanceof NextResponse) return auth;++ const resolvedParams = await params;+ const suggestionId = resolvedParams.id;+ if (!suggestionId) {+ return NextResponse.json({ error: 'id is required' }, { status: 400 });+ }++ try {+ const result = await dismissTopicSuggestionFor(auth, suggestionId);+ if (!result) {+ return NextResponse.json(+ { error: 'Suggestion not found, not pending, or already processed' },+ { 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/app/api/mcp/topic-suggestions/route.ts b/web/src/app/api/mcp/topic-suggestions/route.tsnew file mode 100644index 000000000..4734ba806--- /dev/null+++ b/web/src/app/api/mcp/topic-suggestions/route.ts@@ -0,0 +1,31 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { listTopicSuggestionsFor } from '@/lib/mcp/data';++/**+ * GET /api/mcp/topic-suggestions?brand_id=...+ *+ * Parallel REST surface for the `list_topic_suggestions` MCP tool — same+ * data-layer function, same ownership guarantee.+ */+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 suggestions = await listTopicSuggestionsFor(auth, brandId);+ if (suggestions === null) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });+ }+ return NextResponse.json({ suggestions });+ } 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 311918cd5..567f5b7f5 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -308,6 +308,134 @@ export async function listTopicsFor(}));}+// ── Topic suggestions (#498) ─────────────────────────────────────────────────+// Read/act on the AI-generated suggestions persisted by #497 (topic_suggestions+// table). Generation itself stays plan-gated behind the web UI's refresh+// button — these tools only list, accept, or dismiss what already exists.++export interface TopicSuggestionRow {+ id: string;+ name: string;+ reason: string | null;+ generated_at: string;+}++/**+ * List pending (status = 'new') topic suggestions for a brand. Ownership is+ * checked the same way as listTopicsFor — a wrong-org or missing brand id+ * returns null before any suggestion row is read.+ */+export async function listTopicSuggestionsFor(+ auth: McpAuthContext,+ brandId: string,+): Promise<TopicSuggestionRow[] | null> {+ if (!auth.organizationId) return null;++ const { data: brand } = await supabaseAdmin+ .from('brands')+ .select('id')+ .eq('id', brandId)+ .eq('organization_id', auth.organizationId)+ .maybeSingle();+ if (!brand) return null;++ const { data, error } = await supabaseAdmin+ .from('topic_suggestions')+ .select('id, name, reason, generated_at')+ .eq('brand_id', brandId)+ .eq('status', 'new')+ .order('generated_at', { ascending: false });+ if (error) throw new Error(error.message);++ return (data ?? []) as TopicSuggestionRow[];+}++export interface DismissedTopicSuggestion {+ id: string;+ status: 'dismissed';+}++/**+ * Dismiss a pending suggestion so it never reappears in future refreshes.+ * Scoped to status = 'new' so dismissing an already-decided suggestion (added+ * or already dismissed) is a no-op that returns null rather than silently+ * "succeeding" twice.+ */+export async function dismissTopicSuggestionFor(+ auth: McpAuthContext,+ suggestionId: string,+): Promise<DismissedTopicSuggestion | null> {+ if (!auth.organizationId) return null;++ const { data: ownership } = await supabaseAdmin+ .from('topic_suggestions')+ .select('id, status, brands!inner(organization_id)')+ .eq('id', suggestionId)+ .eq('brands.organization_id', auth.organizationId)+ .eq('status', 'new')+ .maybeSingle();+ if (!ownership) return null;++ const { data, error } = await supabaseAdmin+ .from('topic_suggestions')+ .update({ status: 'dismissed', updated_at: new Date().toISOString() })+ .eq('id', suggestionId)+ .select('id, status')+ .single();+ if (error) throw new Error(error.message);++ return { id: data.id, status: 'dismissed' };+}++export interface AcceptedTopicSuggestion {+ suggestion_id: string;+ topic_id: string;+ topic_name: string;+}++/**+ * Accept a suggestion: create exactly ONE topic via a singular insert (never+ * a bulk replace of the brand's topic list — mirrors the web app's+ * createTopic action), then mark the suggestion added with a pointer to the+ * new topic. Scoped to status = 'new' up front, so accepting the same+ * suggestion twice fails the ownership lookup on the second call instead of+ * creating a second topic.+ */+export async function acceptTopicSuggestionFor(+ auth: McpAuthContext,+ suggestionId: string,+): Promise<AcceptedTopicSuggestion | null> {+ if (!auth.organizationId) return null;++ const { data: suggestion } = await supabaseAdmin+ .from('topic_suggestions')+ .select('id, brand_id, name, brands!inner(organization_id)')+ .eq('id', suggestionId)+ .eq('brands.organization_id', auth.organizationId)+ .eq('status', 'new')+ .maybeSingle();+ if (!suggestion) return null;++ const { data: topic, error: topicErr } = await supabaseAdmin+ .from('topics')+ .insert({ brand_id: suggestion.brand_id, name: suggestion.name.trim() })+ .select('id, name')+ .single();+ if (topicErr) throw new Error(topicErr.message);++ const { error: updateErr } = await supabaseAdmin+ .from('topic_suggestions')+ .update({+ status: 'added',+ added_topic_id: topic.id,+ updated_at: new Date().toISOString(),+ })+ .eq('id', suggestionId);+ if (updateErr) throw new Error(updateErr.message);++ return { suggestion_id: suggestionId, topic_id: topic.id, topic_name: topic.name };+}+// ── Prompts ───────────────────────────────────────────────────────────────────export interface PromptRow {diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex 5199dc850..2d25d3d59 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -4,6 +4,8 @@ import { z } from 'zod';import type { McpAuthContext } from '@/lib/mcp-auth';import {CONTENT_OPPORTUNITY_STATUSES,+ acceptTopicSuggestionFor,+ dismissTopicSuggestionFor,generateBriefFor,getCompetitorComparisonFor,getContentOpportunityFor,@@ -14,6 +16,7 @@ import {listContentOpportunitiesFor,listPromptsFor,listTopicsFor,+ listTopicSuggestionsFor,updateOpportunityStatusFor,getAiTrafficFor,getPromptVolumesFor,@@ -175,6 +178,79 @@ export function createMcpServer(auth: McpAuthContext): McpServer {},);+ server.registerTool(+ 'list_topic_suggestions',+ {+ description:+ 'List pending AI-generated topic suggestions for a brand (id, name, reason, and when they were generated). These are suggestions awaiting a decision — already accepted or dismissed suggestions never appear here. Generating new suggestions is not available via MCP; use accept_topic_suggestion or dismiss_topic_suggestion to act on what is already pending.',+ inputSchema: {+ brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),+ },+ },+ async (args) => {+ const suggestions = await listTopicSuggestionsFor(auth, args.brand_id);+ if (suggestions === null) {+ return {+ content: [{ type: 'text', text: 'Brand not found' }],+ isError: true,+ };+ }+ return {+ content: [{ type: 'text', text: JSON.stringify(suggestions, null, 2) }],+ };+ },+ );++ server.registerTool(+ 'accept_topic_suggestion',+ {+ description:+ 'Accept a pending topic suggestion: creates exactly one new topic from it and marks the suggestion as added. Only fire on explicit user intent for a specific suggestion (from list_topic_suggestions), never as part of an exploratory query. Accepting the same suggestion twice fails cleanly — it is not accepted or already decided — no duplicate topic is created.',+ inputSchema: {+ suggestion_id: relaxedUuid.describe('Topic suggestion UUID, from list_topic_suggestions.'),+ },+ },+ async (args) => {+ const result = await acceptTopicSuggestionFor(auth, args.suggestion_id);+ if (!result) {+ return {+ content: [+ { type: 'text', text: 'Suggestion not found, not pending, or already processed' },+ ],+ isError: true,+ };+ }+ return {+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],+ };+ },+ );++ server.registerTool(+ 'dismiss_topic_suggestion',+ {+ description:+ 'Dismiss a pending topic suggestion so it never reappears in future suggestion batches. Only fire on explicit user intent for a specific suggestion (from list_topic_suggestions), never as part of an exploratory query.',+ inputSchema: {+ suggestion_id: relaxedUuid.describe('Topic suggestion UUID, from list_topic_suggestions.'),+ },+ },+ async (args) => {+ const result = await dismissTopicSuggestionFor(auth, args.suggestion_id);+ if (!result) {+ return {+ content: [+ { type: 'text', text: 'Suggestion not found, not pending, or already processed' },+ ],+ isError: true,+ };+ }+ return {+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],+ };+ },+ );+server.registerTool('list_content_opportunities',{