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): list_site_audits + get_site_audit_quota read tools (#306)
Gökhan Geyik0ac973a7e172
diff --git a/server/src/server.js b/server/src/server.jsindex e62850458..68109ad6b 100644--- a/server/src/server.js+++ b/server/src/server.js@@ -25,6 +25,7 @@ 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 { getSiteAuditQuotaStatus } from './lib/plan-guard.js';import supabaseAdmin from './config/supabase.js';import { getPlan, hasFeature, isCloud, isSubscriptionActive } from './config/plans.js';@@ -258,6 +259,38 @@ app.post('/api/internal/site-audits', async (req, res) => {}});+// --- Internal site-audit quota endpoint (CRON_SECRET auth, called by web MCP layer) ---+// Read-only: returns the org's monthly Site Audit allowance via the same+// getSiteAuditQuotaStatus the dashboard uses, so the MCP `get_site_audit_quota`+// tool shares one source of truth for plan limits + usage counting. The web+// MCP layer passes its authenticated org id.+app.get('/api/internal/site-audit-quota', 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 {+ // Express gives an array when a query param is repeated; take the first so+ // a single string always reaches getSiteAuditQuotaStatus.+ const raw = req.query.orgId;+ const orgId = Array.isArray(raw) ? raw[0] : raw;+ if (!orgId) {+ return res.status(400).json({ success: false, message: 'orgId is required' });+ }+ const quota = await getSiteAuditQuotaStatus(orgId);+ return res.json({ success: true, quota });+ } catch (err) {+ if (err.statusCode) {+ return res+ .status(err.statusCode)+ .json({ success: false, error: 'quota_exceeded', message: err.message });+ }+ console.error('[internal] site audit quota 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/quota/route.ts b/web/src/app/api/mcp/site-audits/quota/route.tsnew file mode 100644index 000000000..c1dd9f708--- /dev/null+++ b/web/src/app/api/mcp/site-audits/quota/route.ts@@ -0,0 +1,30 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { getSiteAuditQuotaFor } from '@/lib/mcp/data';++/**+ * GET /api/mcp/site-audits/quota+ *+ * Parallel REST surface for the `get_site_audit_quota` MCP tool — the org's+ * monthly Site Audit allowance ({ used, limit, remaining }). Pure read; no+ * quota consumed. The static `quota` segment takes precedence over the+ * dynamic `[id]` route, so this is matched before site-audits/[id].+ */+export async function GET(req: Request) {+ const auth = await authenticateMcpRequest(req);+ if (auth instanceof NextResponse) return auth;++ try {+ const quota = await getSiteAuditQuotaFor(auth);+ if (!quota) {+ return NextResponse.json(+ { error: 'No organization found for this API key' },+ { status: 404 },+ );+ }+ return NextResponse.json(quota);+ } 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.tsindex dd9b9bbce..e8bc479dc 100644--- a/web/src/app/api/mcp/site-audits/route.ts+++ b/web/src/app/api/mcp/site-audits/route.ts@@ -1,6 +1,33 @@import { NextResponse } from 'next/server';import { authenticateMcpRequest } from '@/lib/mcp-auth';-import { runSiteAuditFor } from '@/lib/mcp/data';+import { runSiteAuditFor, listSiteAuditsFor } from '@/lib/mcp/data';++/**+ * GET /api/mcp/site-audits?brand_id=…+ *+ * Parallel REST surface for the `list_site_audits` MCP tool. Pure read; no+ * quota consumed.+ */+export async function GET(req: Request) {+ const auth = await authenticateMcpRequest(req);+ if (auth instanceof NextResponse) return auth;++ const brandId = new URL(req.url).searchParams.get('brand_id');+ if (!brandId) {+ return NextResponse.json({ error: 'brand_id is required' }, { status: 400 });+ }++ try {+ const audits = await listSiteAuditsFor(auth, brandId);+ if (!audits) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });+ }+ return NextResponse.json(audits);+ } catch (err) {+ const message = err instanceof Error ? err.message : 'Failed';+ return NextResponse.json({ error: message }, { status: 500 });+ }+}/*** POST /api/mcp/site-audits { brand_id, url }diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.tsindex 0f4ab9cda..912309243 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -525,6 +525,92 @@ export interface SiteAuditRun {status: string;}+export interface SiteAuditListRow {+ id: string;+ url: string;+ status: string;+ totalScore: number | null;+ signalsEvaluated: number | null;+ signalsTotal: number | null;+ createdAt: string;+}++/**+ * List a brand's recent Site Audits (newest first). Pure DB read, no quota —+ * ownership is verified via the brand belonging to the caller's org, so a+ * foreign or unknown brand returns `null`. Lets an agent find a past audit by+ * url/date instead of needing its id.+ */+export async function listSiteAuditsFor(+ auth: McpAuthContext,+ brandId: string,+): Promise<SiteAuditListRow[] | 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('site_audits')+ .select('id, url, status, total_score, signals_evaluated, signals_total, created_at')+ .eq('brand_id', brandId)+ .order('created_at', { ascending: false })+ .limit(50);+ if (error) throw new Error(error.message);++ return ((data ?? []) as Array<Record<string, unknown>>).map((r) => ({+ id: r.id as string,+ url: r.url as string,+ status: r.status as string,+ totalScore: r.total_score == null ? null : Number(r.total_score),+ signalsEvaluated: r.signals_evaluated == null ? null : Number(r.signals_evaluated),+ signalsTotal: r.signals_total == null ? null : Number(r.signals_total),+ createdAt: r.created_at as string,+ }));+}++export interface SiteAuditQuota {+ used: number;+ limit: number;+ remaining: number;+}++/**+ * The org's monthly Site Audit allowance ({ used, limit, remaining };+ * limit -1 = unlimited). Delegates to the server's `getSiteAuditQuotaStatus`+ * via the CRON_SECRET internal endpoint so plan-limit + usage-counting logic+ * stays single-sourced on the server. No quota is charged.+ */+export async function getSiteAuditQuotaFor(auth: McpAuthContext): Promise<SiteAuditQuota | null> {+ if (!auth.organizationId) return null;++ const cronSecret = process.env.CRON_SECRET;+ if (!cronSecret) {+ throw new Error('CRON_SECRET must be configured for MCP site audit quota');+ }++ const url = `${API_BASE_URL}/api/internal/site-audit-quota?orgId=${encodeURIComponent(+ auth.organizationId,+ )}`;+ const res = await fetch(url, {+ method: 'GET',+ headers: { Authorization: `Bearer ${cronSecret}` },+ });++ if (!res.ok) {+ const body = (await res.json().catch(() => null)) as { message?: string } | null;+ throw new Error(body?.message ?? `Internal site-audit-quota endpoint returned ${res.status}`);+ }++ const body = (await res.json()) as { quota: SiteAuditQuota };+ return body.quota;+}+/*** Start a Site Audit for a brand + URL via MCP.*diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex 99435a58f..c24fdba29 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -22,6 +22,8 @@ import {getPromptPerformanceFor,runSiteAuditFor,getSiteAuditFor,+ listSiteAuditsFor,+ getSiteAuditQuotaFor,} from './data';/**@@ -312,6 +314,50 @@ export function createMcpServer(auth: McpAuthContext): McpServer {},);+ server.registerTool(+ 'list_site_audits',+ {+ description:+ "List a brand's recent Site Audits (newest first) — id, url, status, total score, signals evaluated, and created date. Use this to find a past audit by url or date (then read it in full with get_site_audit) without needing the audit id. This is a read — no credit is consumed.",+ inputSchema: {+ brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),+ },+ },+ async (args) => {+ const audits = await listSiteAuditsFor(auth, args.brand_id);+ if (!audits) {+ return {+ content: [{ type: 'text', text: 'Brand not found' }],+ isError: true,+ };+ }+ return {+ content: [{ type: 'text', text: JSON.stringify(audits, null, 2) }],+ };+ },+ );++ server.registerTool(+ 'get_site_audit_quota',+ {+ description:+ "Check the org's monthly Site Audit allowance — { used, limit, remaining } (limit -1 means unlimited). Use this before run_site_audit to see how many audit credits remain this month. This is a read — no credit is consumed.",+ inputSchema: {},+ },+ async () => {+ const quota = await getSiteAuditQuotaFor(auth);+ if (!quota) {+ return {+ content: [{ type: 'text', text: 'No organization found for this API key' }],+ isError: true,+ };+ }+ return {+ content: [{ type: 'text', text: JSON.stringify(quota, null, 2) }],+ };+ },+ );+server.registerTool('update_opportunity_status',{