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): run a Site Audit via MCP (run_site_audit + get_site_audit) (#305)
Gökhan Geyik7b310888c9a9
diff --git a/server/src/routes/audits.js b/server/src/routes/audits.jsindex fe2c6109f..cc94270e1 100644--- a/server/src/routes/audits.js+++ b/server/src/routes/audits.js@@ -149,6 +149,52 @@ async function runAuditJob(auditId, brandId, url, orgId) {}}+/**+ * Enforce the monthly quota, create the `running` row, and kick off the+ * detached audit job. Shared by the dashboard POST handler and the internal+ * MCP endpoint. Returns the assembled (still-running) audit. Throws+ * PlanLimitError when the quota is exhausted — nothing is created in that case.+ */+export async function createAndRunAudit(brandId, url, orgId) {+ // Enforce the monthly Site Audit quota (Starter 100 / Growth 500;+ // Enterprise & self-hosted unlimited). Throws PlanLimitError when exhausted.+ await enforceSiteAuditQuota(orgId);++ const { data: created, error: insErr } = await supabaseAdmin+ .from('site_audits')+ .insert({ brand_id: brandId, url, status: 'running', rubric_version: RUBRIC_VERSION })+ .select('*')+ .single();+ if (insErr) throw insErr;++ // Fire-and-forget — the work continues after the response is sent.+ runAuditJob(created.id, brandId, url, orgId).catch((err) =>+ console.error('[audit] background job crashed:', err.message),+ );++ return assembleAudit(created, []);+}++/**+ * Internal/MCP entry point: start an audit addressed by brand id + url.+ * Org-ownership is verified upstream in the web MCP layer; here we resolve the+ * brand's org ourselves so the quota is charged authoritatively server-side.+ * Throws a 404-status error when the brand doesn't exist.+ */+export async function startSiteAuditForBrand(brandId, url) {+ const { data: brand } = await supabaseAdmin+ .from('brands')+ .select('organization_id')+ .eq('id', brandId)+ .maybeSingle();+ if (!brand) {+ const err = new Error('Brand not found');+ err.status = 404;+ throw err;+ }+ return createAndRunAudit(brandId, url, brand.organization_id);+}+// POST /api/audits — start an audit. Returns immediately with a `running`// row; the client polls GET /:id until it flips to completed/failed.router.post('/', requireFeature('content_optimization'), async (req, res) => {@@ -161,24 +207,8 @@ router.post('/', requireFeature('content_optimization'), async (req, res) => {try {const { orgId } = await assertBrandAccess(brandId, userId);-- // Enforce the monthly Site Audit quota (Starter 100 / Growth 500;- // Enterprise & self-hosted unlimited). Throws PlanLimitError when exhausted.- await enforceSiteAuditQuota(orgId);-- const { data: created, error: insErr } = await supabaseAdmin- .from('site_audits')- .insert({ brand_id: brandId, url, status: 'running', rubric_version: RUBRIC_VERSION })- .select('*')- .single();- if (insErr) throw insErr;-- // Fire-and-forget — the work continues after the response is sent.- runAuditJob(created.id, brandId, url, orgId).catch((err) =>- console.error('[audit] background job crashed:', err.message),- );-- return res.status(202).json({ success: true, audit: assembleAudit(created, []) });+ const audit = await createAndRunAudit(brandId, url, orgId);+ return res.status(202).json({ success: true, audit });} catch (err) {if (err instanceof PlanLimitError) {return resdiff --git a/server/src/server.js b/server/src/server.jsindex 9ab0ff76c..e62850458 100644--- a/server/src/server.js+++ b/server/src/server.js@@ -24,6 +24,7 @@ import { parseScraperResponse } from './lib/cloro-scraper.js';import { handleScraperResult } from './lib/cloro-result-handler.js';import { verifyCloroWebhook } from './lib/cloro-webhook-verify.js';import { generateBriefForOpportunity } from './routes/content.js';+import { startSiteAuditForBrand } from './routes/audits.js';import supabaseAdmin from './config/supabase.js';import { getPlan, hasFeature, isCloud, isSubscriptionActive } from './config/plans.js';@@ -222,6 +223,41 @@ app.post('/api/internal/content/:id/brief', async (req, res) => {}});+// --- Internal site-audit endpoint (CRON_SECRET auth, called by web MCP layer) ---+// The web MCP layer verifies the caller's `ans_` API key org owns `brandId`+// before reaching here, so this endpoint just trusts the secret, resolves the+// brand's org, enforces the monthly Site Audit quota, and starts the detached+// audit job — returning the new `running` audit (the MCP caller then polls+// get_site_audit for the result).+app.post('/api/internal/site-audits', 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 { brandId, url } = req.body || {};+ if (!brandId || !url) {+ return res.status(400).json({ success: false, message: 'brandId and url are required' });+ }+ const audit = await startSiteAuditForBrand(brandId, url);+ return res.status(202).json({ success: true, audit });+ } catch (err) {+ if (err.status === 404) {+ return res.status(404).json({ success: false, message: err.message });+ }+ // PlanLimitError (audit quota exhausted / inactive subscription) carries a+ // statusCode — surface it so the MCP layer can relay a clear message.+ if (err.statusCode) {+ return res+ .status(err.statusCode)+ .json({ success: false, error: 'quota_exceeded', message: err.message });+ }+ console.error('[internal] site audit 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/site-audits/[id]/route.ts b/web/src/app/api/mcp/site-audits/[id]/route.tsnew file mode 100644index 000000000..752bd060b--- /dev/null+++ b/web/src/app/api/mcp/site-audits/[id]/route.ts@@ -0,0 +1,30 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { getSiteAuditFor } from '@/lib/mcp/data';++/**+ * GET /api/mcp/site-audits/[id]+ *+ * Parallel REST surface for the `get_site_audit` MCP tool — same data-layer+ * function, same ownership guarantee. Pure read; no quota consumed.+ */+export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {+ const auth = await authenticateMcpRequest(req);+ if (auth instanceof NextResponse) return auth;++ const { id } = await params;+ if (!id) {+ return NextResponse.json({ error: 'id is required' }, { status: 400 });+ }++ try {+ const audit = await getSiteAuditFor(auth, id);+ if (!audit) {+ return NextResponse.json({ error: 'Audit not found' }, { status: 404 });+ }+ return NextResponse.json(audit);+ } 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/site-audits/route.ts b/web/src/app/api/mcp/site-audits/route.tsnew file mode 100644index 000000000..dd9b9bbce--- /dev/null+++ b/web/src/app/api/mcp/site-audits/route.ts@@ -0,0 +1,39 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { runSiteAuditFor } from '@/lib/mcp/data';++/**+ * POST /api/mcp/site-audits { brand_id, url }+ *+ * Parallel REST surface for the `run_site_audit` MCP tool — same data-layer+ * function, same ownership guarantee. Charges the monthly Site Audit quota and+ * returns the new audit id + "running" status (poll GET /api/mcp/site-audits/[id]).+ */+export async function POST(req: Request) {+ const auth = await authenticateMcpRequest(req);+ if (auth instanceof NextResponse) return auth;++ let body: { brand_id?: string; url?: string };+ try {+ body = await req.json();+ } catch {+ return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });+ }++ const brandId = body.brand_id;+ const url = body.url;+ if (!brandId || !url) {+ return NextResponse.json({ error: 'brand_id and url are required' }, { status: 400 });+ }++ try {+ const result = await runSiteAuditFor(auth, brandId, url);+ if (!result) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });+ }+ return NextResponse.json(result, { status: 202 });+ } 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 195957695..0f4ab9cda 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -518,6 +518,156 @@ export async function generateBriefFor(};}+export interface SiteAuditRun {+ id: string;+ brandId: string;+ url: string;+ status: string;+}++/**+ * Start a Site Audit for a brand + URL via MCP.+ *+ * Org-ownership is verified *first* via supabaseAdmin — a wrong-org or missing+ * brand returns `null` (→ 404 upstream) and never reaches the aeo-server, so+ * no audit is created and no quota is charged for a tenant that doesn't own the+ * brand. Only after ownership passes do we call the internal audit endpoint at+ * `${API_BASE_URL}/api/internal/site-audits` with `Authorization: Bearer+ * ${CRON_SECRET}` — same pattern as `generateBriefFor`. The `ans_` API key+ * never leaves the web layer. The audit runs async (~30s); the caller polls+ * `getSiteAuditFor` with the returned id.+ */+export async function runSiteAuditFor(+ auth: McpAuthContext,+ brandId: string,+ url: string,+): Promise<SiteAuditRun | null> {+ if (!auth.organizationId) return null;++ // Ownership check first — a wrong-org or missing brand returns null with no+ // outbound call, so probing brand ids costs nothing and starts no audit.+ const { data: brand } = await supabaseAdmin+ .from('brands')+ .select('id')+ .eq('id', brandId)+ .eq('organization_id', auth.organizationId)+ .maybeSingle();+ if (!brand) return null;++ const cronSecret = process.env.CRON_SECRET;+ if (!cronSecret) {+ throw new Error('CRON_SECRET must be configured for MCP site audits');+ }++ const res = await fetch(`${API_BASE_URL}/api/internal/site-audits`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${cronSecret}`,+ },+ body: JSON.stringify({ brandId, url }),+ });++ if (res.status === 404) return null;++ if (!res.ok) {+ // Surface the server's message (e.g. the monthly-quota / inactive-subscription+ // text) so the agent can relay it instead of a generic failure.+ const body = (await res.json().catch(() => null)) as { message?: string } | null;+ throw new Error(body?.message ?? `Internal site-audit endpoint returned ${res.status}`);+ }++ const body = (await res.json()) as {+ audit: { id: string; brandId: string; url: string; status: string };+ };+ return {+ id: body.audit.id,+ brandId: body.audit.brandId,+ url: body.audit.url,+ status: body.audit.status,+ };+}++export interface SiteAuditSignal {+ key: string;+ category: string | null;+ status: string;+ score: number | null;+ evidence: Record<string, unknown>;+}++export interface SiteAuditResult {+ id: string;+ brandId: string;+ url: string;+ finalUrl: string | null;+ status: string;+ totalScore: number | null;+ categoryScores: Record<string, unknown>;+ signalsEvaluated: number | null;+ signalsTotal: number | null;+ recommendations: unknown[];+ signals: SiteAuditSignal[];+ error: string | null;+ createdAt: string;+ completedAt: string | null;+}++/**+ * Read a Site Audit by id for the caller's org. Pure DB read (no LLM, no+ * quota) — the org-ownership filter is applied in the query via the+ * `brands!inner(organization_id)` join, so a foreign or unknown id returns+ * `null`. Returns the status + scores + signals + AI recommendations.+ */+export async function getSiteAuditFor(+ auth: McpAuthContext,+ auditId: string,+): Promise<SiteAuditResult | null> {+ if (!auth.organizationId) return null;++ const { data: audit } = await supabaseAdmin+ .from('site_audits')+ .select('*, brands!inner(organization_id)')+ .eq('id', auditId)+ .eq('brands.organization_id', auth.organizationId)+ .maybeSingle();+ if (!audit) return null;++ const { data: signalRows } = await supabaseAdmin+ .from('audit_signal_results')+ .select('signal_key, category, status, score, evidence')+ .eq('audit_id', auditId);++ const signals: SiteAuditSignal[] = ((signalRows ?? []) as Array<Record<string, unknown>>).map(+ (r) => ({+ key: r.signal_key as string,+ category: (r.category as string | null) ?? null,+ status: r.status as string,+ score: r.score === null || r.score === undefined ? null : Number(r.score),+ evidence: (r.evidence as Record<string, unknown>) ?? {},+ }),+ );++ const a = audit as Record<string, unknown>;+ const num = (v: unknown) => (v === null || v === undefined ? null : Number(v));+ return {+ id: a.id as string,+ brandId: a.brand_id as string,+ url: a.url as string,+ finalUrl: (a.final_url as string | null) ?? null,+ status: a.status as string,+ totalScore: num(a.total_score),+ categoryScores: (a.category_scores as Record<string, unknown>) ?? {},+ signalsEvaluated: a.signals_evaluated == null ? null : Number(a.signals_evaluated),+ signalsTotal: a.signals_total == null ? null : Number(a.signals_total),+ recommendations: (a.recommendations as unknown[]) ?? [],+ signals,+ error: (a.error as string | null) ?? null,+ createdAt: a.created_at as string,+ completedAt: (a.completed_at as string | null) ?? null,+ };+}+export async function getContentOpportunityFor(auth: McpAuthContext,opportunityId: string,diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex 93def22b1..99435a58f 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -20,6 +20,8 @@ import {listShoppingCards,getProductVisibility,getPromptPerformanceFor,+ runSiteAuditFor,+ getSiteAuditFor,} from './data';/**@@ -263,6 +265,53 @@ export function createMcpServer(auth: McpAuthContext): McpServer {},);+ server.registerTool(+ 'run_site_audit',+ {+ description:+ 'Run a Site Audit (AEO/GEO page score + AI fix recommendations) for a page URL under a brand. WARNING: this consumes one of the org\'s monthly Site Audit credits (the same pool as the dashboard) and runs asynchronously (~30s). It returns immediately with the new audit id and status "running" — then poll get_site_audit with that id until status is "completed" (or "failed") to read the result. Only fire on explicit user intent to audit a specific URL, never as part of exploratory queries.',+ inputSchema: {+ brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),+ url: z.string().url().describe('Full URL of the page to audit, including https://.'),+ },+ },+ async (args) => {+ const result = await runSiteAuditFor(auth, args.brand_id, args.url);+ if (!result) {+ return {+ content: [{ type: 'text', text: 'Brand not found' }],+ isError: true,+ };+ }+ return {+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],+ };+ },+ );++ server.registerTool(+ 'get_site_audit',+ {+ description:+ 'Fetch a Site Audit by id — its status, total score, per-category scores, evaluated signals, and AI fix recommendations. Use after run_site_audit to poll for the result: while status is "running" the scores are not yet populated; once it is "completed" (or "failed") the full result is available. This is a read — no credit is consumed.',+ inputSchema: {+ audit_id: relaxedUuid.describe('Site audit UUID, from run_site_audit.'),+ },+ },+ async (args) => {+ const audit = await getSiteAuditFor(auth, args.audit_id);+ if (!audit) {+ return {+ content: [{ type: 'text', text: 'Audit not found' }],+ isError: true,+ };+ }+ return {+ content: [{ type: 'text', text: JSON.stringify(audit, null, 2) }],+ };+ },+ );+server.registerTool('update_opportunity_status',{