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(mentions): read Mentions & Sentiment and correct a sentiment from the API and MCP (#1126)

Cihan30d596726bed
diff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdx
index 80fb319de..eabe912fa 100644
--- a/docs/guides/mcp-server.mdx
+++ b/docs/guides/mcp-server.mdx
@@ -250,6 +250,26 @@ intent, not during exploratory queries.
| `list_reports` | Saved report snapshots for a brand, newest first; returns metadata without the full payload (default 50, max 100 per call). | |
| `get_report` | Full immutable snapshot for one saved report, including its stored payload; does not regenerate it. | |
+### Mentions & sentiment
+
+The Mentions & Sentiment page's figures, under the page's filters: `date_from` / `date_to` (the last 30 days when left out), `platform`, `region`, `topic_id` and `search` over the prompts' text. They are built from the stored answers with no LLM call. Net sentiment runs from −100 to +100, and under 20 mentions a figure is marked `lowSample`, with no change read into it. Sentiment is measured for your brand only.
+
+| Tool | What it does | Writes |
+| --- | --- | --- |
+| `get_mentions_summary` | The Overview: times named (the page's Total mentions), mentions, mention rate, prompts with mentions, average position and sentiment, now and in the window before, with each change taken on the prompts both windows answered (`changes.basis`), as the page's cards; the platform that moved net sentiment most, each platform and each day. | |
+| `list_mentions` | The responses naming the brand, 100 a page, with sentiment, position, competitors in the same response and an excerpt; filter by `sentiment` or `competitor_id` (`none` for no competitor) and sort. | |
+| `get_mention` | One response in full: text, citations, competitors named, sentiment and its latest correction. | |
+| `get_mention_competitors` | How often AI names each competitor in the brand's responses, and how often in the same response as the brand. | |
+| `get_mentions_perception` | What AI associates with the brand: its terms, the attributes that set it apart from its top competitors, co-mentions and the biggest gap. | |
+| `override_mention_sentiment` | "Sentiment is wrong": correct one response's sentiment, with an optional note. The key's user must be an admin or manager. | **yes** |
+
+The same reads are available over REST with the same `ans_` key: `GET /api/mcp/mentions/summary`, `/api/mcp/mentions`, `/api/mcp/mentions/<id>`, `/api/mcp/mentions/competitors` and `/api/mcp/mentions/perception`, with the filters as query parameters. A correction is `POST /api/mcp/mentions/<id>/sentiment-override` with `{ "sentiment": "negative", "note": "…" }`.
+
+```bash
+curl "https://app.ansvisor.com/api/mcp/mentions/summary?brand_id=<brand_id>&platform=gemini-web" \
+ -H "Authorization: Bearer ans_..."
+```
+
### Topics & prompts
| Tool | What it does | Writes |
@@ -327,6 +347,7 @@ Ask your client things like:
- _"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?"_
+- _"Why did our sentiment drop on Gemini?"_
The model picks the right tool, fills in the brand id and filters, and
answers in plain English using the returned data.
diff --git a/supabase/migrations/00223_mention_sentiment_override_api.sql b/supabase/migrations/00223_mention_sentiment_override_api.sql
new file mode 100644
index 000000000..b65f95c58
--- /dev/null
+++ b/supabase/migrations/00223_mention_sentiment_override_api.sql
@@ -0,0 +1,120 @@
+-- ============================================================================
+-- 00223: "Sentiment is wrong" over the API and MCP (MS-13)
+-- ============================================================================
+-- override_mention_sentiment (00160) takes the person correcting from
+-- auth.uid(), so it only works for a signed-in admin or manager. The API and
+-- MCP tools authenticate with an API key and reach the database as the
+-- service role, where auth.uid() is null.
+--
+-- Restated with p_user_id: the person the service role corrects for, the API
+-- key's owner. It counts only for the service role; a signed-in caller is
+-- always auth.uid(), whatever it passes. Either way the person must be an
+-- admin or manager of the answer's organization, and the correction is logged
+-- under their name, as from the dashboard.
+--
+-- The 3-argument function is dropped rather than overloaded: a call with
+-- three arguments would match both, and the dashboard's call keeps working
+-- through p_user_id's default.
+
+drop function if exists public.override_mention_sentiment(uuid, text, text);
+
+-- Returns jsonb { changed, previous, sentiment, override: { id, sentiment,
+-- previous_sentiment, note, user_name, created_at } }. Raises:
+-- 42501 the person isn't an admin or manager of the answer's organization
+-- P0002 no such answer
+-- 22023 not a sentiment, or an answer that doesn't name the brand
+create or replace function public.override_mention_sentiment(
+ p_result_id uuid,
+ p_sentiment text,
+ p_note text default null,
+ p_user_id uuid default null
+)
+returns jsonb
+language plpgsql
+security definer
+set search_path to 'public'
+as $$
+declare
+ v_row record;
+ v_user record;
+ v_day date;
+ v_note text := nullif(btrim(coalesce(p_note, '')), '');
+ v_override public.sentiment_overrides;
+ -- Who corrects: the API key's owner for the service role, else the caller.
+ v_person uuid := case when auth.role() = 'service_role' then p_user_id else auth.uid() end;
+begin
+ if p_sentiment is null or p_sentiment not in ('positive', 'neutral', 'negative') then
+ raise exception 'Invalid sentiment' using errcode = '22023';
+ end if;
+ if v_note is not null and char_length(v_note) > 500 then
+ raise exception 'The note is longer than 500 characters' using errcode = '22023';
+ end if;
+
+ select pr.id, pr.brand_id, pr.sentiment, pr.mention_count, pr.created_at, b.organization_id
+ into v_row
+ from public.prompt_results pr
+ join public.brands b on b.id = pr.brand_id
+ where pr.id = p_result_id
+ for update of pr;
+ if not found then
+ raise exception 'Answer not found' using errcode = 'P0002';
+ end if;
+
+ select p.id, p.full_name, p.role
+ into v_user
+ from public.profiles p
+ where p.id = v_person
+ and p.organization_id = v_row.organization_id
+ and p.role = any (array['admin', 'manager']::public.user_role[]);
+ if not found then
+ raise exception 'Only admins and managers can correct a sentiment' using errcode = '42501';
+ end if;
+
+ -- Sentiment is only classified for answers that name the brand.
+ if coalesce(v_row.mention_count, 0) <= 0 then
+ raise exception 'This answer does not name the brand' using errcode = '22023';
+ end if;
+
+ if v_row.sentiment = p_sentiment then
+ return jsonb_build_object('changed', false, 'previous', v_row.sentiment,
+ 'sentiment', p_sentiment, 'override', null);
+ end if;
+
+ update public.prompt_results
+ set sentiment = p_sentiment,
+ visibility_score = greatest(0, least(100,
+ coalesce(visibility_score, 0)
+ - public.sentiment_visibility_bonus(v_row.sentiment)
+ + public.sentiment_visibility_bonus(p_sentiment)))
+ where id = p_result_id;
+
+ insert into public.sentiment_overrides
+ (result_id, brand_id, previous_sentiment, sentiment, note, user_id, user_name)
+ values
+ (p_result_id, v_row.brand_id, coalesce(v_row.sentiment, 'neutral'), p_sentiment, v_note,
+ v_user.id, v_user.full_name)
+ returning * into v_override;
+
+ -- The answer's day in the rollups, now rather than at the nightly sweep.
+ v_day := (v_row.created_at at time zone 'utc')::date;
+ perform public.refresh_insights_daily(v_row.brand_id, v_day, v_day);
+ perform public.refresh_mentions_daily(v_row.brand_id, v_day, v_day);
+
+ return jsonb_build_object(
+ 'changed', true,
+ 'previous', v_override.previous_sentiment,
+ 'sentiment', v_override.sentiment,
+ 'override', jsonb_build_object(
+ 'id', v_override.id,
+ 'sentiment', v_override.sentiment,
+ 'previous_sentiment', v_override.previous_sentiment,
+ 'note', v_override.note,
+ 'user_name', v_override.user_name,
+ 'created_at', v_override.created_at));
+end;
+$$;
+
+revoke execute on function public.override_mention_sentiment(uuid, text, text, uuid)
+ from public, anon;
+grant execute on function public.override_mention_sentiment(uuid, text, text, uuid)
+ to authenticated, service_role;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 41415a866..cd91babaa 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -32569,6 +32569,130 @@ grant execute on function public.content_plan_pages(uuid, integer) to authentica
comment on function public.content_plan_pages(uuid, integer) is
'Content Editor (CE-014): the brand''s 100 most cited pages over the last N (7, 30 or 90) whole UTC days to yesterday and the N before, from the daily rollups: citations, the brand''s answers in each window, platforms citing at a lower rate, AI visits and how many of its other pages compete for the same prompts; with the earlier window''s first day and the brand''s first tracked day. Security definer with an organization check.';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00223_mention_sentiment_override_api.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00223: "Sentiment is wrong" over the API and MCP (MS-13)
+-- ============================================================================
+-- override_mention_sentiment (00160) takes the person correcting from
+-- auth.uid(), so it only works for a signed-in admin or manager. The API and
+-- MCP tools authenticate with an API key and reach the database as the
+-- service role, where auth.uid() is null.
+--
+-- Restated with p_user_id: the person the service role corrects for, the API
+-- key's owner. It counts only for the service role; a signed-in caller is
+-- always auth.uid(), whatever it passes. Either way the person must be an
+-- admin or manager of the answer's organization, and the correction is logged
+-- under their name, as from the dashboard.
+--
+-- The 3-argument function is dropped rather than overloaded: a call with
+-- three arguments would match both, and the dashboard's call keeps working
+-- through p_user_id's default.
+
+drop function if exists public.override_mention_sentiment(uuid, text, text);
+
+-- Returns jsonb { changed, previous, sentiment, override: { id, sentiment,
+-- previous_sentiment, note, user_name, created_at } }. Raises:
+-- 42501 the person isn't an admin or manager of the answer's organization
+-- P0002 no such answer
+-- 22023 not a sentiment, or an answer that doesn't name the brand
+create or replace function public.override_mention_sentiment(
+ p_result_id uuid,
+ p_sentiment text,
+ p_note text default null,
+ p_user_id uuid default null
+)
+returns jsonb
+language plpgsql
+security definer
+set search_path to 'public'
+as $$
+declare
+ v_row record;
+ v_user record;
+ v_day date;
+ v_note text := nullif(btrim(coalesce(p_note, '')), '');
+ v_override public.sentiment_overrides;
+ -- Who corrects: the API key's owner for the service role, else the caller.
+ v_person uuid := case when auth.role() = 'service_role' then p_user_id else auth.uid() end;
+begin
+ if p_sentiment is null or p_sentiment not in ('positive', 'neutral', 'negative') then
+ raise exception 'Invalid sentiment' using errcode = '22023';
+ end if;
+ if v_note is not null and char_length(v_note) > 500 then
+ raise exception 'The note is longer than 500 characters' using errcode = '22023';
+ end if;
+
+ select pr.id, pr.brand_id, pr.sentiment, pr.mention_count, pr.created_at, b.organization_id
+ into v_row
+ from public.prompt_results pr
+ join public.brands b on b.id = pr.brand_id
+ where pr.id = p_result_id
+ for update of pr;
+ if not found then
+ raise exception 'Answer not found' using errcode = 'P0002';
+ end if;
+
+ select p.id, p.full_name, p.role
+ into v_user
+ from public.profiles p
+ where p.id = v_person
+ and p.organization_id = v_row.organization_id
+ and p.role = any (array['admin', 'manager']::public.user_role[]);
+ if not found then
+ raise exception 'Only admins and managers can correct a sentiment' using errcode = '42501';
+ end if;
+
+ -- Sentiment is only classified for answers that name the brand.
+ if coalesce(v_row.mention_count, 0) <= 0 then
+ raise exception 'This answer does not name the brand' using errcode = '22023';
+ end if;
+
+ if v_row.sentiment = p_sentiment then
+ return jsonb_build_object('changed', false, 'previous', v_row.sentiment,
+ 'sentiment', p_sentiment, 'override', null);
+ end if;
+
+ update public.prompt_results
+ set sentiment = p_sentiment,
+ visibility_score = greatest(0, least(100,
+ coalesce(visibility_score, 0)
+ - public.sentiment_visibility_bonus(v_row.sentiment)
+ + public.sentiment_visibility_bonus(p_sentiment)))
+ where id = p_result_id;
+
+ insert into public.sentiment_overrides
+ (result_id, brand_id, previous_sentiment, sentiment, note, user_id, user_name)
+ values
+ (p_result_id, v_row.brand_id, coalesce(v_row.sentiment, 'neutral'), p_sentiment, v_note,
+ v_user.id, v_user.full_name)
+ returning * into v_override;
+
+ -- The answer's day in the rollups, now rather than at the nightly sweep.
+ v_day := (v_row.created_at at time zone 'utc')::date;
+ perform public.refresh_insights_daily(v_row.brand_id, v_day, v_day);
+ perform public.refresh_mentions_daily(v_row.brand_id, v_day, v_day);
+
+ return jsonb_build_object(
+ 'changed', true,
+ 'previous', v_override.previous_sentiment,
+ 'sentiment', v_override.sentiment,
+ 'override', jsonb_build_object(
+ 'id', v_override.id,
+ 'sentiment', v_override.sentiment,
+ 'previous_sentiment', v_override.previous_sentiment,
+ 'note', v_override.note,
+ 'user_name', v_override.user_name,
+ 'created_at', v_override.created_at));
+end;
+$$;
+
+revoke execute on function public.override_mention_sentiment(uuid, text, text, uuid)
+ from public, anon;
+grant execute on function public.override_mention_sentiment(uuid, text, text, uuid)
+ to authenticated, service_role;
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00224_results_autovacuum.sql
-- ─────────────────────────────────────────────────────────────────────────
diff --git a/web/src/app/api/mcp/mentions/[id]/route.ts b/web/src/app/api/mcp/mentions/[id]/route.ts
new file mode 100644
index 000000000..c88564881
--- /dev/null
+++ b/web/src/app/api/mcp/mentions/[id]/route.ts
@@ -0,0 +1,25 @@
+import { NextResponse } from 'next/server';
+import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { getMentionFor } from '@/lib/mcp/mentions';
+
+/** GET /api/mcp/mentions/[id] — REST mirror of the `get_mention` MCP tool. */
+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 mention = await getMentionFor(auth, id);
+ if (!mention) {
+ return NextResponse.json({ error: 'Answer not found' }, { status: 404 });
+ }
+ return NextResponse.json(mention);
+ } 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/mentions/[id]/sentiment-override/route.test.ts b/web/src/app/api/mcp/mentions/[id]/sentiment-override/route.test.ts
new file mode 100644
index 000000000..153b3e9c4
--- /dev/null
+++ b/web/src/app/api/mcp/mentions/[id]/sentiment-override/route.test.ts
@@ -0,0 +1,78 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * POST /api/mcp/mentions/{id}/sentiment-override (MS-13): the body is
+ * checked here, and the database's refusals come back as HTTP statuses.
+ */
+
+const { overrideMentionSentimentFor } = vi.hoisted(() => ({
+ overrideMentionSentimentFor: vi.fn(),
+}));
+vi.mock('@/lib/mcp-auth', () => ({
+ authenticateMcpRequest: vi.fn(async () => ({
+ userId: 'user-1',
+ email: null,
+ organizationId: 'org-1',
+ apiKeyId: 'key-1',
+ })),
+}));
+// The real filters and checks; only the database read is replaced.
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));
+vi.mock('@/lib/mcp/mentions', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/lib/mcp/mentions')>()),
+ overrideMentionSentimentFor,
+}));
+
+const { POST } = await import('./route');
+
+const post = (body: unknown) =>
+ POST(
+ new Request('http://localhost/api/mcp/mentions/r1/sentiment-override', {
+ method: 'POST',
+ body: typeof body === 'string' ? body : JSON.stringify(body),
+ }),
+ { params: Promise.resolve({ id: 'r1' }) },
+ );
+
+beforeEach(() => overrideMentionSentimentFor.mockReset());
+
+describe('POST /api/mcp/mentions/{id}/sentiment-override', () => {
+ it("corrects the answer as the key's owner", async () => {
+ overrideMentionSentimentFor.mockResolvedValue({
+ changed: true,
+ previous: 'negative',
+ sentiment: 'neutral',
+ override: null,
+ });
+ const res = await post({ sentiment: 'neutral', note: 'Comparison' });
+ expect(res.status).toBe(200);
+ expect(overrideMentionSentimentFor).toHaveBeenCalledWith(
+ expect.objectContaining({ userId: 'user-1' }),
+ 'r1',
+ 'neutral',
+ 'Comparison',
+ );
+ expect(await res.json()).toMatchObject({ changed: true, sentiment: 'neutral' });
+ });
+
+ it('refuses a body without a sentiment, or with a note that is not text', async () => {
+ expect((await post('not json')).status).toBe(400);
+ expect((await post({ sentiment: 'great' })).status).toBe(400);
+ expect((await post({ sentiment: 'neutral', note: 5 })).status).toBe(400);
+ expect(overrideMentionSentimentFor).not.toHaveBeenCalled();
+ });
+
+ it("returns the database's refusals as 403, 400 and 404", async () => {
+ for (const [error, status] of [
+ ['forbidden', 403],
+ ['invalid', 400],
+ ['missing', 404],
+ ] as const) {
+ overrideMentionSentimentFor.mockResolvedValueOnce({ error, message: `${error}!` });
+ const res = await post({ sentiment: 'neutral' });
+ expect(res.status).toBe(status);
+ expect(await res.json()).toEqual({ error: `${error}!` });
+ }
+ });
+});
diff --git a/web/src/app/api/mcp/mentions/[id]/sentiment-override/route.ts b/web/src/app/api/mcp/mentions/[id]/sentiment-override/route.ts
new file mode 100644
index 000000000..cd9febb58
--- /dev/null
+++ b/web/src/app/api/mcp/mentions/[id]/sentiment-override/route.ts
@@ -0,0 +1,50 @@
+import { NextResponse } from 'next/server';
+import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { isMentionSentiment, overrideMentionSentimentFor } from '@/lib/mcp/mentions';
+
+const STATUS = { forbidden: 403, invalid: 400, missing: 404 } as const;
+
+/**
+ * POST /api/mcp/mentions/[id]/sentiment-override
+ *
+ * REST mirror of the `override_mention_sentiment` MCP tool ("Sentiment is
+ * wrong"). Body: `{ "sentiment": "positive" | "neutral" | "negative",
+ * "note"?: string }`. The API key's owner must be an admin or manager of the
+ * brand's organization.
+ */
+export async function POST(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 });
+ }
+
+ let body: { sentiment?: unknown; note?: unknown };
+ try {
+ body = (await req.json()) as { sentiment?: unknown; note?: unknown };
+ } catch {
+ return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
+ }
+ if (!isMentionSentiment(body.sentiment)) {
+ return NextResponse.json(
+ { error: 'sentiment is required and must be one of: positive, neutral, negative' },
+ { status: 400 },
+ );
+ }
+ if (body.note !== undefined && typeof body.note !== 'string') {
+ return NextResponse.json({ error: 'note must be a string' }, { status: 400 });
+ }
+
+ try {
+ const result = await overrideMentionSentimentFor(auth, id, body.sentiment, body.note);
+ if ('error' in result) {
+ return NextResponse.json({ error: result.message }, { status: STATUS[result.error] });
+ }
+ 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/app/api/mcp/mentions/competitors/route.ts b/web/src/app/api/mcp/mentions/competitors/route.ts
new file mode 100644
index 000000000..435ec0521
--- /dev/null
+++ b/web/src/app/api/mcp/mentions/competitors/route.ts
@@ -0,0 +1,28 @@
+import { NextResponse } from 'next/server';
+import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { getMentionCompetitorsFor, mentionsFiltersFromUrl } from '@/lib/mcp/mentions';
+
+/**
+ * GET /api/mcp/mentions/competitors — REST mirror of the
+ * `get_mention_competitors` MCP tool, with the summary's filters.
+ */
+export async function GET(req: Request) {
+ const auth = await authenticateMcpRequest(req);
+ if (auth instanceof NextResponse) return auth;
+
+ const filters = mentionsFiltersFromUrl(new URL(req.url));
+ if (!filters) {
+ return NextResponse.json({ error: 'brand_id is required' }, { status: 400 });
+ }
+
+ try {
+ const competitors = await getMentionCompetitorsFor(auth, filters);
+ if (!competitors) {
+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });
+ }
+ return NextResponse.json(competitors);
+ } 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/mentions/perception/route.ts b/web/src/app/api/mcp/mentions/perception/route.ts
new file mode 100644
index 000000000..e99f99075
--- /dev/null
+++ b/web/src/app/api/mcp/mentions/perception/route.ts
@@ -0,0 +1,28 @@
+import { NextResponse } from 'next/server';
+import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { getMentionsPerceptionFor, mentionsFiltersFromUrl } from '@/lib/mcp/mentions';
+
+/**
+ * GET /api/mcp/mentions/perception — REST mirror of the
+ * `get_mentions_perception` MCP tool, with the summary's filters.
+ */
+export async function GET(req: Request) {
+ const auth = await authenticateMcpRequest(req);
+ if (auth instanceof NextResponse) return auth;
+
+ const filters = mentionsFiltersFromUrl(new URL(req.url));
+ if (!filters) {
+ return NextResponse.json({ error: 'brand_id is required' }, { status: 400 });
+ }
+
+ try {
+ const perception = await getMentionsPerceptionFor(auth, filters);
+ if (!perception) {
+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });
+ }
+ return NextResponse.json(perception);
+ } 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/mentions/route.test.ts b/web/src/app/api/mcp/mentions/route.test.ts
new file mode 100644
index 000000000..356c11642
--- /dev/null
+++ b/web/src/app/api/mcp/mentions/route.test.ts
@@ -0,0 +1,69 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/** GET /api/mcp/mentions (MS-13): the page's filters and the table's, from the query string. */
+
+const { listMentionsFor } = vi.hoisted(() => ({ listMentionsFor: vi.fn() }));
+vi.mock('@/lib/mcp-auth', () => ({
+ authenticateMcpRequest: vi.fn(async () => ({
+ userId: 'user-1',
+ email: null,
+ organizationId: 'org-1',
+ apiKeyId: 'key-1',
+ })),
+}));
+// The real filters and checks; only the database read is replaced.
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));
+vi.mock('@/lib/mcp/mentions', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/lib/mcp/mentions')>()),
+ listMentionsFor,
+}));
+
+const { GET } = await import('./route');
+
+const get = (query: string) => GET(new Request(`http://localhost/api/mcp/mentions${query}`));
+
+beforeEach(() => listMentionsFor.mockReset());
+
+describe('GET /api/mcp/mentions', () => {
+ it('reads the filters, and leaves out a sentiment or sort it does not know', async () => {
+ listMentionsFor.mockResolvedValue({
+ total: 0,
+ prompts: 0,
+ page: 2,
+ pageSize: 100,
+ mentions: [],
+ });
+ const res = await get(
+ '?brand_id=b1&date_from=2026-10-01&region=DE&topic_id=t1&search=beans' +
+ '&sentiment=negative&competitor_id=none&sort=oldest&page=2',
+ );
+ expect(res.status).toBe(200);
+ expect(listMentionsFor.mock.calls[0][1]).toEqual({
+ brandId: 'b1',
+ dateFrom: '2026-10-01',
+ dateTo: undefined,
+ platform: undefined,
+ region: 'DE',
+ topicId: 't1',
+ search: 'beans',
+ sentiment: 'negative',
+ competitorId: 'none',
+ sort: 'oldest',
+ page: 2,
+ });
+
+ await get('?brand_id=b1&sentiment=great&sort=best&page=x');
+ expect(listMentionsFor.mock.calls[1][1]).toMatchObject({
+ sentiment: undefined,
+ sort: undefined,
+ page: undefined,
+ });
+ });
+
+ it("needs a brand, and says when the brand is not the key's", async () => {
+ expect((await get('')).status).toBe(400);
+ listMentionsFor.mockResolvedValue(null);
+ expect((await get('?brand_id=b9')).status).toBe(404);
+ });
+});
diff --git a/web/src/app/api/mcp/mentions/route.ts b/web/src/app/api/mcp/mentions/route.ts
new file mode 100644
index 000000000..72f77764c
--- /dev/null
+++ b/web/src/app/api/mcp/mentions/route.ts
@@ -0,0 +1,45 @@
+import { NextResponse } from 'next/server';
+import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import {
+ isMentionSentiment,
+ isMentionSort,
+ listMentionsFor,
+ mentionsFiltersFromUrl,
+} from '@/lib/mcp/mentions';
+
+/**
+ * GET /api/mcp/mentions — REST mirror of the `list_mentions` MCP tool: the
+ * summary's filters plus sentiment, competitor_id (`none` for responses
+ * naming no competitor), sort (newest | oldest | co_mentions | negative) and
+ * page (100 rows a page).
+ */
+export async function GET(req: Request) {
+ const auth = await authenticateMcpRequest(req);
+ if (auth instanceof NextResponse) return auth;
+
+ const url = new URL(req.url);
+ const filters = mentionsFiltersFromUrl(url);
+ if (!filters) {
+ return NextResponse.json({ error: 'brand_id is required' }, { status: 400 });
+ }
+ const sentiment = url.searchParams.get('sentiment');
+ const sort = url.searchParams.get('sort');
+ const page = Number.parseInt(url.searchParams.get('page') ?? '', 10);
+
+ try {
+ const list = await listMentionsFor(auth, {
+ ...filters,
+ sentiment: isMentionSentiment(sentiment) ? sentiment : undefined,
+ competitorId: url.searchParams.get('competitor_id') ?? undefined,
+ sort: isMentionSort(sort) ? sort : undefined,
+ page: Number.isFinite(page) ? page : undefined,
+ });
+ if (!list) {
+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });
+ }
+ return NextResponse.json(list);
+ } 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/mentions/summary/route.ts b/web/src/app/api/mcp/mentions/summary/route.ts
new file mode 100644
index 000000000..34bca56cc
--- /dev/null
+++ b/web/src/app/api/mcp/mentions/summary/route.ts
@@ -0,0 +1,29 @@
+import { NextResponse } from 'next/server';
+import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { getMentionsSummaryFor, mentionsFiltersFromUrl } from '@/lib/mcp/mentions';
+
+/**
+ * GET /api/mcp/mentions/summary — REST mirror of the `get_mentions_summary`
+ * MCP tool. Filters: brand_id (required), date_from, date_to, platform,
+ * region, topic_id, search; 30 days when date_from is left out.
+ */
+export async function GET(req: Request) {
+ const auth = await authenticateMcpRequest(req);
+ if (auth instanceof NextResponse) return auth;
+
+ const filters = mentionsFiltersFromUrl(new URL(req.url));
+ if (!filters) {
+ return NextResponse.json({ error: 'brand_id is required' }, { status: 400 });
+ }
+
+ try {
+ const summary = await getMentionsSummaryFor(auth, filters);
+ if (!summary) {
+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });
+ }
+ return NextResponse.json(summary);
+ } catch (err) {
+ const message = err instanceof Error ? err.message : 'Failed';
+ return NextResponse.json({ error: message }, { status: 500 });
+ }
+}
diff --git a/web/src/lib/agent/system-prompt.test.ts b/web/src/lib/agent/system-prompt.test.ts
index 4f9232766..2587a648f 100644
--- a/web/src/lib/agent/system-prompt.test.ts
+++ b/web/src/lib/agent/system-prompt.test.ts
@@ -28,4 +28,19 @@ describe('buildAgentSystemPrompt', () => {
"If there is no default brand and the user doesn't name one, call list_brands.",
);
});
+
+ it('lists the Mentions & Sentiment tools and how to read net sentiment', () => {
+ const prompt = buildAgentSystemPrompt(now);
+
+ for (const name of [
+ 'get_mentions_summary',
+ 'list_mentions',
+ 'get_mention',
+ 'get_mention_competitors',
+ 'get_mentions_perception',
+ ]) {
+ expect(prompt).toContain(`- **${name}** —`);
+ }
+ expect(prompt).toContain('Under 20 mentions a figure is a low sample (`lowSample: true`)');
+ });
});
diff --git a/web/src/lib/agent/system-prompt.ts b/web/src/lib/agent/system-prompt.ts
index 516d1af92..31780102c 100644
--- a/web/src/lib/agent/system-prompt.ts
+++ b/web/src/lib/agent/system-prompt.ts
@@ -47,6 +47,11 @@ You have these tools, all scoped to the authenticated user's organization:
- **list_topics** — topics on a brand with prompt count each. Use for coverage audits.
- **list_prompts** — prompts being tracked for a brand. Use when the user asks what is being tracked or wants to drill into a specific topic.
- **get_prompt_performance** — aggregates performance (average visibility, total mentions, citations, appearances, and competitor score) grouped by prompt over a date range. Use to answer questions like "what is the best-performing prompt today?" or "which prompts dropped this week?".
+- **get_mentions_summary** — the Mentions & Sentiment overview: mentions, mention rate, prompts with mentions, average position and sentiment (net −100…+100), now vs the window before, per platform and per day, and the platform that moved net sentiment most. Use for "how is AI talking about us?" and "why did sentiment drop on Gemini?".
+- **list_mentions** — the responses naming the brand with sentiment, position, competitors in the same response and an excerpt; filter by sentiment or competitor. Use to quote what AI actually said.
+- **get_mention** — one response in full (text, citations, competitors named, latest sentiment correction), by an id from list_mentions.
+- **get_mention_competitors** — how often AI names each competitor in the brand's responses, and how often beside the brand.
+- **get_mentions_perception** — the terms AI uses next to the brand, the attributes that set it apart from competitors, and the biggest gap.
- **list_content_opportunities** — content gaps for a brand sorted by opportunity score. Use for "what should I write?" questions.
- **run_site_audit** — run a Site Audit (AEO/GEO page score + AI fix recommendations) for a URL under a brand. Returns immediately with status "running"; poll get_site_audit for the result. **This is a write that spends one of the org's monthly Site Audit credits** — only run it when the user explicitly asks to audit a page.
- **get_site_audit** — read a Site Audit's result (status, total + per-category scores, signals, AI fix recommendations) by id. No credit consumed.
@@ -94,6 +99,7 @@ Hard rules:
- **Visibility score** is 0–100 per result, averaged across results in the window. Below 30 = essentially invisible; 30–60 = present but not dominant; 60+ = strong presence.
- **Share of voice** is the brand's share of mentions among (brand + tracked competitors) in AI responses. SoV moves more slowly than visibility — a 5-point shift week-over-week is significant.
+- **Net sentiment** is the positive minus the negative share of the responses naming the brand, −100…+100; neutral counts in the total. Under 20 mentions a figure is a low sample (\`lowSample: true\`): say so and don't read a change into it. Sentiment is measured for the brand only, not competitors.
- **Citations** are URLs AI engines explicitly link to. Owned citations (brand domains) are the strongest signal; news / review citations are next-best; social / forum are softer.
Start by greeting briefly only on the first message in a conversation; on follow-ups, get straight to the answer.`;
diff --git a/web/src/lib/agent/tools.ts b/web/src/lib/agent/tools.ts
index d939e2054..0b98f7357 100644
--- a/web/src/lib/agent/tools.ts
+++ b/web/src/lib/agent/tools.ts
@@ -16,6 +16,35 @@ import {
getSiteAuditFor,
listSiteAuditsFor,
} from '@/lib/mcp/data';
+import {
+ getMentionCompetitorsFor,
+ getMentionFor,
+ getMentionsPerceptionFor,
+ getMentionsSummaryFor,
+ listMentionsFor,
+} from '@/lib/mcp/mentions';
+import { MENTION_SENTIMENTS, MENTION_SORTS } from '@/lib/mentions-list';
+
+/** The Mentions & Sentiment page's filters, the same on every mentions tool. */
+const mentionFilters = {
+ brand_id: z.string().uuid(),
+ date_from: z.string().optional(),
+ date_to: z.string().optional(),
+ platform: z.string().optional(),
+ region: z.string().optional(),
+ topic_id: z.string().uuid().optional(),
+ search: z.string().optional(),
+};
+
+const mentionParams = (args: z.infer<z.ZodObject<typeof mentionFilters>>) => ({
+ brandId: args.brand_id,
+ dateFrom: args.date_from,
+ dateTo: args.date_to,
+ platform: args.platform,
+ region: args.region,
+ topicId: args.topic_id,
+ search: args.search,
+});
/**
* Vercel AI SDK tool definitions for the in-product agent. Each tool is a
@@ -208,6 +237,54 @@ export function buildAgentTools(auth: McpAuthContext) {
}),
}),
+ get_mentions_summary: tool({
+ description:
+ 'Mentions & Sentiment overview for a brand: times named (timesNamed, the page\'s Total mentions), responses naming it, mention rate, prompts with mentions, average position and sentiment (counts, shares, net −100…+100), now and in the window before, with changes taken on the prompts both windows answered (changes.basis), as the page\'s cards; the platform that moved net sentiment most; each platform; each day. Use for "how is AI talking about us?" / "why did sentiment drop on Gemini?". Platform ids look like "chatgpt-web", "gemini-web". 30 days when date_from is left out.',
+ inputSchema: z.object(mentionFilters),
+ execute: async (args) => getMentionsSummaryFor(auth, mentionParams(args)),
+ }),
+
+ list_mentions: tool({
+ description:
+ 'The responses naming the brand, 100 a page: prompt, platform, country, sentiment, position, competitors in the same response and an excerpt. Filter by sentiment or competitor_id ("none" for responses naming no competitor); sort newest, oldest, co_mentions or negative. Use to quote what AI actually said.',
+ inputSchema: z.object({
+ ...mentionFilters,
+ sentiment: z.enum(MENTION_SENTIMENTS).optional(),
+ competitor_id: z.string().optional(),
+ sort: z.enum(MENTION_SORTS).optional(),
+ page: z.number().int().min(1).optional(),
+ }),
+ execute: async (args) =>
+ listMentionsFor(auth, {
+ ...mentionParams(args),
+ sentiment: args.sentiment,
+ competitorId: args.competitor_id,
+ sort: args.sort,
+ page: args.page,
+ }),
+ }),
+
+ get_mention: tool({
+ description:
+ 'One response in full, by the id list_mentions returns: the stored text, citations, competitors it names, sentiment and its latest correction.',
+ inputSchema: z.object({ id: z.string().uuid() }),
+ execute: async (args) => getMentionFor(auth, args.id),
+ }),
+
+ get_mention_competitors: tool({
+ description:
+ "How often AI names each competitor in the brand's tracked responses (count, share, change against the window before) and how often in the same response as the brand.",
+ inputSchema: z.object(mentionFilters),
+ execute: async (args) => getMentionCompetitorsFor(auth, mentionParams(args)),
+ }),
+
+ get_mentions_perception: tool({
+ description:
+ 'What AI associates with the brand: the terms next to it (with share of the responses naming it, now and before), the attributes that set it apart from its top competitors, co-mentions, and the biggest gap (an attribute a competitor leads by 20+ points). Found by rule, no LLM.',
+ inputSchema: z.object(mentionFilters),
+ execute: async (args) => getMentionsPerceptionFor(auth, mentionParams(args)),
+ }),
+
run_site_audit: tool({
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 (shared with the dashboard) and runs asynchronously (~30s). It returns the new audit id with status "running" — then call get_site_audit with that id until status is "completed" (or "failed") to read the result. Only run on explicit user intent to audit a specific URL; never audit unprompted.',
diff --git a/web/src/lib/mcp/mentions.test.ts b/web/src/lib/mcp/mentions.test.ts
new file mode 100644
index 000000000..3af98d9c2
--- /dev/null
+++ b/web/src/lib/mcp/mentions.test.ts
@@ -0,0 +1,610 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { McpAuthContext } from '@/lib/mcp-auth';
+
+/**
+ * The Mentions & Sentiment API/MCP reads (MS-13): each checks the brand is the
+ * key's organization's before calling the page's database functions as the
+ * service role, and returns the page's figures; the correction goes through
+ * override_mention_sentiment for the key's owner (00223).
+ */
+
+type Result = { data: unknown; error: { code?: string; message: string } | null };
+
+let tables: Record<string, Result> = {};
+const filters: unknown[][] = [];
+const rpc = vi.fn<(fn: string, args: Record<string, unknown>) => Promise<Result>>();
+
+function builder(table: string) {
+ const chain = {
+ select: () => chain,
+ eq: (...args: unknown[]) => (filters.push([table, ...args]), chain),
+ order: () => chain,
+ limit: () => chain,
+ in: (...args: unknown[]) => (filters.push([table, 'in', ...args]), chain),
+ maybeSingle: async () => tables[table] ?? { data: null, error: null },
+ then: (resolve: (v: Result) => void) => resolve(tables[table] ?? { data: [], error: null }),
+ };
+ return chain;
+}
+
+vi.mock('@/lib/supabase/admin', () => ({
+ supabaseAdmin: {
+ from: (table: string) => builder(table),
+ rpc: (fn: string, args: Record<string, unknown>) => rpc(fn, args),
+ },
+}));
+
+const {
+ getMentionCompetitorsFor,
+ getMentionFor,
+ getMentionsPerceptionFor,
+ getMentionsSummaryFor,
+ listMentionsFor,
+ mentionsFiltersFromUrl,
+ overrideMentionSentimentFor,
+} = await import('./mentions');
+
+const auth: McpAuthContext = {
+ userId: 'user-1',
+ email: null,
+ organizationId: 'org-1',
+ apiKeyId: 'key-1',
+};
+
+const brand = {
+ data: { id: 'b1', name: 'Acme Coffee', brand_domains: [{ domain: 'acme.com' }] },
+ error: null,
+};
+
+const totals = (over: Record<string, number>) => ({
+ answers: 0,
+ mentions: 0,
+ occurrences: 0,
+ positive: 0,
+ negative: 0,
+ position_sum: 0,
+ position_count: 0,
+ prompts: 0,
+ prompts_with_mentions: 0,
+ ...over,
+});
+
+const overview = {
+ window: {
+ from: '2026-09-17T09:00:00Z',
+ to: '2026-10-17T09:00:00Z',
+ days: 30,
+ source: 'days',
+ day_from: '2026-10-16',
+ day_to: '2026-10-17',
+ },
+ current: totals({
+ answers: 400,
+ mentions: 100,
+ occurrences: 130,
+ positive: 48,
+ negative: 14,
+ position_sum: 150,
+ position_count: 100,
+ prompts: 20,
+ prompts_with_mentions: 15,
+ }),
+ previous: totals({
+ answers: 400,
+ mentions: 80,
+ occurrences: 104,
+ positive: 40,
+ negative: 8,
+ prompts: 20,
+ prompts_with_mentions: 12,
+ }),
+ platforms: [
+ {
+ platform: 'gemini-web',
+ answers: 100,
+ mentions: 50,
+ positive: 15,
+ negative: 18,
+ prev_answers: 100,
+ prev_mentions: 50,
+ prev_positive: 16,
+ prev_negative: 10,
+ },
+ ],
+ daily: [
+ { day: '2026-10-17', answers: 10, mentions: 4, occurrences: 6, positive: 2, negative: 1 },
+ ],
+ competitors: [
+ { competitor_id: 'c2', name: 'Origin Box', mentions: 90, co_mentions: 36, prev_mentions: 0 },
+ { competitor_id: 'c1', name: 'Crema Club', mentions: 260, co_mentions: 41, prev_mentions: 200 },
+ ],
+};
+
+beforeEach(() => {
+ tables = { brands: brand };
+ filters.length = 0;
+ rpc.mockReset();
+ rpc.mockResolvedValue({ data: null, error: null });
+});
+
+describe('mentionsFiltersFromUrl', () => {
+ it('reads the page filters from the query string, and needs a brand', () => {
+ expect(
+ mentionsFiltersFromUrl(
+ new URL('http://x/api/mcp/mentions/summary?brand_id=b1&platform=gemini-web&search=beans'),
+ ),
+ ).toEqual({
+ brandId: 'b1',
+ dateFrom: undefined,
+ dateTo: undefined,
+ platform: 'gemini-web',
+ region: undefined,
+ topicId: undefined,
+ search: 'beans',
+ });
+ expect(mentionsFiltersFromUrl(new URL('http://x/api/mcp/mentions/summary'))).toBeNull();
+ });
+});
+
+describe('getMentionsSummaryFor', () => {
+ it("reads the Overview for the key's brand, 30 days back by default", async () => {
+ rpc.mockResolvedValue({ data: overview, error: null });
+ const before = Date.now();
+ const summary = await getMentionsSummaryFor(auth, {
+ brandId: 'b1',
+ dateTo: '2026-10-17',
+ platform: 'gemini-web',
+ });
+
+ expect(filters).toContainEqual(['brands', 'organization_id', 'org-1']);
+ const [fn, args] = rpc.mock.calls[0];
+ expect(fn).toBe('mentions_overview');
+ expect(args).toMatchObject({
+ p_brand_id: 'b1',
+ p_date_to: '2026-10-17T23:59:59.999Z',
+ p_platform: 'gemini-web',
+ });
+ const from = Date.parse(String(args.p_date_from));
+ expect(before - from).toBeGreaterThanOrEqual(30 * 86_400_000 - 1000);
+ expect(before - from).toBeLessThan(30 * 86_400_000 + 1000);
+
+ expect(summary?.brand).toEqual({ id: 'b1', name: 'Acme Coffee' });
+ expect(summary?.current).toEqual({
+ trackedResponses: 400,
+ mentions: 100,
+ mentionRate: 25,
+ timesNamed: 130,
+ trackedPrompts: 20,
+ promptsWithMentions: 15,
+ averagePosition: 1.5,
+ sentiment: {
+ positive: 48,
+ neutral: 38,
+ negative: 14,
+ positivePct: 48,
+ neutralPct: 38,
+ negativePct: 14,
+ net: 34,
+ lowSample: false,
+ },
+ });
+ // Without the shared prompts (before 00195), the windows' totals.
+ expect(summary?.changes).toEqual({
+ mentionsPct: 25,
+ mentionRatePoints: 5,
+ promptsWithMentionsPct: 25,
+ netSentimentPoints: -6,
+ basis: null,
+ });
+ expect(summary?.headline).toEqual({
+ mover: { platform: 'gemini-web', label: 'Gemini', change: -18 },
+ companions: ['Crema Club', 'Origin Box'],
+ });
+ expect(summary?.platforms[0]).toMatchObject({
+ label: 'Gemini',
+ mentionRate: 50,
+ netSentiment: -6,
+ netSentimentChange: -18,
+ lowSample: false,
+ });
+ expect(summary?.daily).toEqual([
+ {
+ day: '2026-10-16',
+ trackedResponses: 0,
+ mentions: 0,
+ timesNamed: 0,
+ mentionRate: null,
+ netSentiment: null,
+ },
+ {
+ day: '2026-10-17',
+ trackedResponses: 10,
+ mentions: 4,
+ timesNamed: 6,
+ mentionRate: 40,
+ netSentiment: 25,
+ },
+ ]);
+ });
+
+ it("reads nothing for a brand outside the key's organization", async () => {
+ tables = { brands: { data: null, error: null } };
+ await expect(getMentionsSummaryFor(auth, { brandId: 'b9' })).resolves.toBeNull();
+ expect(rpc).not.toHaveBeenCalled();
+ await expect(
+ getMentionsSummaryFor({ ...auth, organizationId: null }, { brandId: 'b1' }),
+ ).resolves.toBeNull();
+ });
+
+ it('marks a low sample and reads no change into it', async () => {
+ rpc.mockResolvedValue({
+ data: {
+ ...overview,
+ current: totals({ answers: 12, mentions: 3, occurrences: 4, positive: 2 }),
+ previous: totals({
+ answers: 400,
+ mentions: 80,
+ occurrences: 100,
+ positive: 40,
+ negative: 8,
+ }),
+ },
+ error: null,
+ });
+ const summary = await getMentionsSummaryFor(auth, { brandId: 'b1' });
+ expect(summary?.current.sentiment).toMatchObject({ net: 67, lowSample: true });
+ expect(summary?.changes).toEqual({
+ mentionsPct: -96,
+ mentionRatePoints: null,
+ promptsWithMentionsPct: null,
+ netSentimentPoints: null,
+ basis: null,
+ });
+ });
+ it("reads no rate change from a window before under 20 responses, as the page's card", async () => {
+ rpc.mockResolvedValue({
+ data: { ...overview, previous: totals({ answers: 10, mentions: 1 }) },
+ error: null,
+ });
+ const summary = await getMentionsSummaryFor(auth, { brandId: 'b1' });
+ expect(summary?.changes.mentionRatePoints).toBeNull();
+ expect(summary?.changes.netSentimentPoints).toBeNull();
+ });
+
+ // 00195: as the page's cards, each change on the prompts both windows
+ // answered; the figures stay the whole windows'.
+ it('takes every change on the prompts both windows answered, and says which', async () => {
+ rpc.mockResolvedValue({
+ data: {
+ ...overview,
+ same: {
+ prompts: 18,
+ new_prompts: 2,
+ dropped_prompts: 1,
+ current: totals({
+ answers: 360,
+ mentions: 90,
+ occurrences: 120,
+ positive: 45,
+ negative: 9,
+ prompts_with_mentions: 14,
+ }),
+ previous: totals({
+ answers: 360,
+ mentions: 72,
+ occurrences: 80,
+ positive: 36,
+ negative: 7,
+ prompts_with_mentions: 10,
+ }),
+ },
+ },
+ error: null,
+ });
+ const summary = await getMentionsSummaryFor(auth, { brandId: 'b1' });
+ expect(summary?.current.timesNamed).toBe(130);
+ expect(summary?.changes).toEqual({
+ // 120 against 80 times named, on the shared prompts.
+ mentionsPct: 50,
+ // 25% against 20% of the shared prompts' responses.
+ mentionRatePoints: 5,
+ promptsWithMentionsPct: 40,
+ // +40 against +40 on the shared prompts.
+ netSentimentPoints: 0,
+ basis: { sharedPrompts: 18, newPrompts: 2, droppedPrompts: 1 },
+ });
+ });
+});
+
+describe('getMentionCompetitorsFor', () => {
+ it('lists competitors by mentions, with their share and the same-response count', async () => {
+ rpc.mockResolvedValue({ data: overview, error: null });
+ const result = await getMentionCompetitorsFor(auth, { brandId: 'b1' });
+ expect(result?.brand).toEqual({
+ id: 'b1',
+ name: 'Acme Coffee',
+ mentions: 100,
+ shareOfResponses: 25,
+ });
+ expect(result?.competitors).toEqual([
+ {
+ competitorId: 'c1',
+ name: 'Crema Club',
+ mentions: 260,
+ shareOfResponses: 65,
+ sameResponseAsYou: 41,
+ previousMentions: 200,
+ mentionsChangePct: 30,
+ },
+ {
+ competitorId: 'c2',
+ name: 'Origin Box',
+ mentions: 90,
+ shareOfResponses: 22.5,
+ sameResponseAsYou: 36,
+ previousMentions: 0,
+ mentionsChangePct: null,
+ },
+ ]);
+ });
+});
+
+describe('listMentionsFor', () => {
+ it("reads the page asked for with the table's filters, each answer cut to its excerpt", async () => {
+ rpc.mockResolvedValue({
+ data: {
+ total: 214,
+ prompts: 12,
+ rows: [
+ {
+ id: 'r1',
+ created_at: '2026-10-16T11:28:06Z',
+ prompt_id: 'p1',
+ prompt_text: 'Best espresso beans?',
+ topic_name: 'Beans',
+ platform: 'gemini-web',
+ model_used: 'gemini-2.5-flash',
+ region: 'DE',
+ sentiment: 'negative',
+ mention_count: 2,
+ mention_position: 2,
+ mentioned_entity_count: 4,
+ co_mentioned: [{ competitor_id: 'c1', name: 'Crema Club', mention_position: 1 }],
+ response: 'Try **Crema Club** first. Acme Coffee is pricier.',
+ },
+ ],
+ },
+ error: null,
+ });
+ const list = await listMentionsFor(auth, {
+ brandId: 'b1',
+ sentiment: 'negative',
+ competitorId: 'none',
+ sort: 'co_mentions',
+ page: 3,
+ });
+ expect(rpc.mock.calls[0][0]).toBe('mentions_list');
+ expect(rpc.mock.calls[0][1]).toMatchObject({
+ p_sentiment: 'negative',
+ p_competitor_id: 'none',
+ p_sort: 'co_mentions',
+ p_limit: 100,
+ p_offset: 200,
+ });
+ expect(list).toEqual({
+ total: 214,
+ prompts: 12,
+ page: 3,
+ pageSize: 100,
+ mentions: [
+ {
+ id: 'r1',
+ createdAt: '2026-10-16T11:28:06Z',
+ prompt: 'Best espresso beans?',
+ promptId: 'p1',
+ topic: 'Beans',
+ platform: 'gemini-web',
+ platformLabel: 'Gemini',
+ model: 'gemini-2.5-flash',
+ region: 'DE',
+ sentiment: 'negative',
+ timesNamed: 2,
+ position: 2,
+ brandsNamed: 4,
+ coMentioned: ['Crema Club'],
+ excerpt: 'Try Crema Club first. Acme Coffee is pricier.',
+ },
+ ],
+ });
+ });
+
+ it('starts at the first page, newest first, and throws on a database error', async () => {
+ rpc.mockResolvedValueOnce({ data: { total: 0, prompts: 0, rows: [] }, error: null });
+ await listMentionsFor(auth, { brandId: 'b1', page: 0 });
+ expect(rpc.mock.calls[0][1]).toMatchObject({ p_sort: 'newest', p_offset: 0 });
+
+ rpc.mockResolvedValueOnce({
+ data: null,
+ error: { code: '57014', message: 'statement timeout' },
+ });
+ await expect(listMentionsFor(auth, { brandId: 'b1' })).rejects.toThrow('statement timeout');
+ });
+});
+
+describe('getMentionFor', () => {
+ const answer = {
+ id: 'r1',
+ brand_id: 'b1',
+ created_at: '2026-10-16T11:28:06Z',
+ platform: 'gemini-web',
+ model_used: 'gemini-2.5-flash',
+ region: 'DE',
+ sentiment: 'negative',
+ mention_count: 2,
+ mention_position: 2,
+ mentioned_entity_count: 3,
+ // Stored at tracking time: Crema Club has since been renamed; Origin Box wasn't named.
+ competitor_mentions: [
+ { competitor_id: 'c3', name: 'Sample Beans', mention_count: 2, mention_position: 3 },
+ { competitor_id: 'c1', name: 'Crema', mention_count: 1, mention_position: 1 },
+ { competitor_id: 'c2', name: 'Origin Box', mention_count: 0 },
+ ],
+ response: 'Try Crema Club first. Acme Coffee is pricier.',
+ citations: [{ url: 'https://acme.com/beans', title: 'Beans' }],
+ prompts: { text: 'Best espresso beans?' },
+ brands: { organization_id: 'org-1' },
+ };
+
+ it('returns the full response, the competitors it names and its latest correction', async () => {
+ tables = {
+ prompt_results: { data: answer, error: null },
+ competitors: { data: [{ id: 'c1', name: 'Crema Club' }], error: null },
+ sentiment_overrides: {
+ data: {
+ sentiment: 'neutral',
+ previous_sentiment: 'negative',
+ note: 'Comparison, not criticism',
+ user_name: 'Demo User',
+ created_at: '2026-10-17T10:00:00Z',
+ },
+ error: null,
+ },
+ };
+ const mention = await getMentionFor(auth, 'r1');
+ expect(filters).toContainEqual(['prompt_results', 'brands.organization_id', 'org-1']);
+ expect(filters).toContainEqual(['competitors', 'brand_id', 'b1']);
+ expect(filters).toContainEqual(['competitors', 'in', 'id', ['c3', 'c1']]);
+ expect(mention).toMatchObject({
+ id: 'r1',
+ prompt: 'Best espresso beans?',
+ platformLabel: 'Gemini',
+ sentiment: 'negative',
+ // As the Mentions table lists them: current names, in the answer's order.
+ competitorsNamed: ['Crema Club', 'Sample Beans'],
+ response: 'Try Crema Club first. Acme Coffee is pricier.',
+ citations: [{ url: 'https://acme.com/beans', title: 'Beans' }],
+ sentimentOverride: {
+ sentiment: 'neutral',
+ previousSentiment: 'negative',
+ note: 'Comparison, not criticism',
+ userName: 'Demo User',
+ },
+ });
+ expect(mention).not.toHaveProperty('brands');
+ });
+
+ it("is null for an answer outside the key's organization", async () => {
+ tables = { prompt_results: { data: null, error: null } };
+ await expect(getMentionFor(auth, 'r9')).resolves.toBeNull();
+ tables = {
+ prompt_results: { data: { ...answer, brands: { organization_id: 'org-2' } }, error: null },
+ };
+ await expect(getMentionFor(auth, 'r1')).resolves.toBeNull();
+ });
+});
+
+describe('getMentionsPerceptionFor', () => {
+ it("returns the terms with their share, each attribute's shares and the biggest gap", async () => {
+ rpc.mockResolvedValue({
+ data: {
+ window: { from: 'f', to: 't', days: 30 },
+ entities: [
+ { entity: 'brand', name: 'Acme Coffee', is_brand: true, mentions: 50, prev_mentions: 40 },
+ { entity: 'c1', name: 'Crema Club', is_brand: false, mentions: 80, prev_mentions: 60 },
+ ],
+ brand_terms: [{ term: 'fresh roast', answers: 20, prev_answers: 10 }],
+ attributes: [
+ {
+ term: 'enterprise',
+ values: [
+ { entity: 'brand', answers: 5 },
+ { entity: 'c1', answers: 48 },
+ ],
+ },
+ ],
+ co_mentions: [
+ { competitor_id: 'c1', name: 'Crema Club', co_mentions: 30, prev_co_mentions: 20 },
+ ],
+ },
+ error: null,
+ });
+ const perception = await getMentionsPerceptionFor(auth, { brandId: 'b1' });
+ expect(rpc.mock.calls[0][0]).toBe('mentions_perception');
+ expect(perception?.brandTerms).toEqual([
+ { term: 'fresh roast', responses: 20, sharePct: 40, previousResponses: 10 },
+ ]);
+ expect(perception?.attributes).toEqual([{ term: 'enterprise', sharePct: [10, 60] }]);
+ expect(perception?.coMentions).toEqual([
+ { competitorId: 'c1', name: 'Crema Club', responses: 30, previousResponses: 20 },
+ ]);
+ expect(perception?.biggestGap).toEqual({
+ term: 'enterprise',
+ competitor: 'Crema Club',
+ competitorShare: 60,
+ brandShare: 10,
+ brandRank: 2,
+ });
+ });
+});
+
+describe('overrideMentionSentimentFor', () => {
+ it("corrects as the key's owner once the answer is the organization's", async () => {
+ tables = { prompt_results: { data: { id: 'r1' }, error: null } };
+ rpc.mockResolvedValue({
+ data: {
+ changed: true,
+ previous: 'negative',
+ sentiment: 'neutral',
+ override: {
+ sentiment: 'neutral',
+ previous_sentiment: 'negative',
+ note: 'Comparison',
+ user_name: 'Demo User',
+ created_at: '2026-10-17T10:00:00Z',
+ },
+ },
+ error: null,
+ });
+ const result = await overrideMentionSentimentFor(auth, 'r1', 'neutral', ' Comparison ');
+ expect(rpc).toHaveBeenCalledWith('override_mention_sentiment', {
+ p_result_id: 'r1',
+ p_sentiment: 'neutral',
+ p_note: 'Comparison',
+ p_user_id: 'user-1',
+ });
+ expect(result).toMatchObject({
+ changed: true,
+ previous: 'negative',
+ sentiment: 'neutral',
+ override: { userName: 'Demo User', note: 'Comparison' },
+ });
+ });
+
+ it("reads another organization's answer as missing, and maps the database's refusals", async () => {
+ tables = { prompt_results: { data: null, error: null } };
+ await expect(overrideMentionSentimentFor(auth, 'r9', 'neutral')).resolves.toEqual({
+ error: 'missing',
+ message: 'Answer not found',
+ });
+ expect(rpc).not.toHaveBeenCalled();
+
+ tables = { prompt_results: { data: { id: 'r1' }, error: null } };
+ rpc.mockResolvedValueOnce({
+ data: null,
+ error: { code: '42501', message: 'Only admins and managers can correct a sentiment' },
+ });
+ await expect(overrideMentionSentimentFor(auth, 'r1', 'neutral')).resolves.toEqual({
+ error: 'forbidden',
+ message: 'Only admins and managers can correct a sentiment',
+ });
+ rpc.mockResolvedValueOnce({
+ data: null,
+ error: { code: '22023', message: 'This answer does not name the brand' },
+ });
+ await expect(overrideMentionSentimentFor(auth, 'r1', 'neutral')).resolves.toMatchObject({
+ error: 'invalid',
+ });
+ rpc.mockResolvedValueOnce({ data: null, error: { code: '57014', message: 'timeout' } });
+ await expect(overrideMentionSentimentFor(auth, 'r1', 'neutral')).rejects.toThrow('timeout');
+ });
+});
diff --git a/web/src/lib/mcp/mentions.ts b/web/src/lib/mcp/mentions.ts
new file mode 100644
index 000000000..50c247fb0
--- /dev/null
+++ b/web/src/lib/mcp/mentions.ts
@@ -0,0 +1,717 @@
+import { supabaseAdmin } from '@/lib/supabase/admin';
+import type { McpAuthContext } from '@/lib/mcp-auth';
+import { expandDateToEndOfDay } from '@/lib/dates';
+import { mentionExcerpt } from '@/lib/mention-match';
+import {
+ mentionPlatformLabel,
+ mentionsHeadline,
+ platformNetChange,
+ wholeNet,
+} from '@/lib/mentions-headline';
+import {
+ MENTION_SENTIMENTS,
+ MENTION_SORTS,
+ MENTIONS_PAGE_SIZE,
+ parseMentionsList,
+ parseSentimentOverride,
+ type MentionRow,
+ type MentionSentiment,
+ type MentionSort,
+ type SentimentOverride,
+} from '@/lib/mentions-list';
+import {
+ averagePosition,
+ changeBasis,
+ isLowSample,
+ LOW_SAMPLE_MENTIONS,
+ mentionRate,
+ mentionTrend,
+ parseMentionsOverview,
+ relativeChange,
+ sentimentSplit,
+ type MentionTotals,
+ type MentionsOverview,
+} from '@/lib/mentions-overview';
+import {
+ attributeShares,
+ biggestGap,
+ parseMentionsPerception,
+ shareOf,
+ type PerceptionGap,
+} from '@/lib/mentions-perception';
+import type { Citation } from '@/types';
+
+/**
+ * Mentions & Sentiment over the API and MCP (MS-13): the page's figures for a
+ * brand, under the filters the page takes (window, platform, country, topic,
+ * prompt search), for AI Agent Chat and other clients to answer "why did
+ * sentiment drop on Gemini?". Each function checks the brand is the API key's
+ * organization's, then reads through the page's own database functions as the
+ * service role (00157, 00158 and 00161 let it through), so the numbers are
+ * the dashboard's. No LLM is called.
+ */
+
+/** The page opens on 30 days, and so does a read without date_from. */
+export const MENTIONS_DEFAULT_DAYS = 30;
+
+export interface MentionsFilterParams {
+ brandId: string;
+ /** ISO timestamps; a date_to of `YYYY-MM-DD` covers that whole day. */
+ dateFrom?: string;
+ dateTo?: string;
+ /** A prompt_results platform id, e.g. `gemini-web`. */
+ platform?: string;
+ region?: string;
+ topicId?: string;
+ /** Matched against the prompts' text, as the page's search box. */
+ search?: string;
+}
+
+/** The filters every /api/mcp/mentions endpoint reads from its query string. */
+export function mentionsFiltersFromUrl(url: URL): MentionsFilterParams | null {
+ const q = url.searchParams;
+ const brandId = q.get('brand_id');
+ if (!brandId) return null;
+ return {
+ brandId,
+ dateFrom: q.get('date_from') ?? undefined,
+ dateTo: q.get('date_to') ?? undefined,
+ platform: q.get('platform') ?? undefined,
+ region: q.get('region') ?? undefined,
+ topicId: q.get('topic_id') ?? undefined,
+ search: q.get('search') ?? undefined,
+ };
+}
+
+function filterArgs(p: MentionsFilterParams, now = Date.now()) {
+ return {
+ p_brand_id: p.brandId,
+ p_date_from: p.dateFrom || new Date(now - MENTIONS_DEFAULT_DAYS * 86_400_000).toISOString(),
+ p_date_to: expandDateToEndOfDay(p.dateTo),
+ p_platform: p.platform || undefined,
+ p_region: p.region || undefined,
+ p_topic_id: p.topicId || undefined,
+ p_search: p.search?.trim() || undefined,
+ };
+}
+
+interface OwnedBrand {
+ id: string;
+ name: string;
+ /** The names tracking matches the brand by: its name and domains. */
+ terms: string[];
+}
+
+/** The brand, when it belongs to the key's organization; null otherwise. */
+async function ownedBrand(auth: McpAuthContext, brandId: string): Promise<OwnedBrand | null> {
+ if (!auth.organizationId) return null;
+ const { data } = await supabaseAdmin
+ .from('brands')
+ .select('id, name, brand_domains(domain)')
+ .eq('id', brandId)
+ .eq('organization_id', auth.organizationId)
+ .maybeSingle();
+ if (!data) return null;
+ const row = data as { id: string; name: string; brand_domains?: { domain?: string }[] };
+ return {
+ id: row.id,
+ name: row.name,
+ terms: [row.name, ...(row.brand_domains ?? []).map((d) => d.domain ?? '')].filter(Boolean),
+ };
+}
+
+const round1 = (n: number | null) => (n === null ? null : Math.round(n * 10) / 10);
+const whole = (n: number | null) => (n === null ? null : Math.round(n));
+
+export interface MentionFigures {
+ trackedResponses: number;
+ /** Responses naming the brand at least once. */
+ mentions: number;
+ /** mentions ÷ trackedResponses, in percent (one decimal); null with no responses. */
+ mentionRate: number | null;
+ /** Times the brand is named over all responses. */
+ timesNamed: number;
+ trackedPrompts: number;
+ promptsWithMentions: number;
+ /** The brand's average place among the brands an answer names (1 = first). */
+ averagePosition: number | null;
+ sentiment: {
+ positive: number;
+ neutral: number;
+ negative: number;
+ /** Shares of the mentions, in whole percent; null with no mentions. */
+ positivePct: number | null;
+ neutralPct: number | null;
+ negativePct: number | null;
+ /** positivePct − negativePct, −100…+100; null with no mentions. */
+ net: number | null;
+ /** n under 20: quote the figure as a low sample and read no change into it. */
+ lowSample: boolean;
+ };
+}
+
+function figures(t: MentionTotals): MentionFigures {
+ const split = sentimentSplit(t);
+ return {
+ trackedResponses: t.answers,
+ mentions: t.mentions,
+ mentionRate: round1(mentionRate(t)),
+ timesNamed: t.occurrences,
+ trackedPrompts: t.prompts,
+ promptsWithMentions: t.promptsWithMentions,
+ averagePosition: round1(averagePosition(t)),
+ sentiment: {
+ positive: t.positive,
+ neutral: Math.max(0, t.mentions - t.positive - t.negative),
+ negative: t.negative,
+ positivePct: whole(split?.positive ?? null),
+ neutralPct: whole(split?.neutral ?? null),
+ negativePct: whole(split?.negative ?? null),
+ net: wholeNet(t),
+ lowSample: isLowSample(t),
+ },
+ };
+}
+
+export interface MentionsSummary {
+ brand: { id: string; name: string };
+ /** The window read, and the one of the same length before it that `previous` covers. */
+ window: MentionsOverview['window'];
+ current: MentionFigures;
+ previous: MentionFigures;
+ /**
+ * Each change as the page's cards take it (00195): on the prompts both
+ * windows answered (`basis`), while the figures above are the whole windows'.
+ */
+ changes: {
+ /** Total mentions (times named, as the page counts them) against before, in percent; null with none before. */
+ mentionsPct: number | null;
+ /** Mention rate's change in points; null when a window has under 20 responses, as on the page's card. */
+ mentionRatePoints: number | null;
+ /** Prompts with mentions against before, in percent; null with none before. */
+ promptsWithMentionsPct: number | null;
+ /** Net sentiment's change in points; null when a window is a low sample. */
+ netSentimentPoints: number | null;
+ /** The prompts both windows answered, and those left out of every change; null before 00195. */
+ basis: { sharedPrompts: number; newPrompts: number; droppedPrompts: number } | null;
+ };
+ /** What the page's summary line says: the platform that moved the net most, and who AI names beside you. */
+ headline: {
+ mover: { platform: string; label: string; change: number } | null;
+ companions: string[];
+ };
+ platforms: Array<{
+ platform: string;
+ label: string;
+ trackedResponses: number;
+ mentions: number;
+ /** Times named on the platform. */
+ timesNamed: number;
+ mentionRate: number | null;
+ netSentiment: number | null;
+ /** Against the window before; null when either has under 20 mentions. */
+ netSentimentChange: number | null;
+ lowSample: boolean;
+ }>;
+ daily: Array<{
+ day: string;
+ trackedResponses: number;
+ mentions: number;
+ /** Times named that day: the page's Mentions line. */
+ timesNamed: number;
+ mentionRate: number | null;
+ netSentiment: number | null;
+ }>;
+}
+
+async function readOverview(p: MentionsFilterParams): Promise<MentionsOverview | null> {
+ const { data, error } = await supabaseAdmin.rpc('mentions_overview', filterArgs(p));
+ if (error) throw new Error(error.message);
+ return parseMentionsOverview(data);
+}
+
+/**
+ * The Overview's figures (get_mentions_summary): totals now and before, the
+ * changes the page shows (none read into a low sample), the summary line's
+ * facts, each platform, and the days. Null when the brand isn't the key's.
+ */
+export async function getMentionsSummaryFor(
+ auth: McpAuthContext,
+ params: MentionsFilterParams,
+): Promise<MentionsSummary | null> {
+ const brand = await ownedBrand(auth, params.brandId);
+ if (!brand) return null;
+ const o = await readOverview(params);
+ if (!o) return null;
+
+ const { current: cur, previous: prev } = o;
+ // As the page's cards: every change on the prompts both windows answered,
+ // and none read from or into a window under the floor.
+ const { current: base, previous: before } = changeBasis(o);
+ const rate = mentionRate(cur);
+ const baseRate = mentionRate(base);
+ const beforeRate = mentionRate(before);
+ const rateChangeLow =
+ cur.answers < LOW_SAMPLE_MENTIONS ||
+ base.answers < LOW_SAMPLE_MENTIONS ||
+ before.answers < LOW_SAMPLE_MENTIONS;
+ const headline = mentionsHeadline(o);
+
+ return {
+ brand: { id: brand.id, name: brand.name },
+ window: o.window,
+ current: figures(cur),
+ previous: figures(prev),
+ changes: {
+ mentionsPct: whole(relativeChange(base.occurrences, before.occurrences)),
+ mentionRatePoints:
+ rateChangeLow || rate === null || baseRate === null || beforeRate === null
+ ? null
+ : round1(baseRate - beforeRate),
+ promptsWithMentionsPct: whole(
+ relativeChange(base.promptsWithMentions, before.promptsWithMentions),
+ ),
+ netSentimentPoints: headline.netChange,
+ basis: o.same
+ ? {
+ sharedPrompts: o.same.prompts,
+ newPrompts: o.same.newPrompts,
+ droppedPrompts: o.same.droppedPrompts,
+ }
+ : null,
+ },
+ headline: {
+ mover: headline.mover
+ ? { ...headline.mover, label: mentionPlatformLabel(headline.mover.platform) }
+ : null,
+ companions: headline.companions,
+ },
+ platforms: o.platforms.map((row) => ({
+ platform: row.platform,
+ label: mentionPlatformLabel(row.platform),
+ trackedResponses: row.answers,
+ mentions: row.mentions,
+ timesNamed: row.occurrences,
+ mentionRate: round1(mentionRate(row)),
+ netSentiment: wholeNet(row),
+ netSentimentChange: platformNetChange(row),
+ lowSample: isLowSample(row),
+ })),
+ daily: mentionTrend(o).map((d) => ({
+ day: d.day,
+ trackedResponses: d.answers,
+ mentions: d.mentions,
+ timesNamed: d.occurrences,
+ mentionRate: round1(d.rate),
+ netSentiment: whole(d.net),
+ })),
+ };
+}
+
+export interface MentionCompetitors {
+ brand: { id: string; name: string; mentions: number; shareOfResponses: number | null };
+ trackedResponses: number;
+ /** Most mentioned first. Sentiment is measured for your brand only (V1). */
+ competitors: Array<{
+ competitorId: string;
+ name: string;
+ /** Responses naming the competitor, and its share of the tracked responses (%). */
+ mentions: number;
+ shareOfResponses: number | null;
+ /** Of those, the responses naming your brand too. */
+ sameResponseAsYou: number;
+ previousMentions: number;
+ /** Against the window before, in percent; null with none before. */
+ mentionsChangePct: number | null;
+ }>;
+}
+
+/**
+ * The Overview's competitor framing (get_mention_competitors): how often AI
+ * names each competitor in the brand's tracked responses, and how often in the
+ * same response as the brand.
+ */
+export async function getMentionCompetitorsFor(
+ auth: McpAuthContext,
+ params: MentionsFilterParams,
+): Promise<MentionCompetitors | null> {
+ const brand = await ownedBrand(auth, params.brandId);
+ if (!brand) return null;
+ const o = await readOverview(params);
+ if (!o) return null;
+ const answers = o.current.answers;
+ const share = (n: number) => round1(answers > 0 ? (n * 100) / answers : null);
+ return {
+ brand: {
+ id: brand.id,
+ name: brand.name,
+ mentions: o.current.mentions,
+ shareOfResponses: share(o.current.mentions),
+ },
+ trackedResponses: answers,
+ competitors: [...o.competitors]
+ .sort((a, b) => b.mentions - a.mentions)
+ .map((c) => ({
+ competitorId: c.competitorId,
+ name: c.name,
+ mentions: c.mentions,
+ shareOfResponses: share(c.mentions),
+ sameResponseAsYou: c.coMentions,
+ previousMentions: c.previousMentions,
+ mentionsChangePct: whole(relativeChange(c.mentions, c.previousMentions)),
+ })),
+ };
+}
+
+export interface MentionListParams extends MentionsFilterParams {
+ sentiment?: MentionSentiment;
+ /** A competitor named in the same response, or `none` for responses naming none. */
+ competitorId?: string;
+ sort?: MentionSort;
+ /** 1-based, 100 rows a page. */
+ page?: number;
+}
+
+export interface MentionListItem {
+ /** The answer's id: pass it to get_mention or override_mention_sentiment. */
+ id: string;
+ createdAt: string;
+ prompt: string;
+ promptId: string;
+ topic: string | null;
+ platform: string;
+ platformLabel: string;
+ model: string | null;
+ region: string | null;
+ sentiment: MentionSentiment | null;
+ timesNamed: number;
+ position: number | null;
+ brandsNamed: number | null;
+ coMentioned: string[];
+ /** The passage around the brand's first mention. */
+ excerpt: string;
+}
+
+export interface MentionList {
+ total: number;
+ prompts: number;
+ page: number;
+ pageSize: number;
+ mentions: MentionListItem[];
+}
+
+export function isMentionSentiment(value: unknown): value is MentionSentiment {
+ return (MENTION_SENTIMENTS as readonly unknown[]).includes(value);
+}
+
+export function isMentionSort(value: unknown): value is MentionSort {
+ return (MENTION_SORTS as readonly unknown[]).includes(value);
+}
+
+function listItem(row: MentionRow): MentionListItem {
+ return {
+ id: row.id,
+ createdAt: row.createdAt,
+ prompt: row.promptText,
+ promptId: row.promptId,
+ topic: row.topicName,
+ platform: row.platform,
+ platformLabel: mentionPlatformLabel(row.platform),
+ model: row.model,
+ region: row.region,
+ sentiment: row.sentiment,
+ timesNamed: row.occurrences,
+ position: row.position,
+ brandsNamed: row.brandsNamed,
+ coMentioned: row.coMentioned.map((c) => c.name),
+ excerpt: row.excerpt,
+ };
+}
+
+/**
+ * The Mentions tab's table (list_mentions): the responses naming the brand,
+ * 100 a page, with the table's filters and sorts, each cut to its excerpt.
+ */
+export async function listMentionsFor(
+ auth: McpAuthContext,
+ params: MentionListParams,
+): Promise<MentionList | null> {
+ const brand = await ownedBrand(auth, params.brandId);
+ if (!brand) return null;
+ const page = Math.max(1, Math.floor(params.page ?? 1));
+ const { data, error } = await supabaseAdmin.rpc('mentions_list', {
+ ...filterArgs(params),
+ p_sentiment: params.sentiment,
+ p_competitor_id: params.competitorId || undefined,
+ p_sort: params.sort ?? 'newest',
+ p_limit: MENTIONS_PAGE_SIZE,
+ p_offset: (page - 1) * MENTIONS_PAGE_SIZE,
+ });
+ if (error) throw new Error(error.message);
+ const list = parseMentionsList(data, (response) => mentionExcerpt(response, brand.terms));
+ if (!list) return null;
+ return {
+ total: list.total,
+ prompts: list.prompts,
+ page,
+ pageSize: MENTIONS_PAGE_SIZE,
+ mentions: list.rows.map(listItem),
+ };
+}
+
+export interface MentionDetail {
+ id: string;
+ brandId: string;
+ createdAt: string;
+ prompt: string | null;
+ platform: string;
+ platformLabel: string;
+ model: string | null;
+ region: string | null;
+ sentiment: MentionSentiment | null;
+ timesNamed: number;
+ position: number | null;
+ brandsNamed: number | null;
+ competitorsNamed: string[];
+ /** The full stored response. */
+ response: string;
+ citations: Citation[];
+ /** The latest "Sentiment is wrong" correction, if any. */
+ sentimentOverride: SentimentOverride | null;
+}
+
+interface ResultRow {
+ id: string;
+ brand_id: string;
+ created_at: string;
+ platform: string;
+ model_used: string | null;
+ region: string | null;
+ sentiment: string | null;
+ mention_count: number | null;
+ mention_position: number | null;
+ mentioned_entity_count: number | null;
+ competitor_mentions: unknown;
+ response: string | null;
+ citations: unknown;
+ prompts: { text?: string } | null;
+ brands: { organization_id?: string } | null;
+}
+
+interface StoredCompetitorMention {
+ competitor_id?: string;
+ name?: string;
+ mention_count?: number;
+ mention_position?: number | null;
+}
+
+/**
+ * The competitors an answer names, as the Mentions table lists them
+ * (mentions_list, 00158): each by its current name, the name stored at
+ * tracking time when it has none, in the order the answer names them.
+ */
+async function competitorsNamed(row: ResultRow): Promise<string[]> {
+ const named = (
+ Array.isArray(row.competitor_mentions)
+ ? (row.competitor_mentions as StoredCompetitorMention[])
+ : []
+ ).filter((c) => c.competitor_id && (c.mention_count ?? 0) > 0);
+ if (named.length === 0) return [];
+ const { data } = await supabaseAdmin
+ .from('competitors')
+ .select('id, name')
+ .eq('brand_id', row.brand_id)
+ .in(
+ 'id',
+ named.map((c) => String(c.competitor_id)),
+ );
+ const current = new Map(
+ ((data ?? []) as { id: string; name: string }[]).map((c) => [c.id, c.name]),
+ );
+ return named
+ .map((c) => ({
+ name: current.get(String(c.competitor_id)) ?? String(c.name ?? ''),
+ position: c.mention_position ?? Number.POSITIVE_INFINITY,
+ }))
+ .filter((c) => c.name)
+ .sort((a, b) => a.position - b.position || a.name.localeCompare(b.name))
+ .map((c) => c.name);
+}
+
+/**
+ * One response in full (get_mention): the stored text, its citations, the
+ * competitors it names and its latest sentiment correction, as the page's
+ * response drawer shows it. Null unless the answer's brand is the key's.
+ */
+export async function getMentionFor(
+ auth: McpAuthContext,
+ resultId: string,
+): Promise<MentionDetail | null> {
+ if (!auth.organizationId) return null;
+ const [answer, correction] = await Promise.all([
+ supabaseAdmin
+ .from('prompt_results')
+ .select(
+ 'id, brand_id, created_at, platform, model_used, region, sentiment, mention_count, ' +
+ 'mention_position, mentioned_entity_count, competitor_mentions, response, citations, ' +
+ 'prompts(text), brands!inner(organization_id)',
+ )
+ .eq('id', resultId)
+ .eq('brands.organization_id', auth.organizationId)
+ .maybeSingle(),
+ supabaseAdmin
+ .from('sentiment_overrides')
+ .select('sentiment, previous_sentiment, note, user_name, created_at')
+ .eq('result_id', resultId)
+ .order('created_at', { ascending: false })
+ .limit(1)
+ .maybeSingle(),
+ ]);
+ if (answer.error) throw new Error(answer.error.message);
+ const row = answer.data as unknown as ResultRow | null;
+ if (!row || row.brands?.organization_id !== auth.organizationId) return null;
+
+ return {
+ id: row.id,
+ brandId: row.brand_id,
+ createdAt: row.created_at,
+ prompt: row.prompts?.text ?? null,
+ platform: row.platform,
+ platformLabel: mentionPlatformLabel(row.platform),
+ model: row.model_used,
+ region: row.region,
+ sentiment: isMentionSentiment(row.sentiment) ? row.sentiment : null,
+ timesNamed: row.mention_count ?? 0,
+ position: row.mention_position,
+ brandsNamed: row.mentioned_entity_count,
+ competitorsNamed: await competitorsNamed(row),
+ response: row.response ?? '',
+ citations: Array.isArray(row.citations) ? (row.citations as Citation[]) : [],
+ // A missing table (a database before 00160) reads as no correction.
+ sentimentOverride: correction.error ? null : parseSentimentOverride(correction.data),
+ };
+}
+
+export interface MentionsPerceptionResult {
+ brand: { id: string; name: string };
+ window: { from: string; to: string; days: number };
+ /** The brand first, then up to four competitors by mentions, now and before. */
+ entities: Array<{
+ entity: string;
+ name: string;
+ isBrand: boolean;
+ mentions: number;
+ previousMentions: number;
+ }>;
+ /** What AI says next to the brand: responses with the term, their share of the brand's mentions, and before. */
+ brandTerms: Array<{
+ term: string;
+ responses: number;
+ sharePct: number | null;
+ previousResponses: number;
+ }>;
+ /** Each attribute's share of each entity's mentions (%), in `entities` order; null without mentions. */
+ attributes: Array<{ term: string; sharePct: (number | null)[] }>;
+ /** Competitors named in the same responses as the brand, now and before. */
+ coMentions: Array<{
+ competitorId: string;
+ name: string;
+ responses: number;
+ previousResponses: number;
+ }>;
+ /** The attribute a competitor leads by 20+ points, over 20+ mentions each; null when none. */
+ biggestGap: PerceptionGap | null;
+}
+
+/**
+ * The Perception tab (get_mentions_perception): terms found by rule in the
+ * sentences that name each brand (no LLM), the attributes that tell the brand
+ * and its competitors apart, co-mentions, and the biggest gap.
+ */
+export async function getMentionsPerceptionFor(
+ auth: McpAuthContext,
+ params: MentionsFilterParams,
+): Promise<MentionsPerceptionResult | null> {
+ const brand = await ownedBrand(auth, params.brandId);
+ if (!brand) return null;
+ const { data, error } = await supabaseAdmin.rpc('mentions_perception', filterArgs(params));
+ if (error) throw new Error(error.message);
+ const p = parseMentionsPerception(data);
+ if (!p) return null;
+ const brandMentions = p.entities.find((e) => e.isBrand)?.mentions ?? 0;
+ return {
+ brand: { id: brand.id, name: brand.name },
+ window: p.window,
+ entities: p.entities,
+ brandTerms: p.brandTerms.map((t) => ({
+ term: t.term,
+ responses: t.answers,
+ sharePct: whole(shareOf(t.answers, brandMentions)),
+ previousResponses: t.previousAnswers,
+ })),
+ attributes: attributeShares(p).map((a) => ({
+ term: a.term,
+ sharePct: a.shares.map((s) => whole(s)),
+ })),
+ coMentions: p.coMentions.map((c) => ({
+ competitorId: c.competitorId,
+ name: c.name,
+ responses: c.coMentions,
+ previousResponses: c.previousCoMentions,
+ })),
+ biggestGap: biggestGap(p),
+ };
+}
+
+export type MentionOverrideResult =
+ | {
+ changed: boolean;
+ previous: MentionSentiment | null;
+ sentiment: MentionSentiment;
+ override: SentimentOverride | null;
+ }
+ | { error: 'forbidden' | 'invalid' | 'missing'; message: string };
+
+/**
+ * "Sentiment is wrong" (override_mention_sentiment): sets a response's tone
+ * toward the brand, as the API key's owner, who must be an admin or manager
+ * of the brand's organization (00223). The answer's day is refreshed in the
+ * rollups at once, and the correction is kept with its note.
+ */
+export async function overrideMentionSentimentFor(
+ auth: McpAuthContext,
+ resultId: string,
+ sentiment: MentionSentiment,
+ note?: string,
+): Promise<MentionOverrideResult> {
+ // An answer of another organization reads as missing, not as forbidden.
+ if (!auth.organizationId) return { error: 'missing', message: 'Answer not found' };
+ const { data: owned, error: ownedError } = await supabaseAdmin
+ .from('prompt_results')
+ .select('id, brands!inner(organization_id)')
+ .eq('id', resultId)
+ .eq('brands.organization_id', auth.organizationId)
+ .maybeSingle();
+ if (ownedError) throw new Error(ownedError.message);
+ if (!owned) return { error: 'missing', message: 'Answer not found' };
+
+ const { data, error } = await supabaseAdmin.rpc('override_mention_sentiment', {
+ p_result_id: resultId,
+ p_sentiment: sentiment,
+ p_note: note?.trim() || undefined,
+ p_user_id: auth.userId,
+ });
+ if (error) {
+ if (error.code === '42501') return { error: 'forbidden', message: error.message };
+ if (error.code === '22023') return { error: 'invalid', message: error.message };
+ if (error.code === 'P0002') return { error: 'missing', message: error.message };
+ throw new Error(error.message);
+ }
+ const r = (data ?? {}) as Record<string, unknown>;
+ return {
+ changed: r.changed === true,
+ previous: isMentionSentiment(r.previous) ? r.previous : null,
+ sentiment,
+ override: parseSentimentOverride(r.override),
+ };
+}
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index d01d76a3c..d84f80892 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -64,6 +64,16 @@ import {
sourceRefError,
suggestionsShape,
} from './content-schemas';
+import {
+ getMentionCompetitorsFor,
+ getMentionFor,
+ getMentionsPerceptionFor,
+ getMentionsSummaryFor,
+ listMentionsFor,
+ overrideMentionSentimentFor,
+ type MentionsFilterParams,
+} from './mentions';
+import { MENTION_SENTIMENTS, MENTION_SORTS } from '@/lib/mentions-list';
/**
* Build a fresh MCP server bound to a single authenticated request.
@@ -79,6 +89,52 @@ const relaxedUuid = z
'Invalid UUID format',
);
+/** The Mentions & Sentiment page's filters, the same on every mentions tool. */
+const mentionFilters = {
+ brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),
+ date_from: z
+ .string()
+ .optional()
+ .describe('ISO timestamp (inclusive) lower bound. Defaults to 30 days ago, as the page.'),
+ date_to: z
+ .string()
+ .optional()
+ .describe('ISO timestamp (inclusive) upper bound; a YYYY-MM-DD covers that whole day.'),
+ platform: z
+ .string()
+ .optional()
+ .describe('One platform id, e.g. "chatgpt-web", "gemini-web", "perplexity-web".'),
+ region: z.string().optional().describe('Optional country code filter (e.g. "US", "TR").'),
+ topic_id: relaxedUuid.optional().describe('Topic UUID, from list_topics.'),
+ search: z.string().optional().describe("Matched against the prompts' text."),
+};
+
+function mentionParams(args: {
+ brand_id: string;
+ date_from?: string;
+ date_to?: string;
+ platform?: string;
+ region?: string;
+ topic_id?: string;
+ search?: string;
+}): MentionsFilterParams {
+ return {
+ brandId: args.brand_id,
+ dateFrom: args.date_from,
+ dateTo: args.date_to,
+ platform: args.platform,
+ region: args.region,
+ topicId: args.topic_id,
+ search: args.search,
+ };
+}
+
+const MENTIONS_BASIS =
+ 'Built from the stored answers with no LLM call; the window before is the same length. ' +
+ 'Net sentiment is positive minus negative share of the responses naming the brand, ' +
+ '−100…+100; under 20 mentions it is a low sample (lowSample: true): quote it as such and ' +
+ 'read no change into it. Sentiment is measured for the brand only, not competitors.';
+
export function createMcpServer(auth: McpAuthContext): McpServer {
const server = new McpServer({
name: 'ansvisor',
@@ -1345,6 +1401,156 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
},
);
+ server.registerTool(
+ 'get_mentions_summary',
+ {
+ description:
+ "The Mentions & Sentiment page's Overview for a brand: times named (`timesNamed`, the " +
+ "page's Total mentions), responses naming it, mention rate, prompts with mentions, " +
+ 'average position and sentiment (counts, shares, net), now and in the window before, ' +
+ "with `changes` taken as the page's cards take them: on the prompts both windows " +
+ 'answered (`changes.basis`), mentionsPct on times named; the platform that moved net sentiment ' +
+ 'most and the competitors AI names beside the brand (`headline`); each platform; and ' +
+ 'each day. Use it for "how is AI talking about us" / "why did sentiment drop on ' +
+ 'Gemini?". ' +
+ MENTIONS_BASIS,
+ inputSchema: mentionFilters,
+ },
+ async (args) => {
+ const summary = await getMentionsSummaryFor(auth, mentionParams(args));
+ if (!summary) {
+ return { content: [{ type: 'text', text: 'Brand not found' }], isError: true };
+ }
+ return { content: [{ type: 'text', text: JSON.stringify(summary, null, 2) }] };
+ },
+ );
+
+ server.registerTool(
+ 'list_mentions',
+ {
+ description:
+ "The responses naming the brand, as the Mentions tab's table: prompt, platform, model, " +
+ 'country, sentiment, times named, position among the brands named, competitors in the ' +
+ 'same response and an excerpt around the first mention. 100 a page; `total` counts ' +
+ 'every match. Pass a row id to get_mention for the full response. ' +
+ MENTIONS_BASIS,
+ inputSchema: {
+ ...mentionFilters,
+ sentiment: z.enum(MENTION_SENTIMENTS).optional().describe('Only this sentiment.'),
+ competitor_id: z
+ .string()
+ .optional()
+ .describe(
+ 'Only responses that also name this competitor (UUID, from ' +
+ 'get_mention_competitors), or "none" for responses naming no competitor.',
+ ),
+ sort: z
+ .enum(MENTION_SORTS)
+ .optional()
+ .describe('newest (default), oldest, co_mentions (most competitors first) or negative.'),
+ page: z.number().int().min(1).optional().describe('1-based page, 100 rows each.'),
+ },
+ },
+ async (args) => {
+ const list = await listMentionsFor(auth, {
+ ...mentionParams(args),
+ sentiment: args.sentiment,
+ competitorId: args.competitor_id,
+ sort: args.sort,
+ page: args.page,
+ });
+ if (!list) {
+ return { content: [{ type: 'text', text: 'Brand not found' }], isError: true };
+ }
+ return { content: [{ type: 'text', text: JSON.stringify(list, null, 2) }] };
+ },
+ );
+
+ server.registerTool(
+ 'get_mention',
+ {
+ description:
+ "One response in full, as the page's response drawer: the stored text, its citations, " +
+ 'the competitors it names, its sentiment and the latest "Sentiment is wrong" correction ' +
+ '(sentimentOverride), if any.',
+ inputSchema: {
+ id: relaxedUuid.describe('The response id, from list_mentions.'),
+ },
+ },
+ async (args) => {
+ const mention = await getMentionFor(auth, args.id);
+ if (!mention) {
+ return { content: [{ type: 'text', text: 'Answer not found' }], isError: true };
+ }
+ return { content: [{ type: 'text', text: JSON.stringify(mention, null, 2) }] };
+ },
+ );
+
+ server.registerTool(
+ 'get_mention_competitors',
+ {
+ description:
+ 'Competitor framing from the Mentions page: how often AI names each competitor in the ' +
+ "brand's tracked responses (count and share of responses, change against the window " +
+ 'before) and how often in the same response as the brand. ' +
+ MENTIONS_BASIS,
+ inputSchema: mentionFilters,
+ },
+ async (args) => {
+ const competitors = await getMentionCompetitorsFor(auth, mentionParams(args));
+ if (!competitors) {
+ return { content: [{ type: 'text', text: 'Brand not found' }], isError: true };
+ }
+ return { content: [{ type: 'text', text: JSON.stringify(competitors, null, 2) }] };
+ },
+ );
+
+ server.registerTool(
+ 'get_mentions_perception',
+ {
+ description:
+ 'What AI associates with the brand (the Perception tab): the terms in the sentences ' +
+ 'naming it, with responses and share of the responses naming it, now and before; the ' +
+ "attributes that tell the brand and its top competitors apart, as each one's share of " +
+ 'the responses naming it; competitors named in the same responses; and the biggest ' +
+ 'gap, an attribute a competitor leads by 20+ points (null when none does, or when ' +
+ 'the brand or that competitor has fewer than 20 mentions). Terms are found by rule, ' +
+ 'no LLM: a sentence naming two brands lends its words to both.',
+ inputSchema: mentionFilters,
+ },
+ async (args) => {
+ const perception = await getMentionsPerceptionFor(auth, mentionParams(args));
+ if (!perception) {
+ return { content: [{ type: 'text', text: 'Brand not found' }], isError: true };
+ }
+ return { content: [{ type: 'text', text: JSON.stringify(perception, null, 2) }] };
+ },
+ );
+
+ server.registerTool(
+ 'override_mention_sentiment',
+ {
+ description:
+ '"Sentiment is wrong": set one response\'s sentiment toward the brand, with an optional ' +
+ 'note. Every figure that reads it follows (Mentions, Insights) and the change is logged ' +
+ "under the API key's user, who must be an admin or manager of the brand's organization. " +
+ 'It is a write — only fire on explicit user intent for a specific response, never as ' +
+ 'part of an exploratory query.',
+ inputSchema: {
+ id: relaxedUuid.describe('The response id, from list_mentions.'),
+ sentiment: z.enum(MENTION_SENTIMENTS).describe('The correct sentiment.'),
+ note: z.string().max(500).optional().describe('Why, for the correction history.'),
+ },
+ },
+ async (args) => {
+ const result = await overrideMentionSentimentFor(auth, args.id, args.sentiment, args.note);
+ if ('error' in result) {
+ return { content: [{ type: 'text', text: result.message }], isError: true };
+ }
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
+ },
+ );
+
// ─── Content Editor (CE-022): drafts, read and written as a person would ───
const json = (value: unknown) => ({
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index c9952e6c6..31a5b8755 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -4252,7 +4252,12 @@ export type Database = {
Returns: Json
}
override_mention_sentiment: {
- Args: { p_note?: string; p_result_id: string; p_sentiment: string }
+ Args: {
+ p_note?: string
+ p_result_id: string
+ p_sentiment: string
+ p_user_id?: string
+ }
Returns: Json
}
normalize_page_path: { Args: { p_url: string }; Returns: string }