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.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
fix(mcp): gate the shopping reads on the plan's shopping analytics (#1764)
Cihanca64e057d328
diff --git a/docs/api-reference/metrics.mdx b/docs/api-reference/metrics.mdxindex 0fa2c07ca..4e24390b9 100644--- a/docs/api-reference/metrics.mdx+++ b/docs/api-reference/metrics.mdx@@ -128,6 +128,8 @@ GET /api/v1/shopping-cards?brand_id=<uuid>&role=own&limit=50Normalized shopping-card rows (product title, brand, price, merchant, rating, position) captured from AI shopping surfaces. `role` filters to `own`, `competitor` or `other` matches; cursor-paginated via `limit` (default 50, max 200) and the returned `next_cursor`.+Shopping analytics comes with the Growth plan and above. On Starter the endpoint answers `403` with `{ "error": "plan_limit", "message": "…" }`.+## Using it from Looker StudioUntil a native Community Connector ships, any generic JSON/API connector (or a small Apps Script that calls these endpoints with `UrlFetchApp`) works: point it at `/api/v1/visibility-trend` with your key in the `Authorization` header and join on the `date` column. The endpoints are also what a future official connector will consume.diff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdxindex b9d899fb5..e282cb179 100644--- a/docs/guides/mcp-server.mdx+++ b/docs/guides/mcp-server.mdx@@ -336,6 +336,8 @@ The MCP never sends a page to a CMS: Ansvisor's own **Send to CMS** stays in the### Shopping+Shopping analytics comes with the Growth plan and above. On Starter these tools answer `plan_limit`.+| Tool | What it does | Writes || --- | --- | --- || `list_shopping_cards` | Shopping cards surfaced in AI commercial contexts; filter by role, platform, and region. | |diff --git a/web/src/app/api/mcp/product-visibility/route.ts b/web/src/app/api/mcp/product-visibility/route.tsindex 3d8776b61..c48b20dac 100644--- a/web/src/app/api/mcp/product-visibility/route.ts+++ b/web/src/app/api/mcp/product-visibility/route.ts@@ -1,7 +1,13 @@import { NextResponse } from 'next/server';import { authenticateMcpRequest } from '@/lib/mcp-auth';-import { getProductVisibility } from '@/lib/mcp/data';+import { NOT_IN_PLAN, SHOPPING_NOT_IN_PLAN, getProductVisibility } from '@/lib/mcp/data';+/**+ * GET /api/mcp/product-visibility+ *+ * Parallel REST surface for the `get_product_visibility` MCP tool. 403+ * plan_limit on a plan without shopping analytics (Starter).+ */export async function GET(req: Request) {const auth = await authenticateMcpRequest(req);if (auth instanceof NextResponse) return auth;@@ -22,6 +28,9 @@ export async function GET(req: Request) {brandId,productTitle,});+ if (result === NOT_IN_PLAN) {+ return NextResponse.json(SHOPPING_NOT_IN_PLAN, { status: 403 });+ }if (result === null) {return NextResponse.json({ error: 'Product or Brand not found' }, { status: 404 });}diff --git a/web/src/app/api/mcp/shopping-cards/route.ts b/web/src/app/api/mcp/shopping-cards/route.tsindex 588d2c045..a4ba83fbd 100644--- a/web/src/app/api/mcp/shopping-cards/route.ts+++ b/web/src/app/api/mcp/shopping-cards/route.ts@@ -1,7 +1,13 @@import { NextResponse } from 'next/server';import { authenticateMcpRequest } from '@/lib/mcp-auth';-import { listShoppingCards } from '@/lib/mcp/data';+import { NOT_IN_PLAN, SHOPPING_NOT_IN_PLAN, listShoppingCards } from '@/lib/mcp/data';+/**+ * GET /api/mcp/shopping-cards (and /api/v1/shopping-cards)+ *+ * Parallel REST surface for the `list_shopping_cards` MCP tool. 403+ * plan_limit on a plan without shopping analytics (Starter).+ */export async function GET(req: Request) {const auth = await authenticateMcpRequest(req);if (auth instanceof NextResponse) return auth;@@ -33,6 +39,9 @@ export async function GET(req: Request) {limit: Number.isFinite(limit) ? limit : undefined,cursor,});+ if (result === NOT_IN_PLAN) {+ return NextResponse.json(SHOPPING_NOT_IN_PLAN, { status: 403 });+ }if (result === null) {return NextResponse.json({ error: 'Brand not found' }, { status: 404 });}diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.tsindex 1372a6a4a..a9cd0b3c6 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -16,6 +16,7 @@ import { countTrafficLogs, scanTrafficLogs } from '@/lib/traffic-scan';import { computeAiVisibilityScore } from '@/lib/visibility-score';import { API_BASE_URL } from '@/config/api';import { ORG_PLAN_COLUMNS, planFromOrgRow, usagePlanFromOrgRow } from '@/lib/guards/plan-guard';+import { PLANS, type Feature, getMinimumPlanForFeature, hasFeature, isCloud } from '@/config/plans';import { assertSubscriptionActive } from '@/lib/mcp/subscription-gate';import { MEMBER_ROLES, requireManager, requireRole } from '@/lib/mcp/role-gate';import {@@ -2451,6 +2452,37 @@ export async function getPromptVolumesFor(// ── Shopping Cards ────────────────────────────────────────────────────────────+/** A read of a feature the organization's plan doesn't include. */+export const NOT_IN_PLAN = 'not_in_plan';++/**+ * What a shopping read answers without the feature, as the API's+ * requireFeature does: the tools' error text, and the REST routes' 403 body.+ */+export const SHOPPING_NOT_IN_PLAN = {+ error: 'plan_limit',+ message:+ `Shopping analytics comes with the ${PLANS[getMinimumPlanForFeature('shopping_analytics')].name} ` ++ "plan and above, and this workspace's plan doesn't include it. An admin can upgrade in " ++ 'Settings › Billing.',+} as const;++/**+ * Whether the organization's plan includes `feature`, for a read: once a plan+ * has ended (read-only), the plan it was on, as the dashboard and the API's+ * readOnly reads keep it. Self-hosted has every feature.+ */+async function planIncludes(organizationId: string, feature: Feature): Promise<boolean> {+ if (!isCloud()) return true;+ const { data, error } = await supabaseAdmin+ .from('organizations')+ .select(ORG_PLAN_COLUMNS)+ .eq('id', organizationId)+ .maybeSingle();+ if (error) throw new Error(error.message);+ return hasFeature(usagePlanFromOrgRow(data).plan, feature);+}+export interface ListShoppingCardsParams {brandId: string;role?: 'own' | 'competitor' | 'other';@@ -2487,10 +2519,11 @@ export interface ListShoppingCardsOutput {next_cursor: string | null;}+/** The brand's shopping cards: NOT_IN_PLAN on a plan without shopping analytics (Starter). */export async function listShoppingCards(auth: McpAuthContext,params: ListShoppingCardsParams,-): Promise<ListShoppingCardsOutput | null> {+): Promise<ListShoppingCardsOutput | typeof NOT_IN_PLAN | null> {if (!auth.organizationId) return null;// Brand ownership check@@ -2501,6 +2534,7 @@ export async function listShoppingCards(.eq('organization_id', auth.organizationId).maybeSingle();if (!brand) return null;+ if (!(await planIncludes(auth.organizationId, 'shopping_analytics'))) return NOT_IN_PLAN;const finalLimit = Math.min(Math.max(params.limit ?? 50, 1), 200);@@ -2570,10 +2604,11 @@ export interface ProductVisibilityOutput {merchant_domains: Array<{ domain: string; count: number }>;}+/** One product's visibility: NOT_IN_PLAN on a plan without shopping analytics (Starter). */export async function getProductVisibility(auth: McpAuthContext,params: { brandId: string; productTitle: string },-): Promise<ProductVisibilityOutput | null> {+): Promise<ProductVisibilityOutput | typeof NOT_IN_PLAN | null> {if (!auth.organizationId) return null;// Brand ownership check@@ -2584,6 +2619,7 @@ export async function getProductVisibility(.eq('organization_id', auth.organizationId).maybeSingle();if (!brand) return null;+ if (!(await planIncludes(auth.organizationId, 'shopping_analytics'))) return NOT_IN_PLAN;const { data: cards, error } = await supabaseAdmin.from('prompt_result_shopping_cards')diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex 333b73860..ec9c8f7c2 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -28,6 +28,8 @@ import {getPromptVolumesFor,listShoppingCards,getProductVisibility,+ NOT_IN_PLAN,+ SHOPPING_NOT_IN_PLAN,getPromptPerformanceFor,runSiteAuditFor,getSiteAuditFor,@@ -1003,7 +1005,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {'list_shopping_cards',{description:- 'List normalized shopping cards for a brand, showing which products are surfaced by AI engines in commercial-intent contexts. Supports filtering by matched brand role ("own" | "competitor" | "other"), platform, and region. Pagination is cursor-based (default limit 50, max 200). Use this to see which product brands, URLs, and prices are visible in search results.',+ 'List normalized shopping cards for a brand, showing which products are surfaced by AI engines in commercial-intent contexts. Supports filtering by matched brand role ("own" | "competitor" | "other"), platform, and region. Pagination is cursor-based (default limit 50, max 200). Use this to see which product brands, URLs, and prices are visible in search results. Needs a plan with shopping analytics (Growth and above): on Starter it answers plan_limit.',inputSchema: {brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),role: z@@ -1041,6 +1043,12 @@ export function createMcpServer(auth: McpAuthContext): McpServer {limit: args.limit,cursor: args.cursor,});+ if (result === NOT_IN_PLAN) {+ return {+ content: [{ type: 'text', text: JSON.stringify(SHOPPING_NOT_IN_PLAN, null, 2) }],+ isError: true,+ };+ }if (result === null) {return {content: [{ type: 'text', text: 'Brand not found' }],@@ -1057,7 +1065,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {'get_product_visibility',{description:- "Get aggregate visibility metrics for a specific product title across platforms, regions, and dates. Returns total appearances, platform breakdown, region breakdown, chronological trend of dates, average rating, total reviews, and associated merchant domains. Use this to audit a single product's performance and organic footprint in AI-driven shopping results.",+ "Get aggregate visibility metrics for a specific product title across platforms, regions, and dates. Returns total appearances, platform breakdown, region breakdown, chronological trend of dates, average rating, total reviews, and associated merchant domains. Use this to audit a single product's performance and organic footprint in AI-driven shopping results. Needs a plan with shopping analytics (Growth and above): on Starter it answers plan_limit.",inputSchema: {brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),product_title: z.string().describe('The product title/name to query.'),@@ -1068,6 +1076,12 @@ export function createMcpServer(auth: McpAuthContext): McpServer {brandId: args.brand_id,productTitle: args.product_title,});+ if (result === NOT_IN_PLAN) {+ return {+ content: [{ type: 'text', text: JSON.stringify(SHOPPING_NOT_IN_PLAN, null, 2) }],+ isError: true,+ };+ }if (result === null) {return {content: [{ type: 'text', text: 'Product or Brand not found' }],diff --git a/web/src/lib/mcp/shopping-plan.test.ts b/web/src/lib/mcp/shopping-plan.test.tsnew file mode 100644index 000000000..b73729cfb--- /dev/null+++ b/web/src/lib/mcp/shopping-plan.test.ts@@ -0,0 +1,169 @@+// @vitest-environment node+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * Shopping analytics is a Growth feature: over an API key, list_shopping_cards,+ * get_product_visibility and their REST routes (/api/v1/shopping-cards too)+ * answer plan_limit on Starter, as the Shopping page shows it locked, without+ * reading a card. A plan that has ended keeps reading what it had; self-hosted+ * has no gate.+ */++/** The organization's row, as the plan is read from it. */+let org: { plan: string; subscription_status: string; plan_overrides: null } | null;+/** The tables read, in order. */+const reads: string[] = [];++const CARD = {+ id: 'card-1',+ brand_id: 'b1',+ product_title: 'Trail Pack 30',+ platform: 'chatgpt-shopping',+ region: 'US',+ created_at: '2026-10-28T10:00:00Z',+ rating: 4.5,+ review_count: 120,+ merchant_domain: 'shop.example',+};++vi.mock('@/lib/supabase/admin', () => ({+ supabaseAdmin: {+ from: (table: string) => {+ reads.push(table);+ const answer = () => ({+ data: table === 'organizations' ? org : table === 'brands' ? { id: 'b1' } : [CARD],+ error: null,+ });+ const chain = {+ select: () => chain,+ eq: () => chain,+ order: () => chain,+ limit: () => chain,+ maybeSingle: async () => answer(),+ then: (resolve: (value: unknown) => void) => resolve(answer()),+ };+ return chain;+ },+ },+}));+vi.mock('@/lib/mcp-auth', () => ({+ authenticateMcpRequest: vi.fn(async () => ({+ userId: 'user-1',+ email: null,+ organizationId: 'org-1',+ apiKeyId: 'key-1',+ })),+}));++const { createMcpServer } = await import('./server');+const { GET: listCardsRoute } = await import('@/app/api/v1/shopping-cards/route');+const { GET: productRoute } = await import('@/app/api/mcp/product-visibility/route');++const BRAND = '11111111-2222-3333-4444-555555555555';++async function connect() {+ const server = createMcpServer({+ userId: 'user-1',+ email: null,+ organizationId: 'org-1',+ apiKeyId: 'key-1',+ role: 'admin',+ });+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();+ await server.connect(serverTransport);+ const client = new Client({ name: 'test', version: '1.0.0' });+ await client.connect(clientTransport);+ return client;+}++const text = (result: Awaited<ReturnType<Client['callTool']>>) =>+ (result.content as { text: string }[])[0].text;++/** Both shopping tools, called for the brand. */+async function callBoth(client: Client) {+ return Promise.all([+ client.callTool({ name: 'list_shopping_cards', arguments: { brand_id: BRAND } }),+ client.callTool({+ name: 'get_product_visibility',+ arguments: { brand_id: BRAND, product_title: 'Trail Pack 30' },+ }),+ ]);+}++const onPlan = (plan: string, subscription_status = 'active') => {+ org = { plan, subscription_status, plan_overrides: null };+};++beforeEach(() => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ reads.length = 0;+ onPlan('growth');+});++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('the shopping tools by plan', () => {+ it('answer plan_limit on Starter, without reading a card', async () => {+ onPlan('starter');+ const results = await callBoth(await connect());+ for (const result of results) {+ expect(result.isError).toBe(true);+ expect(JSON.parse(text(result))).toEqual({+ error: 'plan_limit',+ message:+ "Shopping analytics comes with the Growth plan and above, and this workspace's plan doesn't include it. An admin can upgrade in Settings › Billing.",+ });+ }+ expect(reads).not.toContain('prompt_result_shopping_cards');+ });++ it('answer on Growth', async () => {+ const [cards, product] = await callBoth(await connect());+ expect(cards.isError).toBeFalsy();+ expect(JSON.parse(text(cards)).cards).toEqual([CARD]);+ expect(product.isError).toBeFalsy();+ expect(JSON.parse(text(product))).toMatchObject({ total_appearances: 1 });+ });++ it('keep reading a Growth plan that has ended, as the read-only dashboard does', async () => {+ onPlan('growth', 'canceled');+ const [cards] = await callBoth(await connect());+ expect(cards.isError).toBeFalsy();+ });++ it('read no plan self-hosted', async () => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'false');+ org = null;+ const [cards] = await callBoth(await connect());+ expect(cards.isError).toBeFalsy();+ expect(reads).not.toContain('organizations');+ });+});++describe('the shopping REST routes by plan', () => {+ const listCards = () =>+ listCardsRoute(new Request(`http://localhost/api/v1/shopping-cards?brand_id=${BRAND}`));+ const product = () =>+ productRoute(+ new Request(+ `http://localhost/api/mcp/product-visibility?brand_id=${BRAND}&product_title=Trail%20Pack%2030`,+ ),+ );++ it('answer 403 plan_limit on Starter', async () => {+ onPlan('starter');+ for (const res of [await listCards(), await product()]) {+ expect(res.status).toBe(403);+ expect(await res.json()).toMatchObject({ error: 'plan_limit' });+ }+ });++ it('answer on Growth', async () => {+ expect((await listCards()).status).toBe(200);+ expect((await product()).status).toBe(200);+ });+});