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 generate_content_brief tool that triggers the brief endpoint (#109)
Gökhan Geyik006a8a476539
diff --git a/server/src/routes/content.js b/server/src/routes/content.jsindex f73f643f8..9a52a25cd 100644--- a/server/src/routes/content.js+++ b/server/src/routes/content.js@@ -562,69 +562,82 @@ Rules:- Target word count should be appropriate for the content type (e.g. blog post: 1500-3000, guide: 3000-5000).`;/**- * POST /api/content/:id/brief- * Generate an AI-powered content brief for an opportunity.+ * Generate (or fetch) an AI brief for a content opportunity.+ *+ * Shared core for both the user-facing dashboard route below and the+ * `/api/internal/content/:id/brief` MCP route in server.js. Keeping one+ * implementation here means MCP and dashboard can't drift in cost or+ * output shape.+ *+ * Behavior:+ * - opportunity not found → throws Error with `.status = 404`+ * - opportunity has a brief AND `force` is false → returns the cached+ * brief with `regenerated: false` (no LLM call)+ * - otherwise runs the LLM, writes the result back, returns+ * `{ brief, generated_at, regenerated: true }`*/-router.post('/:id/brief', async (req, res) => {- try {- const { id } = req.params;- const { model } = req.body;-- const { data: opportunity, error: oppErr } = await supabaseAdmin- .from('content_opportunities')- .select('*')- .eq('id', id)- .single();-- if (oppErr || !opportunity) {- return res.status(404).json({ error: 'Opportunity not found' });- }+export async function generateBriefForOpportunity(opportunityId, { force = false, model } = {}) {+ const { data: opportunity, error: oppErr } = await supabaseAdmin+ .from('content_opportunities')+ .select('*')+ .eq('id', opportunityId)+ .single();++ if (oppErr || !opportunity) {+ const err = new Error('Opportunity not found');+ err.status = 404;+ throw err;+ }- if (opportunity.brief) {- return res.json({ brief: opportunity.brief });- }+ if (opportunity.brief && !force) {+ return {+ brief: opportunity.brief,+ generated_at: opportunity.updated_at,+ regenerated: false,+ };+ }- const { data: brand } = await supabaseAdmin- .from('brands')- .select('name, industry, description')- .eq('id', opportunity.brand_id)+ const { data: brand } = await supabaseAdmin+ .from('brands')+ .select('name, industry, description')+ .eq('id', opportunity.brand_id)+ .single();++ const { data: domains } = await supabaseAdmin+ .from('brand_domains')+ .select('domain')+ .eq('brand_id', opportunity.brand_id);++ let promptText = opportunity.source_data?.promptText || '';+ let latestResults = [];++ if (opportunity.prompt_id) {+ const { data: prompt } = await supabaseAdmin+ .from('prompts')+ .select('text, category')+ .eq('id', opportunity.prompt_id).single();- const { data: domains } = await supabaseAdmin- .from('brand_domains')- .select('domain')- .eq('brand_id', opportunity.brand_id);-- let promptText = opportunity.source_data?.promptText || '';- let latestResults = [];-- if (opportunity.prompt_id) {- const { data: prompt } = await supabaseAdmin- .from('prompts')- .select('text, category')- .eq('id', opportunity.prompt_id)- .single();+ if (prompt) promptText = prompt.text;- if (prompt) promptText = prompt.text;+ const { data: results } = await supabaseAdmin+ .from('prompt_results')+ .select('platform, visibility_score, mention_count, citation_count, sentiment, response, competitor_mentions')+ .eq('prompt_id', opportunity.prompt_id)+ .order('created_at', { ascending: false })+ .limit(10);- const { data: results } = await supabaseAdmin- .from('prompt_results')- .select('platform, visibility_score, mention_count, citation_count, sentiment, response, competitor_mentions')- .eq('prompt_id', opportunity.prompt_id)- .order('created_at', { ascending: false })- .limit(10);-- latestResults = results || [];- }+ latestResults = results || [];+ }- const { data: competitors } = await supabaseAdmin- .from('competitors')- .select('name, domain')- .eq('brand_id', opportunity.brand_id);+ const { data: competitors } = await supabaseAdmin+ .from('competitors')+ .select('name, domain')+ .eq('brand_id', opportunity.brand_id);- const sourceData = opportunity.source_data || {};+ const sourceData = opportunity.source_data || {};- const userPrompt = `Brand: ${brand?.name || 'Unknown'}+ const userPrompt = `Brand: ${brand?.name || 'Unknown'}Industry: ${brand?.industry || 'Not specified'}Description: ${brand?.description || 'N/A'}Domain: ${(domains || []).map((d) => d.domain).join(', ') || 'N/A'}@@ -650,22 +663,43 @@ ${latestResults.map((r) => `- ${r.platform}: visibility ${r.visibility_score}%,Generate a detailed content brief for this opportunity.`;- const aiModel = resolveModel(model);+ const aiModel = resolveModel(model);- const { object: brief } = await generateObject({- model: aiModel,- schema: briefSchema,- system: BRIEF_SYSTEM_PROMPT,- prompt: userPrompt,- });+ const { object: brief } = await generateObject({+ model: aiModel,+ schema: briefSchema,+ system: BRIEF_SYSTEM_PROMPT,+ prompt: userPrompt,+ });- await supabaseAdmin- .from('content_opportunities')- .update({ brief, updated_at: new Date().toISOString() })- .eq('id', id);+ const generatedAt = new Date().toISOString();++ await supabaseAdmin+ .from('content_opportunities')+ .update({ brief, updated_at: generatedAt })+ .eq('id', opportunityId);++ return { brief, generated_at: generatedAt, regenerated: true };+}- return res.json({ brief });+/**+ * POST /api/content/:id/brief+ * Generate an AI-powered content brief for an opportunity.+ *+ * Dashboard-facing route. Preserves the existing cache-on-existing-brief+ * behavior — to force a re-generate, the MCP route in server.js calls+ * `generateBriefForOpportunity` with `{ force: true }` directly.+ */+router.post('/:id/brief', async (req, res) => {+ try {+ const { id } = req.params;+ const { model } = req.body;+ const result = await generateBriefForOpportunity(id, { model });+ return res.json({ brief: result.brief });} catch (error) {+ if (error.status === 404) {+ return res.status(404).json({ error: error.message });+ }console.error('[content] Brief generation error:', error);return res.status(500).json({error: 'Failed to generate brief',diff --git a/server/src/server.js b/server/src/server.jsindex 2e63922a1..b44e4536d 100644--- a/server/src/server.js+++ b/server/src/server.js@@ -15,6 +15,7 @@ import { createJob, cleanupStaleJobs, cleanupOldJobs } from './lib/job-manager.jimport { runTrackingJob } from './lib/job-runner.js';import { parseScraperResponse } from './lib/cloro-scraper.js';import { handleScraperResult } from './lib/cloro-result-handler.js';+import { generateBriefForOpportunity } from './routes/content.js';import supabaseAdmin from './config/supabase.js';import {getPlan,@@ -166,6 +167,41 @@ app.post('/api/internal/daily-tracking', async (req, res) => {}});+// --- Internal content-brief endpoint (CRON_SECRET auth, called by web MCP layer) ---+// The web layer's MCP route does the org-ownership check *before* hitting+// this endpoint — it can't reach here unless the authenticated `ans_` API+// key belongs to the same org as the opportunity. So this endpoint just+// trusts the secret and runs the LLM. Always passes force=true to bypass+// the cached-brief early-return (MCP callers want a fresh brief; for+// cached reads they should use get_content_opportunity instead).+app.post('/api/internal/content/:id/brief', async (req, res) => {+ const secret = req.headers.authorization?.replace('Bearer ', '');+ if (!process.env.CRON_SECRET || secret !== process.env.CRON_SECRET) {+ return res.status(401).json({ success: false, message: 'Unauthorized' });+ }++ try {+ const { id } = req.params;+ const { force, model } = req.body || {};+ const result = await generateBriefForOpportunity(id, {+ force: Boolean(force),+ model,+ });+ return res.json({+ success: true,+ brief: result.brief,+ generated_at: result.generated_at,+ regenerated: result.regenerated,+ });+ } catch (err) {+ if (err.status === 404) {+ return res.status(404).json({ success: false, message: err.message });+ }+ console.error('[internal] content brief error:', err.message);+ return res.status(500).json({ success: false, message: err.message });+ }+});+// --- Internal trigger-tracking endpoint (CRON_SECRET auth, called by Stripe success route) ---app.post('/api/internal/trigger-tracking', async (req, res) => {const secret = req.headers.authorization?.replace('Bearer ', '');diff --git a/web/src/app/api/mcp/content-opportunities/[id]/brief/route.ts b/web/src/app/api/mcp/content-opportunities/[id]/brief/route.tsnew file mode 100644index 000000000..1524aa66b--- /dev/null+++ b/web/src/app/api/mcp/content-opportunities/[id]/brief/route.ts@@ -0,0 +1,32 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { generateBriefFor } from '@/lib/mcp/data';++/**+ * POST /api/mcp/content-opportunities/[id]/brief+ *+ * Parallel REST surface for the `generate_content_brief` MCP tool — same+ * data-layer function, same ownership guarantee. Always re-generates;+ * cached reads belong on GET /api/mcp/content-opportunities/[id].+ */+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 opportunityId = resolvedParams.id;+ if (!opportunityId) {+ return NextResponse.json({ error: 'id is required' }, { status: 400 });+ }++ try {+ const result = await generateBriefFor(auth, opportunityId);+ if (!result) {+ return NextResponse.json({ error: 'Content opportunity 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 af7b5656f..71cd1cc6c 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -428,6 +428,80 @@ export interface ContentOpportunityDetail {updated_at: string;}+export interface GeneratedBrief {+ id: string;+ brief: Record<string, unknown>;+ generated_at: string;+ regenerated: boolean;+}++/**+ * Generate (or re-generate) the AI content brief for an opportunity.+ *+ * Org-ownership is verified *first* via supabaseAdmin — a wrong-org or+ * missing id returns `null` (→ 404 upstream) and never reaches the+ * aeo-server, so the LLM is never invoked for a tenant that doesn't own+ * the opportunity. Only after ownership passes do we call the internal+ * brief endpoint at `${NEXT_PUBLIC_API_URL}/api/internal/content/:id/brief`+ * with `Authorization: Bearer ${CRON_SECRET}` — same pattern as the+ * `/api/cron/daily-tracking` route. The `ans_` API key never leaves the+ * web layer.+ *+ * Always passes `force: true` because MCP callers explicitly want a fresh+ * brief; cached reads belong on `getContentOpportunityFor`.+ */+export async function generateBriefFor(+ auth: McpAuthContext,+ opportunityId: string,+): Promise<GeneratedBrief | null> {+ if (!auth.organizationId) return null;++ // Ownership check first — wrong-org or missing id returns null with no+ // outbound call, so no LLM cost or data leak for an attacker probing ids.+ const { data: ownership } = await supabaseAdmin+ .from('content_opportunities')+ .select('id, brands!inner(organization_id)')+ .eq('id', opportunityId)+ .eq('brands.organization_id', auth.organizationId)+ .maybeSingle();+ if (!ownership) return null;++ const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:80';+ const cronSecret = process.env.CRON_SECRET;+ if (!cronSecret) {+ throw new Error('CRON_SECRET must be configured for MCP brief generation');+ }++ const res = await fetch(`${apiUrl}/api/internal/content/${opportunityId}/brief`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${cronSecret}`,+ },+ body: JSON.stringify({ force: true }),+ });++ if (res.status === 404) return null;++ if (!res.ok) {+ const text = await res.text().catch(() => '');+ throw new Error(`Internal brief endpoint returned ${res.status}: ${text.slice(0, 200)}`);+ }++ const body = (await res.json()) as {+ brief: Record<string, unknown>;+ generated_at: string;+ regenerated?: boolean;+ };++ return {+ id: opportunityId,+ brief: body.brief,+ generated_at: body.generated_at,+ regenerated: Boolean(body.regenerated),+ };+}+export async function getContentOpportunityFor(auth: McpAuthContext,opportunityId: string,diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex 1f8a5c8ab..5f41c82b5 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -3,6 +3,7 @@ import { z } from 'zod';import type { McpAuthContext } from '@/lib/mcp-auth';import {+ generateBriefFor,getContentOpportunityFor,getVisibilitySummaryFor,listBrandsFor,@@ -223,5 +224,31 @@ export function createMcpServer(auth: McpAuthContext): McpServer {},);+ server.registerTool(+ 'generate_content_brief',+ {+ description:+ 'Generate a fresh AI-powered content brief for a specific content opportunity. WARNING: this triggers an LLM call (cost + latency) and ALWAYS re-generates, overwriting any existing brief on the opportunity. Use only after list_content_opportunities + get_content_opportunity and only when the user has explicitly asked to generate or refresh a brief for a specific opportunity — never as part of exploratory queries. To read an existing brief without an LLM call, use get_content_opportunity instead.',+ inputSchema: {+ opportunity_id: z+ .string()+ .uuid()+ .describe('Content opportunity UUID, from list_content_opportunities.'),+ },+ },+ async (args) => {+ const result = await generateBriefFor(auth, args.opportunity_id);+ if (!result) {+ return {+ content: [{ type: 'text', text: 'Content opportunity not found' }],+ isError: true,+ };+ }+ return {+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],+ };+ },+ );+return server;}