Skip to content

feat(mentions): read Mentions & Sentiment and correct a sentiment from the API and MCP - #1126

Merged
gkhngyk merged 4 commits into
ansvisor:mainfrom
cihan-gyk:feature/mentions-api
Oct 22, 2026
Merged

gkhngyk merged 4 commits into
ansvisor:mainfrom
cihan-gyk:feature/mentions-api

Conversation

@cihan-gyk

@cihan-gyk cihan-gyk commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Mentions & Sentiment over the API and MCP (MS-13, spec §14). The page's figures are now readable with an ans_ key, so Claude Desktop, Cursor and the in-app AI Agent Chat can answer "why did sentiment drop on Gemini?". "Sentiment is wrong" is available as a write for admins and managers. The numbers are the dashboard's: every read goes through the page's own database functions, and no LLM is called.

Rebased on main (2026-10-21). #1123, #1124 and #1125 are on main, so the diff is this PR's own commits. get_mentions_perception uses the same biggestGap as the tab (#1124), including its low-sample rule.

Reads (web/src/lib/mcp/mentions.ts)

Each read first checks the brand belongs to the key's organization, then calls mentions_overview (00157), mentions_list (00158) or mentions_perception (00161) as the service role, which those functions already let through.

  • Filters: the page's filters on every read: date_from / date_to (the last 30 days when left out, as the page; a date_to of YYYY-MM-DD covers that day), platform, region, topic_id and search over the prompts' text.
MCP tool REST What it returns
get_mentions_summary GET /api/mcp/mentions/summary The Overview: mentions, mention rate, prompts with mentions, average position and sentiment (counts, shares, net, lowSample), now and before, changes with the page's low-sample rules, the summary line's facts (the platform that moved net sentiment, companions), per platform and per day.
list_mentions GET /api/mcp/mentions The Mentions table, 100 a page, with sentiment, competitor_id (none too), sort and page; each answer cut to its excerpt on the server.
get_mention GET /api/mcp/mentions/{id} One answer in full: text, citations, competitors named (current names, as the table), sentiment and its latest correction.
get_mention_competitors GET /api/mcp/mentions/competitors Competitor framing: mentions, share of responses, change, and how often in the same response as the brand.
get_mentions_perception GET /api/mcp/mentions/perception Terms with their share of the responses naming the brand, attribute shares per brand, co-mentions and the biggest gap.

Write: "Sentiment is wrong"

MCP tool REST
override_mention_sentiment POST /api/mcp/mentions/{id}/sentiment-override with { "sentiment", "note"? }
  • Migration 00223_mention_sentiment_override_api.sql (renumbered from 00162, which main's 00162_refresh_insights_daily_range.sql took; 00204–00222 are the open Content and Billing PRs): override_mention_sentiment (00160) took the person from auth.uid(), which is null for API keys. It is restated with p_user_id:
    • when the service role calls, it is the person corrected for: the key's owner;
    • 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.
    • The 3-argument function is dropped rather than overloaded (a 3-argument call would match both). The dashboard's call keeps working through the new argument's default.
  • Statuses: an answer of another organization is a 404 before the database is asked. The function's refusals come back as 403 (42501), 400 (22023) and 404 (P0002).

In-app AI Agent Chat

lib/agent/tools.ts gets the five reads, as thin wrappers like its other tools. The system prompt lists them and says how to read net sentiment and a low sample. The write stays out of the chat.

Docs

docs/guides/mcp-server.mdx has a Mentions & sentiment section with the tools, the REST paths and a curl example. The server registers 50 tools with this PR; the guide's count (mcp-server.mdx:223) is updated to 50 in a one-line docs PR right after this merges, so this approved branch doesn't move. The skills (skills/*/SKILL.md) follow in a separate docs PR.

Deploy

Apply 00223 after 00160 and 00161 (it restates 00160's function with p_user_id; nothing later redefines it).

Related issue

None.

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

  1. Apply 00223 (00157–00161 are on the hosted DB) and run node src/scripts/backfill-mentions-daily.js (server), as in feat(mentions): add the per-answer terms and the Perception read #1123.

  2. Create a key in Settings → API Keys, then call:

    curl "http://localhost:3000/api/mcp/mentions/summary?brand_id=<brand_id>" -H "Authorization: Bearer ans_..."
    • The figures match the Overview.
    • Add &platform=gemini-web, &date_from=… or &search=…: the figures follow the page's filters.
  3. GET /api/mcp/mentions?brand_id=…&sentiment=negative: the total matches the Mentions tab with Sentiment = Negative. Take an id and GET /api/mcp/mentions/<id>.

  4. As an admin's key:

    curl -X POST "http://localhost:3000/api/mcp/mentions/<id>/sentiment-override" -H "Authorization: Bearer ans_..." -H "Content-Type: application/json" -d '{"sentiment":"neutral","note":"test"}'
    • The drawer shows the correction.
    • Revert it the same way.
  5. In an MCP client, tools/list shows 50 tools, the six *mention* ones among them.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/): no errors; the 7 warnings are in files this PR does not touch
  • yarn typecheck passes (run from web/)
  • yarn format:check passes (run from web/)
  • Changes are focused — one concern per PR

Also run:

  • web: yarn test (1,963) and yarn build pass.
    • lib/mcp/mentions.test.ts:
      • the filters from a query string;
      • the 30-day default and a whole-day date_to;
      • the summary's figures, changes, mover and days;
      • low samples;
      • a brand or answer of another organization;
      • competitors by mentions;
      • the list's page, filters and excerpts;
      • one answer with current competitor names;
      • perception shares and the gap;
      • the correction as the key's owner and its refusals.
    • Endpoints: mentions/route.test.ts and [id]/sentiment-override/route.test.ts cover query parsing, body checks and status codes.
    • lib/agent/system-prompt.test.ts: the tools and the low-sample rule.
  • bash supabase/build-schema.sh: regenerated schema.sql.
  • Dev database:
    • A rolled-back dry run first: the service role for an admin corrects and logs their name; the service role with no person is refused; a signed-in admin's 3-argument call works; a signed-in caller passing someone else's id is refused. Then the migration was applied (as 00162 at the time; the body is unchanged).
    • End to end on the demo brand, with a temporary ans_ key (deleted afterwards):
      • the five reads match the page: 107 mentions, net +21, 21 negative, ChatGPT 38 / +24;
      • another brand is a 404 and no key a 401;
      • the correction over REST and over MCP changed one answer (visibility score 43 → 50) and was reverted, with its log rows removed;
      • the drawer's own Sentiment is wrong still works after the migration (tried and reverted).
  • Not run: the in-app agent with a live model, which needs a model key.

🤖 Generated with Claude Code

@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk the last Mentions piece: the page's reads over the API and MCP (summary, list, one answer, competitors, perception) and "Sentiment is wrong" for admin/manager keys, plus the five reads in the in-app agent. On deploy, after 00157–00161, please apply 00162 (override_mention_sentiment gains p_user_id for service-role calls). The in-app agent's new tools could use one live question with your model key, e.g. "why did sentiment drop on Gemini?". Stacked on #1125 → … → #1115.

@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 17, 2026
@gkhngyk

gkhngyk commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

Two things block this from landing on its own:

  1. Migration number. 00162 is taken on main by 00162_refresh_insights_daily_range.sql (feat(mentions): correct an answer's sentiment from the response drawer #1121), and 00163 by feat(action-center): open a brand without KPIs on a ready-made set #1129. Please rename 00162_mention_sentiment_override_api.sql to the next free number when you rebase, and regenerate schema.sql.
  2. Perception. GET /api/mcp/mentions/perception, its MCP tool and the agent tool read mentions_perception from feat(mentions): add the per-answer terms and the Perception read #1123, which is on hold for the read redesign (see feat(mentions): add the per-answer terms and the Perception read #1123 (comment)). feat(mentions): add Copy summary and Export CSV to the Mentions page #1125 is now rebuilt on main without the Perception commits; it only shared context lines with them.

If you'd rather land the API now, move the Perception route and tools (with their tests and the docs lines) into a small follow-up stacked on #1124, and rebase the rest on main after #1125. Otherwise this one, and #1127 with it, waits for #1123/#1124.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cihan-gyk this needs a rebase on main (after #1123). The branch carries an older copy of the stack, and merging it as it stands would undo two fixes that are already on main. Main has no Mentions MCP tools or routes yet, so the API/MCP work itself is still new.

Drop from the branch. Main or #1123 has the current version:

  • 00158_mentions_list.sql: this is the copy from before the read-first rewrite. It would remove the partial index on mention_count > 0 and the mention_rows CTE that brought the 30-day table from 8.8 s to under 2 s.
  • 00161_mentions_perception.sql: this older copy restates refresh_mentions_daily with the terms inside it.
    • That reverts 00192 (#1227): the per-brand advisory lock goes away.
    • It also puts term extraction back inside the sentiment correction's request.
    • Take #1123's version, which has its own refresh_mention_terms.
  • 00160_mention_sentiment_override.sql: identical to main.
  • server/src/lib/mentions-rollups.js and its test: take #1123's version.
  • action-center/from-mentions.js, validate.js, _mention-parts.tsx, _response-drawer.tsx and the other add/add conflicts: these come from the old #1117/#1118 copies. Take main's.

Renumber: 00162_mention_sentiment_override_api.sql collides with main's 00162_refresh_insights_daily_range.sql.

  • It depends on 00160 (sentiment_overrides, sentiment_visibility_bonus), so it can't go in the 00159 gap, and #1123 keeps 00161.
  • Use the next free number when you rebase. The open content stack (#1256 … #1307) takes 00204–00219, so that's 00220 for now.
  • The content is fine: it's 00160's function plus p_user_id, it only calls the refresh_* functions, and nothing later on main redefines it.

After the rebase:

  1. Regenerate types/supabase.ts for the 4-argument override_mention_sentiment, re-run build-schema.sh, and resolve the docs/guides/mcp-server.mdx conflict. Main added tools in #1156/#1157.
  2. If #1226 / #1230 land first, follow them:
    • get_mentions_summary should report "mentions" as the dashboard's Total mentions does (occurrences).
    • Its changes should come from the same-prompt basis (changeBasis), so the MCP numbers match the page.

@gkhngyk

gkhngyk commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

Update: #1308 takes 00220 as well, so the next free number is 00221. Please check supabase/migrations on main when you rebase.

@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk Rebased on main and force-pushed. Its own change is the API/MCP commit (39f9aad), now on #1124 → #1123.

Checked: server 1,920 tests, lint; web 1,963 tests, tsc, lint, Prettier and yarn build. Old head kept locally as backup/1126-before-rebase (458276b).

@mintlify

mintlify Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 416facf.

Approve preview

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs one more rebase on the current main, then it's ready. The code is right. GitHub reports it CONFLICTING because the Content stack landed after this branch was cut.

CI "failure"

  • The failing check is Mintlify Preview (fork), with conclusion action_required. Mintlify won't build a docs preview for a fork PR until someone with write access approves the commit. It runs because the PR edits docs/guides/mcp-server.mdx.
  • All four code checks pass: schema, migrations flag, web and server. Vercel was still pending.
  • Approve the preview from the PR's checks page, or ignore it. Nothing in the code needs to change for it.

Rebase

  • The branch is #1124 plus 39f9aad5.
  • The old copies of 00158, 00160, 00161, mentions-rollups.js and the #1117/#1118 files are gone. What's left is identical to main or to #1123.

Conflicts on the current main

  • web/src/lib/mcp/server.ts: main's Content tools (#1305) and the Mentions tools both add imports and registerTool blocks at the same spots. Keep both. The tool names don't overlap.
  • supabase/schema.sql: re-run bash supabase/build-schema.sh, so 00223 follows 00221.
  • en.json, types/supabase.ts and the docs merge cleanly.

Migration 00223_mention_sentiment_override_api.sql

  • It's a pure renumber: only the header line changed from the old 00162.
  • 00223 is free. Open PRs hold 00222 and 00224–00227.
  • It sorts after 00160, which it depends on. Nothing on main up to 00221 redefines override_mention_sentiment, refresh_mentions_daily or refresh_insights_daily.
  • types/supabase.ts changes only the function's Args, adding p_user_id?.
  • Prod still has the 3-argument function. Apply 00223 before merging: the MCP and REST write passes p_user_id, and the dashboard's 3-argument call keeps working through the default.

Nits (optional)

  • The filters' platform description gives "perplexity" as an example. That's the legacy API id; tracked answers use perplexity-web.
  • get_mentions_perception's description still says "share of its mentions". #1124 now labels these "share of the responses naming".
  • As you said, get_mentions_summary should switch to occurrences and changeBasis once #1226 / #1230 land.

cihan-gyk and others added 2 commits October 21, 2026 22:10
…m the API and MCP

The Mentions page's figures over the API and MCP (MS-13): summary, the
mentions list, one answer, competitors and perception, under the page's
filters, from the page's own database functions after a brand check; and
"Sentiment is wrong" as the API key's owner. Migration 00162 lets
override_mention_sentiment correct for that person when the service role
calls, still only for an admin or manager of the answer's organization. The
in-app agent gets the five reads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The tool description said null only when no competitor leads by 20+
points; it is also null when the brand or that competitor has fewer than
20 mentions (ansvisor#1124's low-sample rule), as the skills now say (ansvisor#1127).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cihan-gyk
cihan-gyk force-pushed the feature/mentions-api branch from 39f9aad to bd20194 Compare October 21, 2026 19:11
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk Rebased onto the current main (58007fc, with #1123, #1124, #1316 and #1318 in), force-pushed with lease from 39f9aad.

  • server.ts: main's Content tools and the Mentions tools are both kept. The Mentions imports and helpers sit after the Content ones, and the Mentions tools come before the Content Editor section.
  • schema.sql: rebuilt with build-schema.sh, so 00223 follows 00221, and 00224–00228 follow it.
  • Nits:
  • Checks: web 2,465 tests, tsc, lint, Prettier and build pass. After the last main merge, tsc and the MCP / agent tests (83) pass again.

00223 is on the dev DB; as you said, it goes on production before this merges. #1127 follows with its two wording fixes.

gkhngyk
gkhngyk previously approved these changes Oct 22, 2026

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. All the earlier review items are done:

  • Rebase. git merge-tree onto the current main (c66906ff) is clean. In server.ts the Content tools and the Mentions tools are both registered, and nothing from main was dropped. schema.sql matches a fresh build-schema.sh, with 00223 between 00221 and 00224.
  • Nits. The platform example is now perplexity-web. The perception descriptions say "share of the responses naming it". bd20194 adds the biggestGap low-sample rule.
  • 00223. The number is still free. p_user_id counts only for the service role, and a signed-in caller is always auth.uid(). Either way the person must be an admin or manager of the answer's organization. anon and public can't execute the function. We'll apply it to the hosted database before merging.

One small thing before merge: please update the PR description, since it becomes the squash commit message.

  • It still says the branch is stacked on #1124 → #1123 and includes their commits.
  • It says tools/list shows 36 tools. The server registers 50 with this PR.
  • The "36 tools" line in docs/guides/mcp-server.mdx:223 was already behind main's 44. Updating it here would also be welcome.

@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk Thanks! PR description updated for the squash message: no longer stacked (#1123/#1124 are on main), and tools/list shows 50 tools. I left docs/guides/mcp-server.mdx:223 out of this branch so your approval stays; a one-line docs PR setting it to 50 follows right after #1126 merges.

@gkhngyk

gkhngyk commented Oct 22, 2026

Copy link
Copy Markdown
Contributor

#1226 and #1230 are merged now (00191 and 00195 are on production). Along with the description update, please switch get_mentions_summary to occurrences and changeBasis as planned, so the API reads the same as the page. Then I'll apply 00223 and merge this with #1127.

cihan-gyk and others added 2 commits October 22, 2026 15:17
…s do

Total mentions' change is now on times named (occurrences), and every
change is taken on the prompts both windows answered (changeBasis,
00195), with the counts behind it in changes.basis. The mention rate's
change is null when either window has under 20 responses, as on the
card. Adds promptsWithMentionsPct, and timesNamed per platform and day.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk switched as planned, in 416facf (on top of a merge of main, 2a14dbf):

  • changes.mentionsPct is now the change in times named (occurrences), the page's Total mentions, not in responses naming the brand.
  • Every change uses changeBasis: it is taken on the prompts both windows answered (00195), as the Overview cards do. The current / previous figures stay the whole windows'. The basis is in a new changes.basis (sharedPrompts, newPrompts, droppedPrompts; null before 00195).
  • changes.mentionRatePoints is null when the current window, or either shared window, has under 20 responses (the card's rule). Before, it only checked the current window.
  • New fields:
    • changes.promptsWithMentionsPct (the third card);
    • timesNamed on each platforms[] row;
    • timesNamed on each daily[] row (the trend's Mentions line).
  • netSentimentPoints is unchanged. It already came from mentionsHeadline, which uses changeBasis.
  • Descriptions:

Checks: web format, lint (0 errors), typecheck, all 2622 tests and build pass.

Ready for 00223 and the merge with #1127 when you are.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. The switch is in (416facf), and get_mentions_summary now takes its changes as main's Overview cards do (_overview-kpis.tsx):

  • changes.mentionsPct is the change in occurrences, taken on changeBasis (web/src/lib/mcp/mentions.ts:266).
  • The rate's change is null when the current window or either shared window has under 20 responses. This is the card's rateChangeLow.
  • promptsWithMentionsPct uses the same basis. netSentimentPoints still comes from mentionsHeadline, which uses changeBasis.
  • The field names match main's mentions-overview.ts:
    • changes.basis reads same.prompts, newPrompts and droppedPrompts;
    • timesNamed reads occurrences on the totals, the platform rows and the days;
    • production's mentions_overview returns same, new_prompts, dropped_prompts and occurrences.
  • The tests cover the shared-prompt basis and the stricter rate rule.
  • The merge of main (2a14dbf) re-merges to the same tree and carries nothing else.

Two small things. Neither blocks the merge:

  1. Optional rename, cheaper before the API ships.
    • current.mentions, platforms[].mentions and daily[].mentions are the responses naming the brand.
    • changes.mentionsPct sits beside them but is the change in timesNamed (mentions.ts:188, :266). A client that works out the change from current.mentions and previous.mentions gets a different number.
    • Renaming it changes.timesNamedPct ties each change to the figure it measures. The MCP and agent descriptions, the mcp-server.mdx row and #1127's two lines would follow.
  2. PR description. It becomes the squash message. Its get_mentions_summary row still reads "mentions, mention rate, … changes with the page's low-sample rules". Please add times named, and that every change is taken on the prompts both windows answered (changes.basis).

00223

  • It isn't on production yet, and the 3-argument function is still the live one.
  • The file hasn't changed since the last review. Its body is the live function's plus the v_person line, and its grants match.
  • refresh_insights_daily and refresh_mentions_daily still take (uuid, date, date).
  • 00231's Perception rollups hold no sentiment, so a correction doesn't need to refresh them.
  • The number is still free on main. We'll apply it before merging.

This merges cleanly on main (12846db) and with #1127, and schema.sql keeps 00223 between 00221 and 00224. With this PR the server registers 50 tools. mcp-server.mdx:223 still says 36 and is left for the follow-up docs PR.

00223 is applied on production. The old 3-argument function is replaced, execute is granted to authenticated and service_role only, and an outsider passing a member's id as p_user_id is refused (42501). Tested on top of main together with #1333: web and server tests, tsc, lint and Prettier pass, and schema.sql matches a rebuild.

@gkhngyk
gkhngyk merged commit 30d5967 into ansvisor:main Oct 22, 2026
6 checks passed
gkhngyk pushed a commit that referenced this pull request Oct 22, 2026
* docs(skills): teach the AEO coach the Mentions & Sentiment tools

Both skills learn the six Mentions tools and REST endpoints from #1126: the
numbers to quote (net sentiment, low sample, brand only), a workflow for
"why did sentiment drop on Gemini?", and the correction as a write. The
sentiment reference explains net sentiment and the README lists the new
questions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(skills): say which Mentions changes are null, and when biggestGap is

- Only changes.netSentimentPoints is null on a low sample (and the
  mention rate's change under 20 tracked responses); mentionsPct isn't
  gated.
- biggestGap is also null when the brand or the leading competitor has
  fewer than 20 mentions (#1124's low-sample rule).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(skills): say Mentions changes are on the prompts both windows answered, and mentionsPct is times named

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(skills): lead the Mentions glossary with times named, the page's Total mentions

As the Overview card counts them, "mentions" are every time AI names the
brand (timesNamed): the coach quotes that for "how many mentions", and
mentions (responses naming the brand) as the base of the rate, net
sentiment and lowSample, whose 20 is responses naming the brand.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-migration Adds or edits a migration — apply it to the hosted database

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants