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 prompts and topics through MCP tools and REST endpoints (#35)
Gökhan Geyikc99bc3428778
diff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdxindex 5f8539f0f..5d990a249 100644--- a/docs/guides/mcp-server.mdx+++ b/docs/guides/mcp-server.mdx@@ -55,6 +55,8 @@ instead.| --- | --- || `list_brands` | List brands the authenticated user can access. || `get_visibility_summary` | Aggregate visibility score, mentions, citations, top competitors for a brand over an optional date range / model / region. |+| `list_topics` | List the topics on a brand with a prompt count per topic. Use for coverage audits (empty / over-concentrated topics). |+| `list_prompts` | List the prompts tracked on a brand, optionally filtered by topic, active status, or capped via `limit`. Returns the prompt text, topic, platforms, models, regions, and active flag. |More tools land regularly — check the [project roadmap](https://github.com/aeohub/ansvisor#whats-next).@@ -64,6 +66,8 @@ Ask your client things like:- _"List my Ansvisor brands."_- _"What's my visibility score on ChatGPT for the last 7 days?"_+- _"Are my topics balanced?" / "Which topic has the most prompts?"_+- _"Show me the prompts in my pricing topic."_- _"Who are my top 5 competitors by mention count this month?"_The model picks the right tool, fills in the brand id and filters, anddiff --git a/skills/ansvisor-aeo-coach-standalone/SKILL.md b/skills/ansvisor-aeo-coach-standalone/SKILL.mdindex a248d3590..7f9ddfa2c 100644--- a/skills/ansvisor-aeo-coach-standalone/SKILL.md+++ b/skills/ansvisor-aeo-coach-standalone/SKILL.md@@ -84,6 +84,33 @@ timestamps), `model` (slug or comma-separated slugs), `region`.}```+### `GET /api/mcp/topics`++Required query: `brand_id`. Returns topics on the brand with prompt+counts. Use for coverage audits.++```json+{ "topics": [+ { "id": "uuid", "name": "Pricing", "is_active": true,+ "prompt_count": 6, "created_at": "..." }+] }+```++### `GET /api/mcp/prompts`++Required query: `brand_id`. Optional: `topic_id`, `is_active`+(`true`/`false`), `limit` (default 100, max 500).++```json+{ "prompts": [+ { "id": "uuid", "text": "best ai for ...",+ "topic_id": "uuid", "topic_name": "Comparisons",+ "platforms": ["chatgpt", "perplexity"],+ "models": ["gpt-5-5"], "regions": ["US", "TR"],+ "is_active": true, "created_at": "..." }+] }+```+### `GET /api/mcp/whoami` (optional sanity check)Returns `{ userId, email, organizationId }`. Use to confirm the key@@ -207,6 +234,60 @@ When the user asks who they're up against:4. Optionally compare with last week's data (same date trick asworkflow 2) to flag whether a competitor is surging or fading.+### 4. Prompt coverage audit++When the user asks _"what am I tracking?"_, _"are my topics balanced?"_,+or any "do I have gaps" question:++1. Call `/api/mcp/topics?brand_id=...`.+2. Read `prompt_count` per topic. Healthy band is **3–8 prompts per+ topic**; anything outside is worth flagging.+3. Report shape, not raw dump. Template:++ > **Topic coverage — `<brand_name>`**+ >+ > **`<n>` topics**, **`<total>` prompts** (avg `<x>` per topic)+ >+ > **Gaps:**+ > - `<topic_a>` — 0 prompts (empty, not being tracked)+ > - `<topic_b>` — 1 prompt (under-covered)+ >+ > **Concentration:**+ > - `<topic_c>` — 14 prompts (over half your total, consider+ > splitting)+ >+ > **Next:** `<one concrete suggestion>`++4. Empty topics are often the biggest unlock — point at them first.+ See [`references/prompt-writing-tips.md`](references/prompt-writing-tips.md)+ for what kinds of prompts to add.++### 5. Prompt deep-dive++When the user asks _"what prompts are in topic X?"_ or _"show me my+prompts for `<theme>`"_:++1. If they named a topic by name, call `/api/mcp/topics?brand_id=...`+ first to resolve the topic name to its `id`.+2. Call `/api/mcp/prompts?brand_id=...&topic_id=...`.+3. Report as a short list with operational signals (platforms, models,+ active status), not a wall of text:++ > **`<topic_name>` — `<n>` prompts**+ >+ > 1. _"`<prompt text>`"_+ > → `<platforms.length>` platforms, `<models.length>` models,+ > `<regions.length>` regions, **active**+ > 2. ...+ >+ > **Inactive:** `<n>` prompts (paused)+ > **Coverage gap:** `<observation>`++4. Flag inactive prompts explicitly — users often forget they paused+ something and that's why visibility on that slice is flat.+5. If a prompt has zero `platforms` or zero `models`, it's effectively+ silent — surface that as a misconfiguration.+## Formatting principles- **Lead with the number, then the meaning.** Don't bury the score in adiff --git a/skills/ansvisor-aeo-coach/SKILL.md b/skills/ansvisor-aeo-coach/SKILL.mdindex 6507f4fc7..48e830ace 100644--- a/skills/ansvisor-aeo-coach/SKILL.md+++ b/skills/ansvisor-aeo-coach/SKILL.md@@ -55,6 +55,16 @@ API directly from this skill (that's a different skill).- `totals.totalCitations` — total citations to the brand's domains- `topCompetitors[]` — up to 5 competitors with `name`, `mentions`,`avgVisibility`+- **`list_topics`** — given a `brand_id`, returns the topics on that+ brand with `prompt_count` per topic. Use this for coverage audits+ (empty topics, lopsided distribution) and as the first call before+ drilling into prompts.+- **`list_prompts`** — given a `brand_id` (and optional `topic_id`,+ `is_active`, `limit`), returns prompts with `text`, `topic_name`,+ `platforms[]`, `models[]`, `regions[]`, `is_active`, `created_at`.+ Default limit 100, max 500. Use this when the user wants to see+ what's actually being tracked, or to spot inactive / mis-targeted+ prompts.More tools land regularly. If a tool you'd want isn't here, say so outloud rather than faking it.@@ -142,6 +152,61 @@ When the user asks who they're up against:4. Optionally compare with last week's data (same date trick asworkflow 2) to flag whether a competitor is surging or fading.+### 4. Prompt coverage audit++When the user asks _"what am I tracking?"_, _"are my topics balanced?"_,+or any "do I have gaps" question:++1. Call `list_topics(brand_id)`.+2. Read the `prompt_count` per topic. A healthy brand usually has+ **3–8 prompts per topic** — anything outside that band is worth+ flagging.+3. Report shape, not raw dump. Template:++ > **Topic coverage — `<brand_name>`**+ >+ > **`<n>` topics**, **`<total>` prompts** (avg `<x>` per topic)+ >+ > **Gaps:**+ > - `<topic_a>` — 0 prompts (empty, not being tracked)+ > - `<topic_b>` — 1 prompt (under-covered)+ >+ > **Concentration:**+ > - `<topic_c>` — 14 prompts (over half your total, consider+ > splitting)+ >+ > **Next:** `<one concrete suggestion>`++4. Empty topics are often the biggest unlock — point at them first.+ See [`references/prompt-writing-tips.md`](references/prompt-writing-tips.md)+ for what kinds of prompts to add.++### 5. Prompt deep-dive++When the user asks _"what prompts are in topic X?"_ or _"show me my+prompts for `<theme>`"_:++1. If they named a topic by name, call `list_topics(brand_id)` first+ to resolve the topic name to its `id`.+2. Call `list_prompts(brand_id, topic_id)`.+3. Report as a short list with the operational signals (platforms,+ models, active status), not a wall of text:++ > **`<topic_name>` — `<n>` prompts**+ >+ > 1. _"`<prompt text>`"_+ > → `<platforms.length>` platforms, `<models.length>` models,+ > `<regions.length>` regions, **active**+ > 2. ...+ >+ > **Inactive:** `<n>` prompts (paused)+ > **Coverage gap:** `<observation>`++4. Flag inactive prompts explicitly — users often forget they paused+ something and that's why visibility on that slice is flat.+5. If a prompt has zero platforms or zero models, it's effectively+ silent — surface that as a misconfiguration.+## Formatting principles- **Lead with the number, then the meaning.** Don't bury the score in adiff --git a/web/src/app/api/mcp/prompts/route.ts b/web/src/app/api/mcp/prompts/route.tsnew file mode 100644index 000000000..18f419f64--- /dev/null+++ b/web/src/app/api/mcp/prompts/route.ts@@ -0,0 +1,42 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { listPromptsFor } 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 topicId = url.searchParams.get('topic_id') ?? undefined;+ const isActiveRaw = url.searchParams.get('is_active');+ const limitRaw = url.searchParams.get('limit');++ const isActive =+ isActiveRaw === 'true'+ ? true+ : isActiveRaw === 'false'+ ? false+ : undefined;+ const limit = limitRaw ? Number.parseInt(limitRaw, 10) : undefined;++ try {+ const prompts = await listPromptsFor(auth, {+ brandId,+ topicId,+ isActive,+ limit: Number.isFinite(limit) ? limit : undefined,+ });+ if (prompts === null) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });+ }+ return NextResponse.json({ prompts });+ } 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/topics/route.ts b/web/src/app/api/mcp/topics/route.tsnew file mode 100644index 000000000..7e4263ab5--- /dev/null+++ b/web/src/app/api/mcp/topics/route.ts@@ -0,0 +1,25 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { listTopicsFor } 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 });+ }++ try {+ const topics = await listTopicsFor(auth, brandId);+ if (topics === null) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });+ }+ return NextResponse.json({ topics });+ } 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 8a3e0301e..bb588d119 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -161,3 +161,163 @@ export async function getVisibilitySummaryFor(topCompetitors,};}++// ── Topics ────────────────────────────────────────────────────────────────────++export interface TopicRow {+ id: string;+ name: string;+ is_active: boolean;+ prompt_count: number;+ created_at: string;+}++export async function listTopicsFor(+ auth: McpAuthContext,+ brandId: string,+): Promise<TopicRow[] | null> {+ if (!auth.organizationId) return null;++ // Ownership check — make sure the brand belongs to the caller's org.+ const { data: brand } = await supabaseAdmin+ .from('brands')+ .select('id')+ .eq('id', brandId)+ .eq('organization_id', auth.organizationId)+ .maybeSingle();+ if (!brand) return null;++ const { data: topics, error: tErr } = await supabaseAdmin+ .from('topics')+ .select('id, name, is_active, created_at')+ .eq('brand_id', brandId)+ .order('created_at', { ascending: true });+ if (tErr) throw new Error(tErr.message);++ const topicRows = (topics ?? []) as Array<{+ id: string;+ name: string;+ is_active: boolean | null;+ created_at: string;+ }>;+ if (topicRows.length === 0) return [];++ // Count prompts per topic in one round trip (instead of N+1) by selecting+ // topic_id from prompts joined to prompt_sets for this brand and bucketing+ // client-side. Topic-less prompts (topic_id null) are intentionally+ // dropped here — they show up in list_prompts but don't add to any topic.+ const { data: prompts } = await supabaseAdmin+ .from('prompts')+ .select('topic_id, prompt_sets!inner(brand_id)')+ .eq('prompt_sets.brand_id', brandId)+ .not('topic_id', 'is', null);++ const promptRows =+ (prompts as Array<{ topic_id: string | null }> | null) ?? [];+ const countByTopic = new Map<string, number>();+ for (const row of promptRows) {+ if (!row.topic_id) continue;+ countByTopic.set(row.topic_id, (countByTopic.get(row.topic_id) ?? 0) + 1);+ }++ return topicRows.map((t) => ({+ id: t.id,+ name: t.name,+ is_active: t.is_active ?? true,+ prompt_count: countByTopic.get(t.id) ?? 0,+ created_at: t.created_at,+ }));+}++// ── Prompts ───────────────────────────────────────────────────────────────────++export interface PromptRow {+ id: string;+ text: string;+ topic_id: string | null;+ topic_name: string | null;+ platforms: string[];+ models: string[];+ regions: string[];+ is_active: boolean;+ created_at: string;+}++export interface ListPromptsParams {+ brandId: string;+ topicId?: string;+ isActive?: boolean;+ limit?: number;+}++const PROMPT_LIST_DEFAULT_LIMIT = 100;+const PROMPT_LIST_MAX_LIMIT = 500;++export async function listPromptsFor(+ auth: McpAuthContext,+ params: ListPromptsParams,+): Promise<PromptRow[] | null> {+ if (!auth.organizationId) return null;++ 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 ?? PROMPT_LIST_DEFAULT_LIMIT, 1),+ PROMPT_LIST_MAX_LIMIT,+ );++ let query = supabaseAdmin+ .from('prompts')+ .select(+ 'id, text, topic_id, platforms, models, regions, is_active, created_at, prompt_sets!inner(brand_id), topics(name)',+ )+ .eq('prompt_sets.brand_id', params.brandId)+ .order('created_at', { ascending: false })+ .limit(limit);++ if (params.topicId) query = query.eq('topic_id', params.topicId);+ if (typeof params.isActive === 'boolean') {+ query = query.eq('is_active', params.isActive);+ }++ const { data, error } = await query;+ if (error) throw new Error(error.message);++ // Supabase's generated types model the prompts→topics FK as an array (it+ // can't tell single vs many from the schema alone), so the join returns+ // `topics: { name }[]` rather than `topics: { name } | null`. We know it's+ // a single relation, so peel the first element off.+ const rows =+ (data as unknown as Array<{+ id: string;+ text: string;+ topic_id: string | null;+ platforms: string[] | null;+ models: string[] | null;+ regions: string[] | null;+ is_active: boolean;+ created_at: string;+ topics: Array<{ name: string }> | { name: string } | null;+ }> | null) ?? [];++ return rows.map((r) => {+ const topic = Array.isArray(r.topics) ? r.topics[0] ?? null : r.topics;+ return {+ id: r.id,+ text: r.text,+ topic_id: r.topic_id,+ topic_name: topic?.name ?? null,+ platforms: r.platforms ?? [],+ models: r.models ?? [],+ regions: r.regions ?? [],+ is_active: r.is_active,+ created_at: r.created_at,+ };+ });+}diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex 16276c5f4..5f1246be9 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -2,7 +2,12 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { z } from 'zod';import type { McpAuthContext } from '@/lib/mcp-auth';-import { getVisibilitySummaryFor, listBrandsFor } from './data';+import {+ getVisibilitySummaryFor,+ listBrandsFor,+ listPromptsFor,+ listTopicsFor,+} from './data';/*** Build a fresh MCP server bound to a single authenticated request.@@ -88,5 +93,88 @@ export function createMcpServer(auth: McpAuthContext): McpServer {},);+ server.registerTool(+ 'list_topics',+ {+ description:+ 'List topics for a brand, each with the number of prompts attached to it. Use this to audit prompt coverage ("are any topics empty / under-represented?") or before drilling into prompts for a specific theme. Topic-less prompts are not counted here — call list_prompts without a topic filter to see them.',+ inputSchema: {+ brand_id: z+ .string()+ .uuid()+ .describe('Brand UUID, from list_brands.'),+ },+ },+ async (args) => {+ const topics = await listTopicsFor(auth, args.brand_id);+ if (topics === null) {+ return {+ content: [{ type: 'text', text: 'Brand not found' }],+ isError: true,+ };+ }+ return {+ content: [+ { type: 'text', text: JSON.stringify(topics, null, 2) },+ ],+ };+ },+ );++ server.registerTool(+ 'list_prompts',+ {+ description:+ 'List the prompts tracked for a brand, optionally filtered by topic or active status. Returns each prompt with its text, topic, platforms, models, regions, and active flag. Use this when the user asks what is being tracked, wants to drill into a specific topic, or wants to spot inactive / mis-targeted prompts.',+ inputSchema: {+ brand_id: z+ .string()+ .uuid()+ .describe('Brand UUID, from list_brands.'),+ topic_id: z+ .string()+ .uuid()+ .optional()+ .describe(+ 'Optional topic UUID (from list_topics) to filter to one topic.',+ ),+ is_active: z+ .boolean()+ .optional()+ .describe(+ 'Optional filter — true returns only active prompts, false only inactive.',+ ),+ limit: z+ .number()+ .int()+ .min(1)+ .max(500)+ .optional()+ .describe(+ 'Optional row cap (default 100, max 500). Newest prompts come first.',+ ),+ },+ },+ async (args) => {+ const prompts = await listPromptsFor(auth, {+ brandId: args.brand_id,+ topicId: args.topic_id,+ isActive: args.is_active,+ limit: args.limit,+ });+ if (prompts === null) {+ return {+ content: [{ type: 'text', text: 'Brand not found' }],+ isError: true,+ };+ }+ return {+ content: [+ { type: 'text', text: JSON.stringify(prompts, null, 2) },+ ],+ };+ },+ );+return server;}