Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(mcp): read the prompts across their locations, as the Locations view shows them (#1727)

Cihan075cfba0cb95
diff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdx
index 1ff845e25..96d49d35d 100644
--- a/docs/guides/mcp-server.mdx
+++ b/docs/guides/mcp-server.mdx
@@ -220,7 +220,7 @@ instead.
## Available tools
-The MCP server exposes **60 tools**. Descriptions below match
+The MCP server exposes **61 tools**. Descriptions below match
[`web/src/lib/mcp/server.ts`](https://github.com/ansvisor/ansvisor/blob/main/web/src/lib/mcp/server.ts).
Tools that change data are marked **writes** — only call them on explicit user
intent, not during exploratory queries. A write that needs a particular role
@@ -293,6 +293,7 @@ curl "https://app.ansvisor.com/api/mcp/mentions/summary?brand_id=<brand_id>&plat
| `accept_prompt_suggestion` | Create a tracked prompt from one pending suggestion using the brand's default engines and plan/location checks. | **yes** (admin, manager) |
| `dismiss_prompt_suggestion` | Dismiss one pending prompt suggestion so it no longer appears in future lists. | **yes** (admin, manager, analyst) |
| `get_prompt_volumes` | Per-prompt Google and estimated AI search demand and competition for prompts that already have analysis, with `measured_demand`: the real signs people ask it (Search Console, Google Trends, People Also Ask, YouTube) and their level, or `null` until any was read. | |
+| `get_prompt_locations` | Each tracked prompt in each location side by side, as the **Locations** view shows it: AI Visibility Score, mentions, citations, average position and runs per prompt and country, US state or city, with each location's averages and the view's cards (weakest and strongest location, the prompt that differs most). Up to 12 `locations` (codes it can't compare come back in `ignored_locations`); paged by prompt, `limit` up to 100. REST: `GET /api/mcp/prompt-locations?brand_id=<brand_id>&locations=US,DE`. | |
| `get_prompt_usage` | Tracked-prompt usage against the plan: the brand's active and paused prompts, and the account's active prompts, brands, prompt locations used and location limit. | |
### Content opportunities
diff --git a/web/src/app/api/mcp/prompt-locations/route.test.ts b/web/src/app/api/mcp/prompt-locations/route.test.ts
new file mode 100644
index 000000000..70df89516
--- /dev/null
+++ b/web/src/app/api/mcp/prompt-locations/route.test.ts
@@ -0,0 +1,56 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/** GET /api/mcp/prompt-locations: the REST mirror of get_prompt_locations. */
+
+const { getPromptLocationsFor } = vi.hoisted(() => ({ getPromptLocationsFor: vi.fn() }));
+vi.mock('@/lib/mcp-auth', () => ({
+ authenticateMcpRequest: vi.fn(async () => ({
+ userId: 'user-1',
+ email: null,
+ organizationId: 'org-1',
+ apiKeyId: 'key-1',
+ })),
+}));
+vi.mock('@/lib/mcp/prompt-locations', () => ({ getPromptLocationsFor }));
+
+const { GET } = await import('./route');
+
+const get = (query: string) =>
+ GET(new Request(`http://localhost/api/mcp/prompt-locations${query}`));
+
+beforeEach(() => {
+ getPromptLocationsFor.mockReset();
+});
+
+describe('GET /api/mcp/prompt-locations', () => {
+ it('compares the locations listed, over the window asked', async () => {
+ getPromptLocationsFor.mockResolvedValue({ locations: [], prompts: [] });
+ const res = await get('?brand_id=brand-1&locations=US-CA,TR&days=7&limit=20');
+ expect(res.status).toBe(200);
+ expect(getPromptLocationsFor).toHaveBeenCalledWith(expect.anything(), {
+ brandId: 'brand-1',
+ locations: ['US-CA', 'TR'],
+ days: 7,
+ from: undefined,
+ to: undefined,
+ limit: 20,
+ offset: undefined,
+ });
+ });
+
+ it('passes every code listed on, for the tool to read and say which it left out', async () => {
+ getPromptLocationsFor.mockResolvedValue({ locations: [], prompts: [] });
+ const codes = Array.from({ length: 13 }, (_, i) => `C${i}`);
+ await get(`?brand_id=brand-1&locations=us,%20de,${codes.join(',')}`);
+ expect(getPromptLocationsFor.mock.calls[0][1].locations).toEqual(['us', ' de', ...codes]);
+ });
+
+ it('refuses a window it does not offer, and answers 404 for another brand', async () => {
+ expect((await get('')).status).toBe(400);
+ expect((await get('?brand_id=brand-1&days=14')).status).toBe(400);
+ expect((await get('?brand_id=brand-1&date_from=soon')).status).toBe(400);
+ getPromptLocationsFor.mockResolvedValue(null);
+ expect((await get('?brand_id=brand-2')).status).toBe(404);
+ });
+});
diff --git a/web/src/app/api/mcp/prompt-locations/route.ts b/web/src/app/api/mcp/prompt-locations/route.ts
new file mode 100644
index 000000000..091aadfdb
--- /dev/null
+++ b/web/src/app/api/mcp/prompt-locations/route.ts
@@ -0,0 +1,55 @@
+import { NextResponse } from 'next/server';
+import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { getPromptLocationsFor } from '@/lib/mcp/prompt-locations';
+
+/**
+ * GET /api/mcp/prompt-locations — REST mirror of the `get_prompt_locations`
+ * MCP tool. `locations` is a comma-separated list of codes.
+ */
+export async function GET(req: Request) {
+ const auth = await authenticateMcpRequest(req);
+ if (auth instanceof NextResponse) return auth;
+
+ const url = new URL(req.url);
+ const brandId = url.searchParams.get('brand_id');
+ if (!brandId) {
+ return NextResponse.json({ error: 'brand_id is required' }, { status: 400 });
+ }
+ const number = (name: string) => {
+ const raw = url.searchParams.get(name);
+ const value = raw === null ? undefined : Number.parseInt(raw, 10);
+ return value !== undefined && Number.isFinite(value) ? value : undefined;
+ };
+ const days = number('days');
+ if (days !== undefined && ![7, 30, 90].includes(days)) {
+ return NextResponse.json({ error: 'days must be 7, 30 or 90' }, { status: 400 });
+ }
+ const date = (name: string) => {
+ const value = url.searchParams.get(name) ?? undefined;
+ return value !== undefined && !Number.isFinite(Date.parse(value)) ? null : value;
+ };
+ const from = date('date_from');
+ const to = date('date_to');
+ if (from === null || to === null) {
+ return NextResponse.json({ error: 'date_from and date_to must be dates' }, { status: 400 });
+ }
+
+ try {
+ const view = await getPromptLocationsFor(auth, {
+ brandId,
+ locations: url.searchParams.get('locations')?.split(','),
+ days,
+ from,
+ to,
+ limit: number('limit'),
+ offset: number('offset'),
+ });
+ if (view === null) {
+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });
+ }
+ return NextResponse.json(view);
+ } catch (err) {
+ const message = err instanceof Error ? err.message : 'Failed';
+ return NextResponse.json({ error: message }, { status: 500 });
+ }
+}
diff --git a/web/src/lib/actions/prompt.test.ts b/web/src/lib/actions/prompt.test.ts
index f0b4d1ba7..f95dfd2ba 100644
--- a/web/src/lib/actions/prompt.test.ts
+++ b/web/src/lib/actions/prompt.test.ts
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { PLANS, type Plan } from '@/config/plans';
import { getPromptVolumes, type VolumeQuota } from '@/lib/actions/volumes';
import { getPromptVisibilitySummaries, type PromptVisibilitySummary } from '@/lib/actions/tracking';
+import { planFromOrgRow } from '@/lib/guards/plan-guard';
/**
* setPromptActive meters resuming like adding (00128): only active prompts
@@ -26,6 +27,10 @@ let positionsNull = false;
let jsonRpcMissing = false;
/** The position RPC calls, and whether any asked for a slice. */
let positionCalls: { fn: string; ranged: boolean }[] = [];
+/** The brand's organization, as its row embeds it for the Positions column's plan. */
+const ORG_ROW = { plan: 'growth', subscription_status: 'active', plan_overrides: null };
+/** When set, reading the brand's row fails with it. */
+let brandReadError: string | null = null;
/** When set, each heavy read takes a moment, counted while it runs. */
let slowReads: { running: number; most: number } | null = null;
/** The prompts a bulk location change reads, and what it writes back. */
@@ -46,6 +51,9 @@ vi.mock('@/lib/actions/tracking', () => ({ getPromptVisibilitySummaries: vi.fn()
vi.mock('@/lib/guards/plan-guard', () => ({
getOrgPlan: vi.fn(async () => plan),
+ // The Positions column reads the organization's plan from its brand's row.
+ ORG_PLAN_COLUMNS: 'plan, subscription_status, plan_overrides',
+ planFromOrgRow: vi.fn(() => plan),
}));
vi.mock('@/lib/supabase/server', () => ({
@@ -106,7 +114,10 @@ vi.mock('@/lib/supabase/server', () => ({
table === 'prompt_sets'
? { data: promptSetRows, error: null }
: { data: null, error: { message: `unexpected ${table}` } },
- maybeSingle: async () => ({ data: { organization_id: 'org-1' }, error: null }),
+ maybeSingle: async () =>
+ brandReadError
+ ? { data: null, error: { message: brandReadError } }
+ : { data: { organization_id: 'org-1', organizations: ORG_ROW }, error: null },
single: async () =>
promptRow
? {
@@ -283,6 +294,7 @@ describe('getPromptsPageData', () => {
beforeEach(() => {
plan = capped(50);
promptRow = null;
+ brandReadError = null;
promptSetRows = [
{
id: 'ps1',
@@ -337,6 +349,19 @@ describe('getPromptsPageData', () => {
expect(page.positions.p1.avg).toBe(2);
expect(page.positions.p1.dots.map((d) => d.id)).toEqual(['chatgpt-web']);
+ // The engines the plan includes, from the organization the brand's row embeds.
+ expect(planFromOrgRow).toHaveBeenCalledWith(ORG_ROW);
+ });
+
+ it('says when the brand’s plan could not be read, the column then reading —', async () => {
+ brandReadError = 'could not embed organizations';
+ const page = await getPromptsPageData('b1');
+
+ expect(page.positions.p1.avg).toBeNull();
+ expect(console.error).toHaveBeenCalledWith(
+ expect.stringContaining('brand plan read failed'),
+ 'could not embed organizations',
+ );
});
/** 1000 rows of other prompts, which come before p1's in the RPC's order. */
diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.ts
index 7286571fc..e5e477427 100644
--- a/web/src/lib/actions/prompt.ts
+++ b/web/src/lib/actions/prompt.ts
@@ -4,7 +4,8 @@ import { z } from 'zod';
import { createClient } from '@/lib/supabase/server';
import { revalidatePath } from 'next/cache';
import type { PromptSet, Prompt, AIPlatform, PromptVolume } from '@/types';
-import { getOrgPlan } from '@/lib/guards/plan-guard';
+import { ORG_PLAN_COLUMNS, getOrgPlan, planFromOrgRow } from '@/lib/guards/plan-guard';
+import { dbClient } from '@/lib/supabase/scoped';
import {
activationDelta,
getOrgLocationUsage,
@@ -1169,14 +1170,20 @@ async function getPositionRows(
async function includedPositionPlatforms(
brandId: string,
): Promise<{ id: string; label: string }[] | null> {
- const supabase = await createClient();
- const { data: brand } = await supabase
+ // dbClient: the member's session, or the service role the MCP's
+ // get_prompt_locations scopes it with (withDbClient), the brand checked.
+ const supabase = await dbClient();
+ const { data: brand, error } = await supabase
.from('brands')
- .select('organization_id')
+ .select(`organization_id, organizations!brands_organization_id_fkey(${ORG_PLAN_COLUMNS})`)
.eq('id', brandId)
.maybeSingle();
+ // The column then reads —: said here, so a broken read doesn't pass for no data.
+ if (error)
+ console.error('[prompts] brand plan read failed, positions without engines:', error.message);
if (!brand?.organization_id) return null;
- const plan = await getOrgPlan(brand.organization_id as string);
+ const org = Array.isArray(brand.organizations) ? brand.organizations[0] : brand.organizations;
+ const plan = planFromOrgRow(org ?? null);
return POSITION_PLATFORMS.filter((p) => platformAccess(plan, p.id).state === 'included').map(
(p) => ({ id: p.id as string, label: p.label as string }),
);
@@ -1254,7 +1261,7 @@ async function positionSums(
window: { from: string; to?: string },
region?: string,
): Promise<Map<string, PlatformPositionRow[]>> {
- const supabase = await createClient();
+ const supabase = await dbClient();
// One jsonb array (00153). A busy brand's 30 or 90 days come to thousands
// of prompt × platform rows, past PostgREST's 1000-row cap, which dropped
// the rest and left most prompts reading —; a single value isn't cut, so
diff --git a/web/src/lib/mcp/prompt-locations.test.ts b/web/src/lib/mcp/prompt-locations.test.ts
new file mode 100644
index 000000000..7a08c1a17
--- /dev/null
+++ b/web/src/lib/mcp/prompt-locations.test.ts
@@ -0,0 +1,190 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { McpAuthContext } from '@/lib/mcp-auth';
+
+/**
+ * get_prompt_locations (B7): the Locations view's matrix, read as the view
+ * reads it (getPromptLocationMatrix) under the service role once the brand
+ * is the key's, with its averages and cards, paged by prompt.
+ */
+
+const brandInOrg = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/mcp/data', () => ({ brandInOrg }));
+
+const getPromptLocationMatrix = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/actions/prompt', () => ({ getPromptLocationMatrix }));
+
+const scoped = vi.hoisted(() => ({ clients: [] as unknown[] }));
+vi.mock('@/lib/supabase/scoped', () => ({
+ withDbClient: (client: unknown, fn: () => unknown) => (scoped.clients.push(client), fn()),
+}));
+
+let promptRows: Record<string, unknown>[] = [];
+const adminClient = vi.hoisted(() => ({ marker: 'service role' }));
+vi.mock('@/lib/supabase/admin', () => ({
+ supabaseAdmin: Object.assign(adminClient, {
+ from: () => {
+ const chain = {
+ select: () => chain,
+ eq: () => chain,
+ order: () => chain,
+ range: async (start: number, end: number) => ({
+ data: promptRows.slice(start, end + 1),
+ error: null,
+ }),
+ };
+ return chain;
+ },
+ }),
+}));
+
+const { getPromptLocationsFor } = await import('./prompt-locations');
+
+const auth: McpAuthContext = {
+ userId: 'user-1',
+ email: null,
+ organizationId: 'org-1',
+ apiKeyId: 'key-1',
+ role: 'admin',
+};
+
+const cell = (score: number | null, over: Record<string, unknown> = {}) => ({
+ score,
+ mentions: 3,
+ citations: 1,
+ position: 2,
+ runs: 6,
+ ...over,
+});
+
+beforeEach(() => {
+ brandInOrg.mockReset().mockResolvedValue(true);
+ scoped.clients.length = 0;
+ promptRows = [
+ { id: 'p1', text: 'Best cold brew', regions: ['US', 'DE'], is_active: true },
+ { id: 'p2', text: 'Cold brew ratio', regions: ['US'], is_active: false },
+ ];
+ getPromptLocationMatrix.mockReset().mockResolvedValue({
+ p1: { US: cell(60), DE: cell(20) },
+ p2: { US: cell(40) },
+ });
+});
+
+describe('getPromptLocationsFor', () => {
+ it('reads the view’s matrix under the service role, the most tracked location first', async () => {
+ const view = (await getPromptLocationsFor(auth, { brandId: 'brand-1' }))!;
+ expect(scoped.clients).toEqual([adminClient]);
+ expect(getPromptLocationMatrix).toHaveBeenCalledWith('brand-1', {
+ days: 30,
+ from: undefined,
+ to: undefined,
+ regions: ['US', 'DE'],
+ });
+ expect(view.locations).toEqual([
+ { code: 'US', name: 'United States' },
+ { code: 'DE', name: 'Germany' },
+ ]);
+ expect(view.ignored_locations).toEqual([]);
+ expect(view.averages.visibility).toEqual([50, 20]);
+ // The cards in the MCP's own snake_case names.
+ expect(view.insights).toEqual({
+ weakest: { region: 'DE', average: 20, untracked: 1 },
+ strongest: { region: 'US', average: 50, tracked: 2 },
+ widest: {
+ prompt_id: 'p1',
+ text: 'Best cold brew',
+ low: 20,
+ low_at: 'DE',
+ high: 60,
+ high_at: 'US',
+ },
+ overall: 40,
+ });
+ expect(view.prompts).toEqual([
+ {
+ id: 'p1',
+ text: 'Best cold brew',
+ is_active: true,
+ tracked_in: ['US', 'DE'],
+ cells: {
+ US: { visibility: 60, mentions: 3, citations: 1, position: 2, runs: 6 },
+ DE: { visibility: 20, mentions: 3, citations: 1, position: 2, runs: 6 },
+ },
+ visibility_gap: 40,
+ },
+ {
+ id: 'p2',
+ text: 'Cold brew ratio',
+ is_active: false,
+ tracked_in: ['US'],
+ cells: { US: { visibility: 40, mentions: 3, citations: 1, position: 2, runs: 6 } },
+ visibility_gap: null,
+ },
+ ]);
+ expect(view.total).toBe(2);
+ expect(view.next_offset).toBeNull();
+ });
+
+ it('compares the locations asked, valid ones only, at most twelve, and says which it left out', async () => {
+ const view = (await getPromptLocationsFor(auth, {
+ brandId: 'brand-1',
+ locations: ['US-CA', 'nowhere', 'US-CA', 'TR', ...Array.from({ length: 11 }, () => 'DE')],
+ days: 7,
+ }))!;
+ expect(getPromptLocationMatrix.mock.calls[0][1]).toMatchObject({
+ days: 7,
+ regions: ['US-CA', 'TR', 'DE'],
+ });
+ expect(view.ignored_locations).toEqual(['nowhere']);
+
+ const many = ['US', 'DE', 'FR', 'GB', 'IT', 'ES', 'NL', 'SE', 'PL', 'TR', 'JP', 'BR', 'CA'];
+ const capped = (await getPromptLocationsFor(auth, { brandId: 'brand-1', locations: many }))!;
+ expect(capped.locations.map((l) => l.code)).toEqual(many.slice(0, 12));
+ expect(capped.ignored_locations).toEqual(['CA']);
+ });
+
+ it('reads a location code in any case, as the prompts keep it', async () => {
+ const view = (await getPromptLocationsFor(auth, {
+ brandId: 'brand-1',
+ locations: [' us ', 'de', 'US'],
+ }))!;
+ expect(getPromptLocationMatrix.mock.calls[0][1]).toMatchObject({ regions: ['US', 'DE'] });
+ expect(view.ignored_locations).toEqual([]);
+ expect(view.prompts[0]).toMatchObject({
+ tracked_in: ['US', 'DE'],
+ cells: { US: { visibility: 60 }, DE: { visibility: 20 } },
+ });
+ });
+
+ it('falls back to the most tracked when no code given names a location, and says so', async () => {
+ const view = (await getPromptLocationsFor(auth, { brandId: 'brand-1', locations: ['xx'] }))!;
+ expect(view.locations.map((l) => l.code)).toEqual(['US', 'DE']);
+ expect(view.ignored_locations).toEqual(['xx']);
+ });
+
+ it('pages the prompts, every location’s averages still over all of them', async () => {
+ const view = (await getPromptLocationsFor(auth, { brandId: 'brand-1', limit: 1 }))!;
+ expect(view.prompts.map((p) => p.id)).toEqual(['p1']);
+ expect(view.next_offset).toBe(1);
+ expect(view.averages.visibility).toEqual([50, 20]);
+ });
+
+ it('gives at most 100 prompts a page', async () => {
+ promptRows = Array.from({ length: 150 }, (_, i) => ({
+ id: `p${i}`,
+ text: `Prompt ${i}`,
+ regions: ['US'],
+ is_active: true,
+ }));
+ const view = (await getPromptLocationsFor(auth, { brandId: 'brand-1', limit: 500 }))!;
+ expect(view.prompts).toHaveLength(100);
+ expect(view.next_offset).toBe(100);
+ expect(view.total).toBe(150);
+ });
+
+ it("answers null for another organization's brand, without reading it", async () => {
+ brandInOrg.mockResolvedValue(false);
+ expect(await getPromptLocationsFor(auth, { brandId: 'brand-2' })).toBeNull();
+ expect(getPromptLocationMatrix).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/lib/mcp/prompt-locations.ts b/web/src/lib/mcp/prompt-locations.ts
new file mode 100644
index 000000000..830015a3e
--- /dev/null
+++ b/web/src/lib/mcp/prompt-locations.ts
@@ -0,0 +1,201 @@
+import { supabaseAdmin } from '@/lib/supabase/admin';
+import { withDbClient, type dbClient } from '@/lib/supabase/scoped';
+import type { McpAuthContext } from '@/lib/mcp-auth';
+import { getPromptLocationMatrix } from '@/lib/actions/prompt';
+import {
+ LOCATION_METRICS,
+ MATRIX_REGIONS,
+ locationAverages,
+ matrixInsights,
+ matrixLocations,
+ metricValue,
+ rowGap,
+ type MatrixInsights,
+ type PromptLocationCell,
+} from '@/lib/prompt-location-matrix';
+import { isValidLocation, regionLabel } from '@/lib/region';
+import { brandInOrg } from './data';
+
+/**
+ * The Tracked Prompts Locations view (PROMPT-015b) for the MCP tool
+ * get_prompt_locations and its REST mirror (MCP plan B7): each tracked prompt
+ * in each location side by side, as the view reads it (getPromptLocationMatrix,
+ * run under the service role once the brand is the key's), with its averages
+ * and the three cards above it.
+ */
+
+/** One prompt in one location. */
+export interface McpLocationCell {
+ /** AI Visibility Score, 0–100; null without answers. */
+ visibility: number | null;
+ mentions: number;
+ citations: number;
+ /** Average position the brand is named at; null when never named. */
+ position: number | null;
+ runs: number;
+}
+
+/** The view's cards, on visibility. */
+export interface McpLocationInsights {
+ /** The location with the lowest average, and how many prompts don't track it. */
+ weakest: { region: string; average: number; untracked: number } | null;
+ /** The location with the highest average, and how many prompts track it. */
+ strongest: { region: string; average: number; tracked: number } | null;
+ /** The prompt whose visibility differs most between locations. */
+ widest: {
+ prompt_id: string;
+ text: string;
+ low: number;
+ low_at: string;
+ high: number;
+ high_at: string;
+ } | null;
+ /** Visibility across every location. */
+ overall: number | null;
+}
+
+export interface McpPromptLocations {
+ window: { from: string; to: string | null };
+ /** The locations compared: country, US state or city codes, with their names. */
+ locations: { code: string; name: string }[];
+ /** The `locations` given that aren't compared: no location's code, or past the twelfth. */
+ ignored_locations: string[];
+ /** Each metric's average per location, over the prompts with a value there (in `locations` order). */
+ averages: Record<string, (number | null)[]>;
+ /** The weakest and strongest location by visibility, and the prompt that differs most between them. */
+ insights: McpLocationInsights;
+ /** The brand's tracked prompts. */
+ total: number;
+ prompts: {
+ id: string;
+ text: string;
+ is_active: boolean;
+ /** The compared locations it tracks. */
+ tracked_in: string[];
+ /** By location code: its figures there; a location it has no answers in is left out. */
+ cells: Record<string, McpLocationCell>;
+ /** Best minus worst location's visibility; null with fewer than two. */
+ visibility_gap: number | null;
+ }[];
+ /** The offset of the next page of prompts; null on the last. */
+ next_offset: number | null;
+}
+
+const PROMPTS_DEFAULT = 50;
+const PROMPT_PAGE = 1000;
+const PROMPTS_MAX = 100;
+
+function mcpInsights(insights: MatrixInsights): McpLocationInsights {
+ const { widest } = insights;
+ return {
+ weakest: insights.weakest,
+ strongest: insights.strongest,
+ widest: widest && {
+ prompt_id: widest.promptId,
+ text: widest.text,
+ low: widest.low,
+ low_at: widest.lowAt,
+ high: widest.high,
+ high_at: widest.highAt,
+ },
+ overall: insights.overall,
+ };
+}
+
+function mcpCell(cell: PromptLocationCell): McpLocationCell {
+ return {
+ visibility: cell.score,
+ mentions: cell.mentions,
+ citations: cell.citations,
+ position: cell.position,
+ runs: cell.runs,
+ };
+}
+
+/**
+ * The brand's prompts across its locations over `days` (or `from`–`to`):
+ * the locations given (at most 12, any case), else those its prompts track,
+ * the most tracked first. Null for a brand outside the key's organization.
+ */
+export async function getPromptLocationsFor(
+ auth: McpAuthContext,
+ params: {
+ brandId: string;
+ days?: number;
+ from?: string;
+ to?: string;
+ locations?: string[];
+ limit?: number;
+ offset?: number;
+ },
+): Promise<McpPromptLocations | null> {
+ if (!(await brandInOrg(auth, params.brandId))) return null;
+
+ // Every prompt, a page at a time: PostgREST answers 1,000 rows at most.
+ const rows: Record<string, unknown>[] = [];
+ for (let start = 0; ; start += PROMPT_PAGE) {
+ const { data, error } = await supabaseAdmin
+ .from('prompts')
+ .select('id, text, regions, is_active, created_at, prompt_sets!inner(brand_id)')
+ .eq('prompt_sets.brand_id', params.brandId)
+ .order('created_at', { ascending: false })
+ .order('id')
+ .range(start, start + PROMPT_PAGE - 1);
+ if (error) throw new Error(error.message);
+ rows.push(...((data ?? []) as Record<string, unknown>[]));
+ if ((data ?? []).length < PROMPT_PAGE) break;
+ }
+ const prompts = rows.map((p) => ({
+ id: p.id as string,
+ text: p.text as string,
+ regions: ((p.regions as string[] | null) ?? []).filter(isValidLocation),
+ isActive: p.is_active !== false,
+ }));
+
+ // Codes as the prompts keep them: `de` or ` US-CA` name DE and US-CA.
+ const given = (params.locations ?? []).map((code) => code.trim()).filter(Boolean);
+ const valid = [...new Set(given.map((code) => code.toUpperCase()).filter(isValidLocation))];
+ const regions = valid.length ? valid.slice(0, MATRIX_REGIONS) : matrixLocations(prompts);
+ const ignored = [...new Set(given.filter((code) => !regions.includes(code.toUpperCase())))];
+ const days = params.days ?? 30;
+ const from = params.from ?? new Date(Date.now() - days * 86_400_000).toISOString();
+ const matrix = regions.length
+ ? await withDbClient(supabaseAdmin as unknown as Awaited<ReturnType<typeof dbClient>>, () =>
+ getPromptLocationMatrix(params.brandId, {
+ days,
+ from: params.from,
+ to: params.to,
+ regions,
+ }),
+ )
+ : {};
+
+ const ids = prompts.map((p) => p.id);
+ const limit = Math.min(Math.max(params.limit ?? PROMPTS_DEFAULT, 1), PROMPTS_MAX);
+ const offset = Math.max(params.offset ?? 0, 0);
+ const page = prompts.slice(offset, offset + limit);
+ return {
+ window: { from, to: params.to ?? null },
+ locations: regions.map((code) => ({ code, name: regionLabel(code) })),
+ ignored_locations: ignored,
+ averages: Object.fromEntries(
+ LOCATION_METRICS.map((metric) => [metric, locationAverages(matrix, ids, regions, metric)]),
+ ),
+ insights: mcpInsights(matrixInsights(matrix, prompts, regions)),
+ total: prompts.length,
+ prompts: page.map((p) => {
+ const cells = matrix[p.id] ?? {};
+ return {
+ id: p.id,
+ text: p.text,
+ is_active: p.isActive,
+ tracked_in: regions.filter((r) => p.regions.includes(r)),
+ cells: Object.fromEntries(
+ regions.filter((r) => cells[r]).map((r) => [r, mcpCell(cells[r])]),
+ ),
+ visibility_gap: rowGap(regions.map((r) => metricValue(cells[r], 'visibility'))),
+ };
+ }),
+ next_offset: offset + page.length < prompts.length ? offset + page.length : null,
+ };
+}
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index 512dcfb7d..7c02fc444 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -89,6 +89,7 @@ import {
getShoppingReadinessFor,
getShoppingShelfFor,
} from './product-visibility';
+import { getPromptLocationsFor } from './prompt-locations';
/**
* Build a fresh MCP server bound to a single authenticated request.
@@ -2068,5 +2069,55 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
),
);
+ // ─── Prompts across locations (B7): the Tracked Prompts Locations view ───
+
+ server.registerTool(
+ 'get_prompt_locations',
+ {
+ title: 'Prompts across locations',
+ description:
+ "Each tracked prompt in each location side by side, as Tracked Prompts' Locations view shows it: per prompt and location (a country, a US state such as US-CA, or a city such as TR~ISTANBUL) its AI Visibility Score (0–100), mentions, citations, average position and runs over the window; `tracked_in` (the compared locations it tracks; one it doesn't track has no cells there) and `visibility_gap` (best minus worst location). Also each metric's average per location and the view's cards (`insights`: the weakest location with how many prompts don't track it, the strongest, the prompt whose visibility differs most, and visibility across all of them). Compares the `locations` given (at most 12, any case), else those the prompts track, the most tracked first; `ignored_locations` lists the codes given that name no location. Over `days` (7, 30 default, 90) or `date_from`/`date_to`. Paged by prompt: `limit` (default 50, max 100) and `offset`.",
+ inputSchema: {
+ brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),
+ locations: z
+ .array(z.string().max(60))
+ .max(12)
+ .optional()
+ .describe(
+ 'Location codes to compare (DE, US-CA, TR~ISTANBUL…); the most tracked when absent.',
+ ),
+ days: z
+ .union([z.literal(7), z.literal(30), z.literal(90)])
+ .optional()
+ .describe('The window: the last 7, 30 (default) or 90 days.'),
+ date_from: z
+ .string()
+ .refine((value) => Number.isFinite(Date.parse(value)), 'Not a date')
+ .optional()
+ .describe('ISO timestamp (inclusive) lower bound; wins over days.'),
+ date_to: z
+ .string()
+ .refine((value) => Number.isFinite(Date.parse(value)), 'Not a date')
+ .optional()
+ .describe('ISO timestamp (inclusive) upper bound.'),
+ limit: z.number().int().min(1).max(100).optional().describe('Prompts a page (default 50).'),
+ offset: z.number().int().min(0).optional().describe('Where the page starts (default 0).'),
+ },
+ annotations: { readOnlyHint: true, openWorldHint: false },
+ },
+ async (args) => {
+ const view = await getPromptLocationsFor(auth, {
+ brandId: args.brand_id,
+ locations: args.locations,
+ days: args.days,
+ from: args.date_from,
+ to: args.date_to,
+ limit: args.limit,
+ offset: args.offset,
+ });
+ return view ? json(view) : notFound('Brand');
+ },
+ );
+
return server;
}
diff --git a/web/src/lib/mcp/subscription-gate.test.ts b/web/src/lib/mcp/subscription-gate.test.ts
index 50a224090..65e711b70 100644
--- a/web/src/lib/mcp/subscription-gate.test.ts
+++ b/web/src/lib/mcp/subscription-gate.test.ts
@@ -79,7 +79,7 @@ describe('the MCP tools on a read-only workspace', () => {
const client = await connect();
const { tools } = await client.listTools();
const names = tools.map((tool) => tool.name);
- expect(names.filter(isReadTool)).toHaveLength(45);
+ expect(names.filter(isReadTool)).toHaveLength(46);
expect(names.filter((name) => !isReadTool(name)).sort()).toEqual([
'accept_prompt_suggestion',
'accept_topic_suggestion',