Skip to content

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.

feat(mcp): add prompt suggestion tools (#1157)

Sanjeev Kumar0b1fe7fac102
diff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdx
index 816d8821a..80fb319de 100644
--- a/docs/guides/mcp-server.mdx
+++ b/docs/guides/mcp-server.mdx
@@ -220,7 +220,7 @@ instead.
## Available tools
-The MCP server exposes **33 tools**. Descriptions below match
+The MCP server exposes **36 tools**. Descriptions below match
[`web/src/lib/mcp/server.ts`](https://github.com/ansvisor/ansvisor/blob/main/web/src/lib/mcp/server.ts).
Tools that change data are marked **writes** — only call them on explicit user
intent, not during exploratory queries.
@@ -259,6 +259,9 @@ intent, not during exploratory queries.
| `list_topic_suggestions` | Pending AI-generated topic suggestions awaiting accept or dismiss. | |
| `accept_topic_suggestion` | Accept one pending suggestion: creates a topic and marks the suggestion added. | **yes** |
| `dismiss_topic_suggestion` | Dismiss one pending suggestion so it does not reappear in future batches. | **yes** |
+| `list_prompt_suggestions` | Pending AI-generated prompt suggestions with source details, expiry and a stale flag. Does not generate new suggestions. | |
+| `accept_prompt_suggestion` | Create a tracked prompt from one pending suggestion using the brand's default engines and plan/location checks. | **yes** |
+| `dismiss_prompt_suggestion` | Dismiss one pending prompt suggestion so it no longer appears in future lists. | **yes** |
| `get_prompt_volumes` | Per-prompt Google and estimated AI search demand and competition for prompts that already have analysis. | |
| `get_prompt_usage` | Tracked-prompt usage against the plan: the brand's active and paused prompts, and the account's active prompts, brands, prompt locations used and location limit. | |
diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.ts
index 87bf72ffa..a688852be 100644
--- a/web/src/lib/mcp/data.ts
+++ b/web/src/lib/mcp/data.ts
@@ -22,6 +22,12 @@ import { mapSignalRows, type SignalRow } from '@/lib/signals/map';
import { readPromptPlaces } from '@/lib/signals/prompt-places';
import { currentActionFirst, signalDetailForApi, type SignalActionRef } from '@/lib/signals/detail';
import { parseTaskDetails } from '@/lib/action-center/task-details';
+import { locationCode, isValidLocation } from '@/lib/region';
+import { getOrgLocationUsage, locationLimitMessage } from '@/lib/prompt-locations';
+import {
+ filterPromptSuggestionEngines,
+ promptSuggestionsAreStale,
+} from './prompt-suggestions-utils';
/**
* Pure data-fetch functions shared by the MCP route and the parallel REST
@@ -505,6 +511,262 @@ export async function acceptTopicSuggestionFor(
return { suggestion_id: suggestionId, topic_id: topic.id, topic_name: topic.name };
}
+// ── Prompt suggestions (#918) ──────────────────────────────────────────────────
+// These tools operate only on suggestions already persisted by the dashboard.
+// Generation remains behind the existing plan-gated refresh action.
+
+export interface PromptSuggestionRow {
+ id: string;
+ suggested_text: string;
+ topic_name: string | null;
+ topic_id: string | null;
+ reason: string | null;
+ est_volume: number | null;
+ relevance: number | null;
+ source: string;
+ source_data: Record<string, unknown> | null;
+ generated_at: string;
+ expires_at: string;
+}
+
+export interface PromptSuggestionList {
+ suggestions: PromptSuggestionRow[];
+ stale: boolean;
+}
+
+/** List pending suggestions only after verifying that the brand belongs to this organization. */
+export async function listPromptSuggestionsFor(
+ auth: McpAuthContext,
+ brandId: string,
+): Promise<PromptSuggestionList | null> {
+ if (!auth.organizationId) return null;
+
+ const { data: brand, error: brandError } = await supabaseAdmin
+ .from('brands')
+ .select('id')
+ .eq('id', brandId)
+ .eq('organization_id', auth.organizationId)
+ .maybeSingle();
+ if (brandError) throw new Error(brandError.message);
+ if (!brand) return null;
+
+ const { data, error } = await supabaseAdmin
+ .from('prompt_suggestions')
+ .select(
+ 'id, suggested_text, topic_name, topic_id, reason, est_volume, relevance, source, source_data, generated_at, expires_at',
+ )
+ .eq('brand_id', brandId)
+ .eq('status', 'new')
+ .order('generated_at', { ascending: false });
+ if (error) throw new Error(error.message);
+
+ const suggestions = (data ?? []) as unknown as PromptSuggestionRow[];
+ return { suggestions, stale: promptSuggestionsAreStale(suggestions) };
+}
+
+export interface DismissedPromptSuggestion {
+ id: string;
+ status: 'dismissed';
+}
+
+/** Dismiss only a pending suggestion belonging to the authenticated organization. */
+export async function dismissPromptSuggestionFor(
+ auth: McpAuthContext,
+ suggestionId: string,
+): Promise<DismissedPromptSuggestion | null> {
+ if (!auth.organizationId) return null;
+
+ const { data: owned, error: lookupError } = await supabaseAdmin
+ .from('prompt_suggestions')
+ .select('id, brands!inner(organization_id)')
+ .eq('id', suggestionId)
+ .eq('brands.organization_id', auth.organizationId)
+ .eq('status', 'new')
+ .maybeSingle();
+ if (lookupError) throw new Error(lookupError.message);
+ if (!owned) return null;
+
+ const { data, error } = await supabaseAdmin
+ .from('prompt_suggestions')
+ .update({ status: 'dismissed', updated_at: new Date().toISOString() })
+ .eq('id', suggestionId)
+ .eq('status', 'new')
+ .select('id, status')
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!data) return null;
+
+ return { id: data.id, status: 'dismissed' };
+}
+
+export interface AcceptedPromptSuggestion {
+ suggestion_id: string;
+ prompt_id: string;
+ prompt_text: string;
+ status: 'added';
+}
+
+export type AcceptPromptSuggestionResult =
+ | AcceptedPromptSuggestion
+ | { error: string; code?: 'plan_limit' };
+
+/**
+ * Accept one pending prompt suggestion by creating a tracked prompt, then
+ * marking the suggestion added. Mirrors the dashboard's target defaults,
+ * plan engine filtering, shopping-mode behavior, region choice and location
+ * quota check. Every lookup is organization-scoped; duplicate acceptance
+ * removes any losing concurrent insert rather than leaving duplicate prompts.
+ */
+export async function acceptPromptSuggestionFor(
+ auth: McpAuthContext,
+ suggestionId: string,
+): Promise<AcceptPromptSuggestionResult | null> {
+ if (!auth.organizationId) return null;
+
+ const { data: suggestion, error: suggestionError } = await supabaseAdmin
+ .from('prompt_suggestions')
+ .select('id, brand_id, suggested_text, topic_name, brands!inner(organization_id)')
+ .eq('id', suggestionId)
+ .eq('brands.organization_id', auth.organizationId)
+ .eq('status', 'new')
+ .maybeSingle();
+ if (suggestionError) throw new Error(suggestionError.message);
+ if (!suggestion) return null;
+
+ const { data: brand, error: brandError } = await supabaseAdmin
+ .from('brands')
+ .select('id, organization_id, region, state, shopping_mode_enabled')
+ .eq('id', suggestion.brand_id)
+ .eq('organization_id', auth.organizationId)
+ .maybeSingle();
+ if (brandError) throw new Error(brandError.message);
+ if (!brand) return null;
+
+ const { data: promptSet, error: promptSetError } = await supabaseAdmin
+ .from('prompt_sets')
+ .select('id')
+ .eq('brand_id', brand.id)
+ .order('created_at', { ascending: true })
+ .limit(1)
+ .maybeSingle();
+ if (promptSetError) throw new Error(promptSetError.message);
+ if (!promptSet) {
+ return { error: 'No prompt set exists for this brand. Create one first.' };
+ }
+
+ const { data: defaults, error: defaultsError } = await supabaseAdmin
+ .from('prompts')
+ .select('platforms, models')
+ .eq('prompt_set_id', promptSet.id)
+ .eq('is_active', true)
+ .order('created_at', { ascending: false })
+ .limit(1)
+ .maybeSingle();
+ if (defaultsError) throw new Error(defaultsError.message);
+
+ const defaultPlatforms =
+ Array.isArray(defaults?.platforms) && defaults.platforms.length > 0
+ ? (defaults.platforms as string[])
+ : ['chatgpt-web'];
+ const defaultModels = Array.isArray(defaults?.models) ? (defaults.models as string[]) : [];
+
+ const { data: organization, error: organizationError } = await supabaseAdmin
+ .from('organizations')
+ .select(ORG_PLAN_COLUMNS)
+ .eq('id', auth.organizationId)
+ .maybeSingle();
+ if (organizationError) throw new Error(organizationError.message);
+ if (!organization) return { error: 'Could not load the organization plan.' };
+
+ const plan = planFromOrgRow(organization);
+ const filtered = filterPromptSuggestionEngines(plan.limits, defaultPlatforms, defaultModels);
+ if (filtered.platforms.length === 0 && filtered.models.length === 0) {
+ return { error: 'Your plan does not allow any of the default prompt engines.' };
+ }
+
+ const platforms = brand.shopping_mode_enabled
+ ? Array.from(new Set([...filtered.platforms, 'chatgpt-shopping']))
+ : filtered.platforms.filter((platform) => platform !== 'chatgpt-shopping');
+ if (platforms.length === 0 && filtered.models.length === 0) {
+ return { error: 'At least one platform or model must be selected.' };
+ }
+
+ const usage = await getOrgLocationUsage(supabaseAdmin, auth.organizationId);
+ const limitError = locationLimitMessage(plan, usage.total, 1);
+ if (limitError) return { error: limitError, code: 'plan_limit' };
+
+ const country = (brand.region as string | null) ?? 'US';
+ const candidateRegion = locationCode(country, brand.state as string | null);
+ const region = isValidLocation(candidateRegion) ? candidateRegion : country;
+
+ let topicId: string | null = null;
+ if (suggestion.topic_name) {
+ const { data: topic, error: topicError } = await supabaseAdmin
+ .from('topics')
+ .select('id')
+ .eq('brand_id', brand.id)
+ .eq('name', suggestion.topic_name)
+ .limit(1)
+ .maybeSingle();
+ if (topicError) throw new Error(topicError.message);
+ topicId = topic?.id ?? null;
+ }
+
+ const { data: prompt, error: promptError } = await supabaseAdmin
+ .from('prompts')
+ .insert({
+ prompt_set_id: promptSet.id,
+ text: suggestion.suggested_text,
+ category: suggestion.topic_name ?? null,
+ topic_id: topicId,
+ platforms,
+ regions: [region],
+ models: filtered.models,
+ is_active: true,
+ })
+ .select('id, text')
+ .single();
+ if (promptError || !prompt) {
+ return { error: promptError?.message ?? 'Failed to add the prompt.' };
+ }
+
+ const { data: updated, error: updateError } = await supabaseAdmin
+ .from('prompt_suggestions')
+ .update({
+ status: 'added',
+ added_prompt_id: prompt.id,
+ updated_at: new Date().toISOString(),
+ })
+ .eq('id', suggestionId)
+ .eq('status', 'new')
+ .select('id')
+ .maybeSingle();
+
+ if (updateError || !updated) {
+ // A concurrent accept may have won after our initial read. Remove the
+ // prompt we just inserted so the suggestion cannot create duplicates.
+ const { error: cleanupError } = await supabaseAdmin
+ .from('prompts')
+ .delete()
+ .eq('id', prompt.id);
+ if (cleanupError) {
+ throw new Error(
+ updateError?.message ??
+ 'Suggestion was processed concurrently and the duplicate prompt could not be removed.',
+ );
+ }
+ if (updateError) throw new Error(updateError.message);
+ return null;
+ }
+
+ return {
+ suggestion_id: suggestionId,
+ prompt_id: prompt.id,
+ prompt_text: prompt.text,
+ status: 'added',
+ };
+}
+
// ── Prompts ───────────────────────────────────────────────────────────────────
export interface PromptRow {
diff --git a/web/src/lib/mcp/prompt-suggestions-utils.test.ts b/web/src/lib/mcp/prompt-suggestions-utils.test.ts
new file mode 100644
index 000000000..1c19af1d4
--- /dev/null
+++ b/web/src/lib/mcp/prompt-suggestions-utils.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from 'vitest';
+import {
+ filterPromptSuggestionEngines,
+ promptSuggestionsAreStale,
+} from './prompt-suggestions-utils';
+
+describe('filterPromptSuggestionEngines', () => {
+ it('keeps only plan-allowed platforms and models', () => {
+ expect(
+ filterPromptSuggestionEngines(
+ { allowedScrapers: ['chatgpt-web'], allowedModels: ['gpt-4o'] },
+ ['chatgpt-web', 'perplexity', 'unknown'],
+ ['gpt-4o', 'claude-3', 'unknown'],
+ ),
+ ).toEqual({ platforms: ['chatgpt-web'], models: ['gpt-4o'] });
+ });
+
+ it('uses all configured engines when a plan has no allow-list', () => {
+ const result = filterPromptSuggestionEngines(
+ { allowedScrapers: null, allowedModels: null },
+ ['chatgpt-web', 'unknown'],
+ ['unknown'],
+ );
+ expect(result.platforms).toContain('chatgpt-web');
+ expect(result.platforms).not.toContain('unknown');
+ expect(result.models).not.toContain('unknown');
+ });
+
+ it('respects an explicitly empty allow-list', () => {
+ expect(
+ filterPromptSuggestionEngines(
+ { allowedScrapers: [], allowedModels: [] },
+ ['chatgpt-web'],
+ ['gpt-4o'],
+ ),
+ ).toEqual({ platforms: [], models: [] });
+ });
+});
+
+describe('promptSuggestionsAreStale', () => {
+ it('treats an empty list as stale', () => {
+ expect(promptSuggestionsAreStale([])).toBe(true);
+ });
+
+ it('is not stale while any suggestion remains unexpired', () => {
+ const now = Date.parse('2026-10-18T12:00:00.000Z');
+ expect(
+ promptSuggestionsAreStale(
+ [{ expires_at: '2026-10-18T11:59:59.000Z' }, { expires_at: '2026-10-18T12:00:01.000Z' }],
+ now,
+ ),
+ ).toBe(false);
+ });
+
+ it('treats all-expired or invalid expiries as stale', () => {
+ const now = Date.parse('2026-10-18T12:00:00.000Z');
+ expect(promptSuggestionsAreStale([{ expires_at: '2026-10-18T11:59:59.000Z' }], now)).toBe(true);
+ expect(promptSuggestionsAreStale([{ expires_at: 'not-a-date' }], now)).toBe(true);
+ });
+});
diff --git a/web/src/lib/mcp/prompt-suggestions-utils.ts b/web/src/lib/mcp/prompt-suggestions-utils.ts
new file mode 100644
index 000000000..5b251e6d0
--- /dev/null
+++ b/web/src/lib/mcp/prompt-suggestions-utils.ts
@@ -0,0 +1,39 @@
+import { ALL_MODELS, ALL_SCRAPERS } from '@/config/prompt-options';
+
+interface PromptEngineLimits {
+ allowedScrapers?: readonly string[] | null;
+ allowedModels?: readonly string[] | null;
+}
+
+/** Apply the same engine allow-lists used when adding prompts in the dashboard. */
+export function filterPromptSuggestionEngines(
+ limits: PromptEngineLimits,
+ platforms: readonly string[],
+ models: readonly string[],
+): { platforms: string[]; models: string[] } {
+ const allowedScrapers = limits.allowedScrapers
+ ? new Set(limits.allowedScrapers)
+ : new Set(ALL_SCRAPERS.map((scraper) => scraper.id));
+ const allowedModels = limits.allowedModels
+ ? new Set(limits.allowedModels)
+ : new Set(ALL_MODELS.map((model) => model.id));
+
+ return {
+ platforms: platforms.filter((platform) => allowedScrapers.has(platform)),
+ models: models.filter((model) => allowedModels.has(model)),
+ };
+}
+
+/** Match the dashboard's stale state: empty lists and all-expired lists are stale. */
+export function promptSuggestionsAreStale(
+ suggestions: readonly { expires_at: string }[],
+ now = Date.now(),
+): boolean {
+ return (
+ suggestions.length === 0 ||
+ suggestions.every((suggestion) => {
+ const expiresAt = new Date(suggestion.expires_at).getTime();
+ return !Number.isFinite(expiresAt) || expiresAt < now;
+ })
+ );
+}
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index 8f9aa4a11..04975228e 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -6,6 +6,9 @@ import {
CONTENT_OPPORTUNITY_STATUSES,
acceptTopicSuggestionFor,
dismissTopicSuggestionFor,
+ listPromptSuggestionsFor,
+ acceptPromptSuggestionFor,
+ dismissPromptSuggestionFor,
generateBriefFor,
getCompetitorComparisonFor,
listCompetitorsFor,
@@ -267,6 +270,89 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
},
);
+ server.registerTool(
+ 'list_prompt_suggestions',
+ {
+ description:
+ 'List pending AI-generated prompt suggestions for a brand, including the suggested query, topic, reason, estimated volume, relevance, source provenance, generation time and expiry. The result includes a stale flag when no suggestions are available or all have expired. This only reads suggestions already generated by the dashboard; it does not generate new suggestions.',
+ inputSchema: {
+ brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),
+ },
+ },
+ async (args) => {
+ const result = await listPromptSuggestionsFor(auth, args.brand_id);
+ if (result === null) {
+ return {
+ content: [{ type: 'text', text: 'Brand not found' }],
+ isError: true,
+ };
+ }
+ return {
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
+ };
+ },
+ );
+
+ server.registerTool(
+ 'accept_prompt_suggestion',
+ {
+ description:
+ "Accept one pending prompt suggestion by creating a tracked prompt with the brand's default platform/model settings and marking the suggestion added. This consumes one active prompt location and respects the organization's plan limit and allowed engines. Only fire on explicit user intent for a specific suggestion from list_prompt_suggestions, never as part of an exploratory query. Accepting the same suggestion twice does not create a duplicate prompt.",
+ inputSchema: {
+ suggestion_id: relaxedUuid.describe(
+ 'Prompt suggestion UUID, from list_prompt_suggestions.',
+ ),
+ },
+ },
+ async (args) => {
+ const result = await acceptPromptSuggestionFor(auth, args.suggestion_id);
+ if (result === null) {
+ return {
+ content: [
+ { type: 'text', text: 'Suggestion not found, not pending, or already processed' },
+ ],
+ isError: true,
+ };
+ }
+ if ('error' in result) {
+ return {
+ content: [{ type: 'text', text: result.error }],
+ isError: true,
+ };
+ }
+ return {
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
+ };
+ },
+ );
+
+ server.registerTool(
+ 'dismiss_prompt_suggestion',
+ {
+ description:
+ 'Dismiss a pending prompt suggestion so it no longer appears in future suggestion lists. Only fire on explicit user intent for a specific suggestion from list_prompt_suggestions, never as part of an exploratory query.',
+ inputSchema: {
+ suggestion_id: relaxedUuid.describe(
+ 'Prompt suggestion UUID, from list_prompt_suggestions.',
+ ),
+ },
+ },
+ async (args) => {
+ const result = await dismissPromptSuggestionFor(auth, args.suggestion_id);
+ if (result === null) {
+ 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_competitors',
{