Skip to content

feat(mcp): expose get_visibility_trend tool (visibility time-series) + REST endpoint - #118

Merged
gkhngyk merged 1 commit into
mainfrom
feat/mcp-get-visibility-trend
May 28, 2026
Merged

gkhngyk merged 1 commit into
mainfrom
feat/mcp-get-visibility-trend

Conversation

@gkhngyk

@gkhngyk gkhngyk commented May 28, 2026

Copy link
Copy Markdown
Contributor

Closes #96. Last of the A-group MCP read tools — the in-product assistant epic (#94) can start in earnest after this lands.

What

  • New MCP tool: `get_visibility_trend(brand_id, ..., granularity)` → buckets of visibility / mentions / citations over time, plus avg competitor score per bucket for brand-vs-competitor charts.
  • New REST endpoint: `GET /api/mcp/visibility-trend`.
  • New migration `00008_visibility_trend_aggregates.sql` — DB-side bucketing via `date_trunc`, jsonb return shape mirroring 00006.

Shape of the response

```json
{
"granularity": "day",
"buckets": [
{
"date": "2026-03-30",
"result_count": 154,
"avg_visibility_score": 76,
"total_mentions": 646,
"total_citations": 693,
"avg_competitor_score": 63
}
]
}
```

`date` is `YYYY-MM-DD` in UTC (week granularity = the ISO Monday). `avg_competitor_score` is the mean of every competitor score unwrapped from `competitor_mentions` in that bucket — `null` if no competitors were mentioned. Stable lex-sortable bucket keys + small numeric fields = chart-friendly without any client-side date-parse step.

Why DB-side

The existing `getVisibilityTrend` in `actions/tracking.ts` fetches every `prompt_results` row in the window and folds by day in JS. Fine for one human loading the insights page; bad for MCP / the assistant in #94, which will fire repeated trend queries and would otherwise pay full row transfer + JS reduce per call. The new RPC buckets server-side and returns ~one row per day. Same lever as #93 / #114, applied to the trend surface.

Granularity

Constrained to `'day'` or `'week'` — both at the SQL layer (the tool description) and the REST layer (400 if anything else). `date_trunc` would happily accept `'month'` / `'year'` too, but exposing those introduces empty-bucket ambiguity at the assistant layer. If a caller wants monthly aggregation today they can group the daily buckets themselves.

Parity verification

Against the largest brand in the cloud project (5054 prompt results, 35 distinct UTC day buckets):

  • ✅ `row_count`, `sum_visibility`, `sum_mentions`, `sum_citations`, `comp_sum_visibility`, `comp_count` match the inline-SQL aggregation byte-for-byte at decimal precision across all 35 buckets
  • ✅ Bucket date range matches expected window (`2026-03-30` → `2026-05-06`)
  • ✅ `yarn typecheck` + `yarn format:check` clean
  • ✅ Migration applied to the cloud project; `SECURITY DEFINER` + `GRANT EXECUTE` for `authenticated` + `service_role` matches the existing aggregate RPC pattern

Auth + safety

Ownership check first via `supabaseAdmin` — wrong-org or missing `brand_id` returns null (→ 404) before the RPC fires. Same defensive pattern as the other MCP data fns. Membership enforcement inside the function itself is tracked uniformly in #115 alongside the other aggregate RPCs.

Files

File Change
`supabase/migrations/00008_visibility_trend_aggregates.sql` New RPC: jsonb-shaped buckets by day/week, raw sums + counts
`web/src/lib/mcp/data.ts` `getVisibilityTrendFor` data fn + `VisibilityTrendParams` / `VisibilityTrendOutput` / `VisibilityTrendGranularity` types
`web/src/lib/mcp/server.ts` Registers `get_visibility_trend`
`web/src/types/supabase.ts` Generated-types entry for the new RPC
`web/src/app/api/mcp/visibility-trend/route.ts` GET handler with granularity-param validation

A-group complete

After this lands, the MCP read-tool surface the assistant epic (#94) needs is done:

#94 epic can now sequence onto Phase 2 (agent + chat UI text-only) without parallel-codepath teknik borç.

…+ REST endpoint

Closes #96. Last of the A-group MCP read tools — exposes the
visibility / mentions / citations trend the dashboard's insights page
already renders, plus an avg competitor score per bucket so an assistant
can plot brand-vs-competitor lines from a single tool call.

The existing getVisibilityTrend in actions/tracking.ts fetches every
prompt_results row in the window and folds by day in JS — fine for one
human loading the page, but it scales badly for MCP clients (the
planned assistant in #94 will fire a lot of these). The migration adds
a visibility_trend_aggregates RPC that buckets by date_trunc(p_granularity,
created_at AT TIME ZONE 'UTC') and returns raw sums + counts as jsonb;
the JS layer only divides and rounds.

Migration mirrors 00006: single jsonb return, ORDER BY inside jsonb_agg
for a stable response, SECURITY DEFINER for symmetry with the other
aggregate RPCs (membership enforcement tracked in #115).

Granularity is constrained to 'day' or 'week' so the response shape
stays predictable for chart consumers; date_trunc would happily accept
'month'/'year' too but those introduce empty-bucket ambiguity at the
assistant layer.

Parity-checked against the largest brand in the cloud project (5054
prompt_results, 35 distinct UTC day buckets) — every bucket's row_count,
sum_visibility, sum_mentions, sum_citations, comp_sum_visibility, and
comp_count matches the inline-SQL aggregation byte-for-byte at decimal
precision.

- supabase/migrations/00008_visibility_trend_aggregates.sql
- web/src/lib/mcp/data.ts: getVisibilityTrendFor(auth, params)
- web/src/lib/mcp/server.ts: registers get_visibility_trend
- web/src/types/supabase.ts: RPC type definition for the new function
- web/src/app/api/mcp/visibility-trend/route.ts: GET handler
@gkhngyk
gkhngyk merged commit a6ff5d6 into main May 28, 2026
3 checks passed
@gkhngyk
gkhngyk deleted the feat/mcp-get-visibility-trend branch May 28, 2026 19:59
gkhngyk added a commit that referenced this pull request May 31, 2026
Bundles the in-product Agent epic (#120, #121), the BYOK rollout on
cloud, the MCP toolkit expansion (#109, #110, #116, #117, #118), the
insights performance fix (#114), and the invite-accept flow rebuild
(#127, #129, #130) into a tagged release.

See CHANGELOG.md for the full notes.
gkhngyk added a commit that referenced this pull request May 31, 2026
Bundles the in-product Agent epic (#120, #121), the BYOK rollout on
cloud, the MCP toolkit expansion (#109, #110, #116, #117, #118), the
insights performance fix (#114), and the invite-accept flow rebuild
(#127, #129, #130) into a tagged release.

See CHANGELOG.md for the full notes.

This branch was successfully deployed

1 active deployment
Preview — 34e69b83 Deployed May 28, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(mcp): expose get_visibility_trend tool (visibility time-series) + REST endpoint

1 participant