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
feat(mcp): read Product Visibility's shelf, readiness and what AI says (#1733)
Cihanb3fc875c6f18
diff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdxindex e282cb179..ae18085c2 100644--- a/docs/guides/mcp-server.mdx+++ b/docs/guides/mcp-server.mdx@@ -220,7 +220,7 @@ instead.## Available tools-The MCP server exposes **55 tools**. Descriptions below match+The MCP server exposes **60 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 userintent, not during exploratory queries. A write that needs a particular role@@ -336,12 +336,21 @@ 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`.+Shopping analytics comes with the Growth plan and above. On Starter, `list_shopping_cards`, `get_product_visibility`, `get_shopping_shelf`, `get_shopping_readiness` and `get_product_ai_says` answer `plan_limit`; the catalog tools read on.| Tool | What it does | Writes || --- | --- | --- || `list_shopping_cards` | Shopping cards surfaced in AI commercial contexts; filter by role, platform, and region. | || `get_product_visibility` | Aggregate visibility for one product title across platforms, regions, and dates. | |+| `get_catalog_sources` | Where the product catalog is read from (feed URLs, uploads, connected stores such as Shopify or Google Merchant Center) and how each last sync went: status, error, what it read and its products in the catalog now. | |+| `list_catalog_products` | The live catalog products, by title, as Product Visibility reads them: price, stock, GTIN, `readiness` for AI shopping (`score` 0–100, the checks `missing`, and the `unknown` ones that can't be made), Merchant Center issues by severity (each issue once per product), and the AI visits, orders and revenue (`revenue_30d`) their pages brought over 30 days. Optional `search`; paged with `limit` (max 200) and `offset`. | |+| `get_shopping_shelf` | Product Visibility's Shelf: for each shopping question and AI channel, the first 10 products the latest answer showed, in order (`products_total` counts them all), the brand's best place on it (`own_rank`) and its last 7 days there; on a shelf the brand isn't on, `why_not_you` names its catalog product the question asks for most, with its readiness. Optional `period` (7d, 30d, 90d, all), `platform`, `market` (us, europe), `absent_only`; paged with `limit` (default 10, max 50) and `offset`. | |+| `get_shopping_readiness` | Product Visibility's Readiness: the checklist scored 0–100, each check's state (pass, warn, fail, unknown), its text as the page writes it and where its fix starts, and each AI channel's state (showing, notShowing, notTracked). Optional `period` and `market`. | |+| `get_product_ai_says` | What AI says about one catalog product: how many answers showed it, up to 5 quotes where they name it, and the pages they cited most. Optional `period`. | |++The catalog is also available over REST: `GET /api/mcp/catalog/sources?brand_id=<brand_id>` and `GET /api/mcp/catalog/products?brand_id=<brand_id>&search=<text>&limit=50&offset=0` (`search` optional).++The Shelf, Readiness and What AI says need a plan with Product Visibility (Growth or Enterprise), as on the page, which a workspace whose trial or subscription ended still reads; on another plan they answer `plan_limit`, as `list_shopping_cards` does (REST: 403 with the same body). Over REST: `GET /api/mcp/product-visibility/shelf?brand_id=<brand_id>&period=30d&platform=<id>&market=us&absent_only=true&limit=10&offset=0`, `GET /api/mcp/product-visibility/readiness?brand_id=<brand_id>&period=30d&market=us` and `GET /api/mcp/product-visibility/ai-says?brand_id=<brand_id>&product_id=<product_id>&period=30d` (all but the IDs optional).### Action Centerdiff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_readiness.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_readiness.tsxindex c7db7dc93..00151a447 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_readiness.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_readiness.tsx@@ -10,11 +10,11 @@ import { Skeleton } from '@/components/ui/skeleton';import { AIProviderAvatar, resolveAIProvider } from '@/components/ai-provider-avatar';import { PLATFORM_LABELS } from '@/config/platform-labels';import { CATALOG_SETTINGS_PATH } from '@/lib/content/feed-match';-import { priceText } from '@/lib/shopping/price';import type { ShoppingMarket } from '@/lib/shopping/markets';import {READINESS_CHANNELS,channelState,+ copyValues,type CheckState,type ReadinessItem,} from '@/lib/shopping/readiness';@@ -33,17 +33,6 @@ const CHANNEL_TONE = {notTracked: 'bg-muted text-muted-foreground',} as const;-/** The values a check's copy reads, prices written as prices. */-function copyValues(item: ReadinessItem): Record<string, string | number> {- const values = { ...(item.values ?? {}) };- if (item.key === 'wrongPrice' && typeof values.seen === 'number') {- const currency = String(values.currency ?? 'USD');- values.seen = priceText(Number(values.seen), currency);- values.yours = priceText(Number(values.yours), currency);- }- return values;-}-/** What the checklist reads that may fail: the catalog sources, and the catalog's products. */export type ReadinessRead = 'sources' | 'products';diff --git a/web/src/app/api/mcp/catalog/products/route.test.ts b/web/src/app/api/mcp/catalog/products/route.test.tsnew file mode 100644index 000000000..c09add983--- /dev/null+++ b/web/src/app/api/mcp/catalog/products/route.test.ts@@ -0,0 +1,61 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++/** GET /api/mcp/catalog/products: the REST mirror of list_catalog_products. */++const { listCatalogProductsFor } = vi.hoisted(() => ({ listCatalogProductsFor: 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/catalog', () => ({ listCatalogProductsFor }));++const { GET } = await import('./route');++const get = (query: string) =>+ GET(new Request(`http://localhost/api/mcp/catalog/products${query}`));++beforeEach(() => {+ listCatalogProductsFor.mockReset();+});++describe('GET /api/mcp/catalog/products', () => {+ it('reads the page and search asked', async () => {+ listCatalogProductsFor.mockResolvedValue({ total: 0, products: [], next_offset: null });+ const res = await get('?brand_id=brand-1&search=trail%20boots&limit=20&offset=40');+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ total: 0, products: [], next_offset: null });+ expect(listCatalogProductsFor).toHaveBeenCalledWith(expect.anything(), {+ brandId: 'brand-1',+ search: 'trail boots',+ limit: 20,+ offset: 40,+ });+ });++ it('leaves out a limit or offset that is not a number, and cuts a long search', async () => {+ listCatalogProductsFor.mockResolvedValue({ total: 0, products: [], next_offset: null });+ await get(`?brand_id=brand-1&limit=many&search=${'a'.repeat(300)}`);+ expect(listCatalogProductsFor).toHaveBeenCalledWith(expect.anything(), {+ brandId: 'brand-1',+ search: 'a'.repeat(200),+ limit: undefined,+ offset: undefined,+ });+ });++ it('asks for a brand, answers 404 for another organization’s and 500 on a failed read', async () => {+ expect((await get('')).status).toBe(400);+ expect(listCatalogProductsFor).not.toHaveBeenCalled();+ listCatalogProductsFor.mockResolvedValue(null);+ expect((await get('?brand_id=brand-2')).status).toBe(404);+ listCatalogProductsFor.mockRejectedValue(new Error('timeout'));+ const res = await get('?brand_id=brand-1');+ expect(res.status).toBe(500);+ expect(await res.json()).toEqual({ error: 'timeout' });+ });+});diff --git a/web/src/app/api/mcp/catalog/products/route.ts b/web/src/app/api/mcp/catalog/products/route.tsnew file mode 100644index 000000000..218674b3a--- /dev/null+++ b/web/src/app/api/mcp/catalog/products/route.ts@@ -0,0 +1,36 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { listCatalogProductsFor } from '@/lib/mcp/catalog';++/** GET /api/mcp/catalog/products — REST mirror of the `list_catalog_products` MCP tool. */+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;+ };++ try {+ const page = await listCatalogProductsFor(auth, {+ brandId,+ search: url.searchParams.get('search')?.slice(0, 200) ?? undefined,+ limit: number('limit'),+ offset: number('offset'),+ });+ if (page === null) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });+ }+ return NextResponse.json(page);+ } 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/catalog/sources/route.test.ts b/web/src/app/api/mcp/catalog/sources/route.test.tsnew file mode 100644index 000000000..3b45a16e0--- /dev/null+++ b/web/src/app/api/mcp/catalog/sources/route.test.ts@@ -0,0 +1,42 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++/** GET /api/mcp/catalog/sources: the REST mirror of get_catalog_sources. */++const { getCatalogSourcesFor } = vi.hoisted(() => ({ getCatalogSourcesFor: 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/catalog', () => ({ getCatalogSourcesFor }));++const { GET } = await import('./route');++const get = (query: string) => GET(new Request(`http://localhost/api/mcp/catalog/sources${query}`));++beforeEach(() => {+ getCatalogSourcesFor.mockReset();+});++describe('GET /api/mcp/catalog/sources', () => {+ it("gives the brand's sources", async () => {+ getCatalogSourcesFor.mockResolvedValue([{ id: 's1', kind: 'feed_url', products: 12 }]);+ const res = await get('?brand_id=brand-1');+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ sources: [{ id: 's1', kind: 'feed_url', products: 12 }] });+ expect(getCatalogSourcesFor).toHaveBeenCalledWith(expect.anything(), 'brand-1');+ });++ it('asks for a brand, answers 404 for another organization’s and 500 on a failed read', async () => {+ expect((await get('')).status).toBe(400);+ expect(getCatalogSourcesFor).not.toHaveBeenCalled();+ getCatalogSourcesFor.mockResolvedValue(null);+ expect((await get('?brand_id=brand-2')).status).toBe(404);+ getCatalogSourcesFor.mockRejectedValue(new Error('timeout'));+ expect((await get('?brand_id=brand-1')).status).toBe(500);+ });+});diff --git a/web/src/app/api/mcp/catalog/sources/route.ts b/web/src/app/api/mcp/catalog/sources/route.tsnew file mode 100644index 000000000..61f5d54bb--- /dev/null+++ b/web/src/app/api/mcp/catalog/sources/route.ts@@ -0,0 +1,24 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { getCatalogSourcesFor } from '@/lib/mcp/catalog';++/** GET /api/mcp/catalog/sources — REST mirror of the `get_catalog_sources` MCP tool. */+export async function GET(req: Request) {+ const auth = await authenticateMcpRequest(req);+ if (auth instanceof NextResponse) return auth;++ const brandId = new URL(req.url).searchParams.get('brand_id');+ if (!brandId) {+ return NextResponse.json({ error: 'brand_id is required' }, { status: 400 });+ }+ try {+ const sources = await getCatalogSourcesFor(auth, brandId);+ if (sources === null) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });+ }+ return NextResponse.json({ sources });+ } 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/product-visibility/ai-says/route.test.ts b/web/src/app/api/mcp/product-visibility/ai-says/route.test.tsnew file mode 100644index 000000000..436a28168--- /dev/null+++ b/web/src/app/api/mcp/product-visibility/ai-says/route.test.ts@@ -0,0 +1,64 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++/** GET /api/mcp/product-visibility/ai-says: the REST mirror of get_product_ai_says. */++const { getProductAiSaysFor } = vi.hoisted(() => ({ getProductAiSaysFor: vi.fn() }));+vi.mock('@/lib/mcp-auth', () => ({+ authenticateMcpRequest: vi.fn(async () => ({+ userId: 'user-1',+ email: null,+ organizationId: 'org-1',+ apiKeyId: 'key-1',+ role: 'admin',+ })),+}));+// The read and the periods are the test's; the plan answer is lib/mcp/data's own (no+// database is read).+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));+vi.mock('@/lib/mcp/product-visibility', () => ({+ getProductAiSaysFor,+ PV_PERIODS: ['7d', '30d', '90d', 'all'],+}));++const { GET } = await import('./route');+const { NOT_IN_PLAN, SHOPPING_NOT_IN_PLAN } = await import('@/lib/mcp/data');++const get = (query: string) =>+ GET(new Request(`http://localhost/api/mcp/product-visibility/ai-says${query}`));++beforeEach(() => {+ getProductAiSaysFor.mockReset();+});++const PRODUCT = '22222222-2222-2222-2222-222222222222';++describe('GET /api/mcp/product-visibility/ai-says', () => {+ it('gives what AI says about the product', async () => {+ getProductAiSaysFor.mockResolvedValue({ product_id: PRODUCT, answers: 2, quotes: [] });+ const res = await get(`?brand_id=brand-1&product_id=${PRODUCT}&period=all`);+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ product_id: PRODUCT, answers: 2, quotes: [] });+ expect(getProductAiSaysFor).toHaveBeenCalledWith(expect.anything(), {+ brandId: 'brand-1',+ productId: PRODUCT,+ period: 'all',+ });+ });++ it('asks for a brand and a product UUID, answers 404, 403 and 500', async () => {+ expect((await get('?brand_id=brand-1')).status).toBe(400);+ expect((await get('?brand_id=brand-1&product_id=p1')).status).toBe(400);+ expect(getProductAiSaysFor).not.toHaveBeenCalled();+ getProductAiSaysFor.mockResolvedValue(null);+ const missing = await get(`?brand_id=brand-1&product_id=${PRODUCT}`);+ expect(missing.status).toBe(404);+ expect(await missing.json()).toEqual({ error: 'Brand or product not found' });+ getProductAiSaysFor.mockResolvedValue(NOT_IN_PLAN);+ const locked = await get(`?brand_id=brand-1&product_id=${PRODUCT}`);+ expect(locked.status).toBe(403);+ expect(await locked.json()).toEqual(SHOPPING_NOT_IN_PLAN);+ getProductAiSaysFor.mockRejectedValue(new Error('timeout'));+ expect((await get(`?brand_id=brand-1&product_id=${PRODUCT}`)).status).toBe(500);+ });+});diff --git a/web/src/app/api/mcp/product-visibility/ai-says/route.ts b/web/src/app/api/mcp/product-visibility/ai-says/route.tsnew file mode 100644index 000000000..b8e086597--- /dev/null+++ b/web/src/app/api/mcp/product-visibility/ai-says/route.ts@@ -0,0 +1,34 @@+import { NextResponse } from 'next/server';+import { z } from 'zod';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { NOT_IN_PLAN, SHOPPING_NOT_IN_PLAN } from '@/lib/mcp/data';+import { PV_PERIODS, getProductAiSaysFor } from '@/lib/mcp/product-visibility';++/** GET /api/mcp/product-visibility/ai-says — REST mirror of the `get_product_ai_says` MCP tool. */+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');+ const productId = url.searchParams.get('product_id');+ if (!brandId || !productId) {+ return NextResponse.json({ error: 'brand_id and product_id are required' }, { status: 400 });+ }+ if (!z.guid().safeParse(productId).success) {+ return NextResponse.json({ error: 'product_id must be a UUID' }, { status: 400 });+ }+ const period = PV_PERIODS.find((p) => p === url.searchParams.get('period'));++ try {+ const read = await getProductAiSaysFor(auth, { brandId, productId, period });+ if (read === null) {+ return NextResponse.json({ error: 'Brand or product not found' }, { status: 404 });+ }+ if (read === NOT_IN_PLAN) return NextResponse.json(SHOPPING_NOT_IN_PLAN, { status: 403 });+ return NextResponse.json(read);+ } 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/product-visibility/readiness/route.test.ts b/web/src/app/api/mcp/product-visibility/readiness/route.test.tsnew file mode 100644index 000000000..ff48670f9--- /dev/null+++ b/web/src/app/api/mcp/product-visibility/readiness/route.test.ts@@ -0,0 +1,58 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++/** GET /api/mcp/product-visibility/readiness: the REST mirror of get_shopping_readiness. */++const { getShoppingReadinessFor } = vi.hoisted(() => ({ getShoppingReadinessFor: vi.fn() }));+vi.mock('@/lib/mcp-auth', () => ({+ authenticateMcpRequest: vi.fn(async () => ({+ userId: 'user-1',+ email: null,+ organizationId: 'org-1',+ apiKeyId: 'key-1',+ role: 'admin',+ })),+}));+// The read and the periods are the test's; the plan answer is lib/mcp/data's own (no+// database is read).+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));+vi.mock('@/lib/mcp/product-visibility', () => ({+ getShoppingReadinessFor,+ PV_PERIODS: ['7d', '30d', '90d', 'all'],+}));++const { GET } = await import('./route');+const { NOT_IN_PLAN, SHOPPING_NOT_IN_PLAN } = await import('@/lib/mcp/data');++const get = (query: string) =>+ GET(new Request(`http://localhost/api/mcp/product-visibility/readiness${query}`));++beforeEach(() => {+ getShoppingReadinessFor.mockReset();+});++describe('GET /api/mcp/product-visibility/readiness', () => {+ it("gives the brand's readiness", async () => {+ getShoppingReadinessFor.mockResolvedValue({ market: 'us', score: 70, checks: [] });+ const res = await get('?brand_id=brand-1&period=90d&market=us');+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ market: 'us', score: 70, checks: [] });+ expect(getShoppingReadinessFor).toHaveBeenCalledWith(expect.anything(), {+ brandId: 'brand-1',+ period: '90d',+ market: 'us',+ });+ });++ it('asks for a brand, answers 404, 403 without Product Visibility, and 500 on a failed read', async () => {+ expect((await get('')).status).toBe(400);+ getShoppingReadinessFor.mockResolvedValue(null);+ expect((await get('?brand_id=brand-2')).status).toBe(404);+ getShoppingReadinessFor.mockResolvedValue(NOT_IN_PLAN);+ const locked = await get('?brand_id=brand-1');+ expect(locked.status).toBe(403);+ expect(await locked.json()).toEqual(SHOPPING_NOT_IN_PLAN);+ getShoppingReadinessFor.mockRejectedValue(new Error('timeout'));+ expect((await get('?brand_id=brand-1')).status).toBe(500);+ });+});diff --git a/web/src/app/api/mcp/product-visibility/readiness/route.ts b/web/src/app/api/mcp/product-visibility/readiness/route.tsnew file mode 100644index 000000000..71b9fbc91--- /dev/null+++ b/web/src/app/api/mcp/product-visibility/readiness/route.ts@@ -0,0 +1,32 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { NOT_IN_PLAN, SHOPPING_NOT_IN_PLAN } from '@/lib/mcp/data';+import { PV_PERIODS, getShoppingReadinessFor } from '@/lib/mcp/product-visibility';+import { isShoppingMarket } from '@/lib/shopping/markets';++/** GET /api/mcp/product-visibility/readiness — REST mirror of the `get_shopping_readiness` MCP tool. */+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 period = PV_PERIODS.find((p) => p === url.searchParams.get('period'));+ const marketParam = url.searchParams.get('market');+ const market = isShoppingMarket(marketParam) ? marketParam : undefined;++ try {+ const read = await getShoppingReadinessFor(auth, { brandId, period, market });+ if (read === null) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });+ }+ if (read === NOT_IN_PLAN) return NextResponse.json(SHOPPING_NOT_IN_PLAN, { status: 403 });+ return NextResponse.json(read);+ } 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/product-visibility/shelf/route.test.ts b/web/src/app/api/mcp/product-visibility/shelf/route.test.tsnew file mode 100644index 000000000..5557f727d--- /dev/null+++ b/web/src/app/api/mcp/product-visibility/shelf/route.test.ts@@ -0,0 +1,81 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++/** GET /api/mcp/product-visibility/shelf: the REST mirror of get_shopping_shelf. */++const { getShoppingShelfFor } = vi.hoisted(() => ({ getShoppingShelfFor: vi.fn() }));+vi.mock('@/lib/mcp-auth', () => ({+ authenticateMcpRequest: vi.fn(async () => ({+ userId: 'user-1',+ email: null,+ organizationId: 'org-1',+ apiKeyId: 'key-1',+ role: 'admin',+ })),+}));+// The read and the periods are the test's; the plan answer is lib/mcp/data's own (no+// database is read).+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));+vi.mock('@/lib/mcp/product-visibility', () => ({+ getShoppingShelfFor,+ PV_PERIODS: ['7d', '30d', '90d', 'all'],+}));++const { GET } = await import('./route');+const { NOT_IN_PLAN, SHOPPING_NOT_IN_PLAN } = await import('@/lib/mcp/data');++const get = (query: string) =>+ GET(new Request(`http://localhost/api/mcp/product-visibility/shelf${query}`));++beforeEach(() => {+ getShoppingShelfFor.mockReset();+});++describe('GET /api/mcp/product-visibility/shelf', () => {+ it('gives a page of the shelves, with what was asked', async () => {+ getShoppingShelfFor.mockResolvedValue({ total: 1, shelves: [{ prompt_id: 'q1' }] });+ const res = await get(+ '?brand_id=brand-1&period=7d&platform=chatgpt-shopping&market=europe&absent_only=true&limit=10&offset=20',+ );+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ total: 1, shelves: [{ prompt_id: 'q1' }] });+ expect(getShoppingShelfFor).toHaveBeenCalledWith(expect.anything(), {+ brandId: 'brand-1',+ period: '7d',+ platform: 'chatgpt-shopping',+ market: 'europe',+ absentOnly: true,+ limit: 10,+ offset: 20,+ });+ });++ it('leaves an unknown period or market to the defaults', async () => {+ getShoppingShelfFor.mockResolvedValue({ total: 0, shelves: [] });+ await get('?brand_id=brand-1&period=1y&market=asia&limit=x');+ expect(getShoppingShelfFor).toHaveBeenCalledWith(expect.anything(), {+ brandId: 'brand-1',+ period: undefined,+ platform: undefined,+ market: undefined,+ absentOnly: false,+ limit: undefined,+ offset: undefined,+ });+ });++ it('asks for a brand, answers 404, 403 without Product Visibility, and 500 on a failed read', async () => {+ expect((await get('')).status).toBe(400);+ expect(getShoppingShelfFor).not.toHaveBeenCalled();+ getShoppingShelfFor.mockResolvedValue(null);+ expect((await get('?brand_id=brand-2')).status).toBe(404);+ getShoppingShelfFor.mockResolvedValue(NOT_IN_PLAN);+ const locked = await get('?brand_id=brand-1');+ expect(locked.status).toBe(403);+ // The other shopping reads' answer, as the API's requireFeature gives it.+ expect(await locked.json()).toEqual(SHOPPING_NOT_IN_PLAN);+ expect(SHOPPING_NOT_IN_PLAN.error).toBe('plan_limit');+ getShoppingShelfFor.mockRejectedValue(new Error('timeout'));+ expect((await get('?brand_id=brand-1')).status).toBe(500);+ });+});diff --git a/web/src/app/api/mcp/product-visibility/shelf/route.ts b/web/src/app/api/mcp/product-visibility/shelf/route.tsnew file mode 100644index 000000000..3acffb309--- /dev/null+++ b/web/src/app/api/mcp/product-visibility/shelf/route.ts@@ -0,0 +1,45 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { NOT_IN_PLAN, SHOPPING_NOT_IN_PLAN } from '@/lib/mcp/data';+import { PV_PERIODS, getShoppingShelfFor } from '@/lib/mcp/product-visibility';+import { isShoppingMarket } from '@/lib/shopping/markets';++/** GET /api/mcp/product-visibility/shelf — REST mirror of the `get_shopping_shelf` MCP tool. */+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 period = PV_PERIODS.find((p) => p === url.searchParams.get('period'));+ const marketParam = url.searchParams.get('market');+ const market = isShoppingMarket(marketParam) ? marketParam : undefined;+ 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;+ };++ try {+ const read = await getShoppingShelfFor(auth, {+ brandId,+ period,+ platform: url.searchParams.get('platform')?.slice(0, 64) || undefined,+ market,+ absentOnly: url.searchParams.get('absent_only') === 'true',+ limit: number('limit'),+ offset: number('offset'),+ });+ if (read === null) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });+ }+ if (read === NOT_IN_PLAN) return NextResponse.json(SHOPPING_NOT_IN_PLAN, { status: 403 });+ return NextResponse.json(read);+ } catch (err) {+ const message = err instanceof Error ? err.message : 'Failed';+ return NextResponse.json({ error: message }, { status: 500 });+ }+}diff --git a/web/src/lib/actions/catalog.ts b/web/src/lib/actions/catalog.tsindex edc930ded..ef0661d39 100644--- a/web/src/lib/actions/catalog.ts+++ b/web/src/lib/actions/catalog.ts@@ -2,14 +2,8 @@import { z } from 'zod';import { createClient } from '@/lib/supabase/server';-import {- catalogSourceKey,- type CatalogCounts,- type CatalogFormat,- type CatalogSource,- type CatalogSourceKind,- type CatalogSyncStatus,-} from '@/lib/catalog';+import type { CatalogFormat, CatalogSource } from '@/lib/catalog';+import { readCatalogSources } from '@/lib/shopping/catalog-read';import { assertWritable } from '@/lib/subscription-guard';/**@@ -24,38 +18,7 @@ const FORMATS = ['auto', 'google_xml', 'csv', 'meta_csv'] as const;/** The brand's sources, oldest first, each with its live products in the catalog. */export async function listCatalogSources(brandId: string): Promise<CatalogSource[]> {if (!z.guid().safeParse(brandId).success) throw new Error('invalid');- const supabase = await createClient();- const { data, error } = await supabase- .from('catalog_sources')- .select(- 'id, kind, format, url, account, label, last_synced_at, last_status, last_error, last_counts',- )- .eq('brand_id', brandId)- .order('created_at', { ascending: true });- if (error) throw new Error(error.message);- return Promise.all(- (data ?? []).map(async (row) => {- const { count } = await supabase- .from('catalog_products')- .select('id', { count: 'exact', head: true })- .eq('brand_id', brandId)- .eq('source', catalogSourceKey(row.id))- .is('removed_at', null);- return {- id: row.id,- kind: row.kind as CatalogSourceKind,- format: row.format as CatalogFormat,- url: row.url,- account: row.account,- label: row.label,- lastSyncedAt: row.last_synced_at,- lastStatus: row.last_status as CatalogSyncStatus | null,- lastError: row.last_error,- lastCounts: row.last_counts as unknown as CatalogCounts | null,- products: count ?? 0,- };- }),- );+ return readCatalogSources(await createClient(), brandId);}export type AddFeedResult =diff --git a/web/src/lib/actions/shopping-market.ts b/web/src/lib/actions/shopping-market.tsindex fb07d5209..5dff7cec0 100644--- a/web/src/lib/actions/shopping-market.ts+++ b/web/src/lib/actions/shopping-market.ts@@ -1,6 +1,6 @@'use server';-import { createClient } from '@/lib/supabase/server';+import { dbClient } from '@/lib/supabase/scoped';const PROMPT_PAGE_SIZE = 1000;const PROMPT_MAX_ROWS = 20_000;@@ -9,11 +9,12 @@ const PROMPT_MAX_ROWS = 20_000;* The brand's countries, for its AI shopping market (#1278): its domains'* `country` and every location code its prompts track (`prompts.regions`,* states included), deduped and sorted. Codes come back as stored;- * `marketForCountry` normalizes them. RLS scopes both reads to the caller's- * organization.+ * `marketForCountry` normalizes them. On the page RLS scopes both reads to+ * the caller's organization; the MCP server runs it with the service role,+ * so their brand_id filters are what keep them to the brand.*/export async function getBrandMarketCountries(brandId: string): Promise<string[]> {- const supabase = await createClient();+ const supabase = await dbClient();const countries = new Set<string>();const add = (code: string | null | undefined) => {const trimmed = code?.trim();diff --git a/web/src/lib/actions/shopping-openai-index.ts b/web/src/lib/actions/shopping-openai-index.tsindex ab5132897..e185ddd02 100644--- a/web/src/lib/actions/shopping-openai-index.ts+++ b/web/src/lib/actions/shopping-openai-index.ts@@ -2,6 +2,7 @@import { z } from 'zod';import { createClient } from '@/lib/supabase/server';+import { dbClient } from '@/lib/supabase/scoped';import type { OpenAiIndexRead } from '@/lib/shopping/openai-index';import { getShoppingMerchantSplit, type ShoppingDatePreset } from './shopping';import { assertWritable } from '@/lib/subscription-guard';@@ -10,15 +11,17 @@ import { assertWritable } from '@/lib/subscription-guard';* What "Catalog in OpenAI's product index" reads (#1281): the brand's word* that it sends a direct feed, and the cards for its own products in US* ChatGPT Shopping answers over the Overview's window, counted by- * `shopping_merchant_split` (own-product cards, classified or not). RLS and- * the RPC's membership check keep both to the caller's organization.+ * `shopping_merchant_split` (own-product cards, classified or not). On the+ * page, RLS and the RPC's membership check keep both to the caller's+ * organization; the MCP server runs it with the service role, so the brand+ * id filter and the RPC's p_brand_id are what keep it to the brand.*/export async function getOpenAiIndexRead(brandId: string,datePreset: ShoppingDatePreset,): Promise<OpenAiIndexRead> {if (!z.guid().safeParse(brandId).success) throw new Error('invalid');- const supabase = await createClient();+ const supabase = await dbClient();const [brand, split] = await Promise.all([supabase.from('brands').select('openai_product_feed').eq('id', brandId).maybeSingle(),getShoppingMerchantSplit(brandId, {diff --git a/web/src/lib/actions/shopping-path.ts b/web/src/lib/actions/shopping-path.tsindex cea9c0aa2..ee0de9af4 100644--- a/web/src/lib/actions/shopping-path.ts+++ b/web/src/lib/actions/shopping-path.ts@@ -2,7 +2,6 @@import { z } from 'zod';import { API_BASE_URL } from '@/config/api';-import { MERCHANT_CENTER_KIND } from '@/lib/catalog';import { createClient } from '@/lib/supabase/server';import { jsonbBytes } from '@/lib/content/draft-inputs';import { variantStock } from '@/lib/content/feed-match';@@ -14,6 +13,7 @@ import type {ShoppingProductCheck,} from '@/lib/content/shopping-check';import { readAllRpcRows } from '@/lib/supabase/rpc-pages';+import { hasMerchantCenter } from '@/lib/shopping/catalog-read';import { assertWritable } from '@/lib/subscription-guard';import {NO_PATH_REASONS,@@ -364,27 +364,6 @@ async function pageSite(return host ? `https://${host}/` : null;}-/**- * Whether the brand reads a Google Merchant Center account into its catalog,- * its last sync read: only then does the check say a product is accepted by- * Merchant Center. None when it can't be read: the check then says less,- * never more.- */-async function hasMerchantCenter(supabase: Client, brandId: string): Promise<boolean> {- const { data, error } = await supabase- .from('catalog_sources')- .select('id')- .eq('brand_id', brandId)- .eq('kind', MERCHANT_CENTER_KIND)- .eq('last_status', 'ok')- .limit(1);- if (error) {- console.error('Failed to read the brand’s catalog sources:', error.message);- return false;- }- return (data ?? []).length > 0;-}-/*** The draft's shopping path read against the catalog now (shopping path,* part 6): each of its products sold out, refused by Merchant Center, gone,diff --git a/web/src/lib/actions/shopping-shelf.test.ts b/web/src/lib/actions/shopping-shelf.test.tsindex 9ebab0c9b..4926682d3 100644--- a/web/src/lib/actions/shopping-shelf.test.ts+++ b/web/src/lib/actions/shopping-shelf.test.ts@@ -6,7 +6,13 @@ const BRAND = '33333333-3333-3333-3333-333333333333';let tables: Record<string, Record<string, unknown>[]>;let catalogCount: number | null;-const reads: { table: string; eq: Record<string, unknown>; gte?: [string, string] }[] = [];+const reads: {+ table: string;+ eq: Record<string, unknown>;+ gte?: [string, string];+ in?: Record<string, unknown[]>;+ limit?: number;+}[] = [];function query(table: string) {const state: {@@ -15,6 +21,8 @@ function query(table: string) {gte?: [string, string];range?: [number, number];head?: boolean;+ in?: Record<string, unknown[]>;+ limit?: number;} = {table,eq: {},@@ -23,19 +31,28 @@ function query(table: string) {select: (_columns: string, opts?: { head?: boolean }) => ((state.head = opts?.head), q),eq: (column: string, value: unknown) => ((state.eq[column] = value), q),is: () => q,- in: () => q,+ in: (column: string, values: unknown[]) => ((state.in = { ...state.in, [column]: values }), q),+ limit: (count: number) => ((state.limit = count), q),lte: () => q,or: () => q,gte: (column: string, value: string) => ((state.gte = [column, value]), q),order: () => q,range: (from: number, to: number) => ((state.range = [from, to]), q),then: (resolve: (value: unknown) => void) => {- reads.push({ table: state.table, eq: state.eq, gte: state.gte });+ reads.push({+ table: state.table,+ eq: state.eq,+ gte: state.gte,+ ...(state.in ? { in: state.in } : {}),+ ...(state.limit === undefined ? {} : { limit: state.limit }),+ });if (state.head) return resolve({ data: null, count: catalogCount, error: null });- const rows = (tables[table] ?? []).filter((row) =>- Object.entries(state.eq).every(([k, v]) => !(k in row) || row[k] === v),+ const rows = (tables[table] ?? []).filter(+ (row) =>+ Object.entries(state.eq).every(([k, v]) => !(k in row) || row[k] === v) &&+ Object.entries(state.in ?? {}).every(([k, vs]) => vs.includes(row[k])),);- const [from, to] = state.range ?? [0, 999];+ const [from, to] = state.range ?? [0, (state.limit ?? 1000) - 1];resolve({ data: rows.slice(from, to + 1), error: null });},};@@ -46,7 +63,8 @@ vi.mock('@/lib/supabase/server', () => ({createClient: vi.fn(async () => ({ from: query })),}));-const { getShoppingAiOrders, getShoppingShelf } = await import('./shopping');+const { getShoppingAiOrders, getShoppingOwnChannels, getShoppingShelf } =+ await import('./shopping');beforeEach(() => {tables = {};@@ -92,6 +110,51 @@ describe('getShoppingShelf', () => {});});+describe('getShoppingOwnChannels', () => {+ it("names the channels with the brand's own products, one row read a channel", async () => {+ const card = (platform: string, role: string) => ({+ id: `${platform}-${role}`,+ platform,+ matched_brand_role: role,+ });+ tables.prompt_result_shopping_cards = [+ card('chatgpt-shopping', 'own'),+ card('chatgpt-shopping', 'own'),+ card('google-aio', 'competitor'),+ card('gemini-web', 'own'),+ ];+ expect(await getShoppingOwnChannels(BRAND, { datePreset: '30d' })).toEqual([+ 'chatgpt-shopping',+ 'gemini-web',+ ]);+ expect(reads).toHaveLength(5);+ for (const read of reads) {+ expect(read).toMatchObject({+ table: 'prompt_result_shopping_cards',+ eq: { brand_id: BRAND, matched_brand_role: 'own' },+ limit: 1,+ });+ }+ expect(reads.map((read) => read.in?.platform)).toEqual([+ ['chatgpt-shopping'],+ ['google-aio'],+ ['google-aimode'],+ ['gemini-web'],+ ['copilot-web'],+ ]);+ });++ it('reads every channel whatever the platform filter, and no brand that isn’t an id', async () => {+ tables.prompt_result_shopping_cards = [+ { id: 'c1', platform: 'google-aimode', matched_brand_role: 'own' },+ ];+ expect(+ await getShoppingOwnChannels(BRAND, { datePreset: '7d', platforms: ['chatgpt-shopping'] }),+ ).toEqual(['google-aimode']);+ await expect(getShoppingOwnChannels('nope', { datePreset: '7d' })).rejects.toThrow('invalid');+ });+});+describe('getShoppingAiOrders', () => {it("counts the last 30 days' orders against the 30 before, in the main currency, by AI source", async () => {tables.ai_traffic_events = [diff --git a/web/src/lib/actions/shopping.ts b/web/src/lib/actions/shopping.tsindex c766d08a5..f1d5c26d7 100644--- a/web/src/lib/actions/shopping.ts+++ b/web/src/lib/actions/shopping.ts@@ -2,6 +2,7 @@import { API_BASE_URL } from '@/config/api';import { createClient } from '@/lib/supabase/server';+import { dbClient } from '@/lib/supabase/scoped';import { readAllRpcRows } from '@/lib/supabase/rpc-pages';import { expandDateToEndOfDay } from '@/lib/dates';import {@@ -29,7 +30,15 @@ import {type ProductShelfLine,} from '@/lib/shopping/product-detail';import { priceText } from '@/lib/shopping/price';+import {+ CARD_MAX_ROWS,+ PRODUCTS_TABLE_MAX,+ readCatalogProducts,+ readCatalogRows,+ readForIds,+} from '@/lib/shopping/catalog-read';import { productAiSays, type AiSaysAnswer, type ProductAiSays } from '@/lib/shopping/ai-says';+import { READINESS_CHANNELS } from '@/lib/shopping/readiness';import { FROM_PRODUCTS_KINDS } from '@/lib/action-center/registry';import {RECHECK_DAYS,@@ -67,7 +76,9 @@ import {* query joins or filters on `brand_id`, and RLS on* `prompt_result_shopping_cards` already restricts to the caller's* organization. The action just adds the matching brand filter to keep- * results scoped to a single brand at a time.+ * results scoped to a single brand at a time. The reads the MCP server+ * shares (lib/mcp/product-visibility.ts) query through dbClient(), so it can+ * run them with the service role once it has checked the brand.*/export type ShoppingDatePreset = '7d' | '30d' | '90d' | 'all';@@ -258,7 +269,7 @@ export async function getShoppingOverview(export async function getShoppingAmazonShareDropAlert(brandId: string,): Promise<AmazonShareDropAlert | null> {- const supabase = await createClient();+ const supabase = await dbClient();const { data, error } = await supabase.rpc('shopping_amazon_share_weekly', {p_brand_id: brandId,});@@ -287,7 +298,7 @@ export async function getShoppingMerchantSplit(brandId: string,filters: ShoppingFilters,): Promise<ShoppingMerchantSplit> {- const supabase = await createClient();+ const supabase = await dbClient();const { data, error } = await supabase.rpc('shopping_merchant_split',windowArgs(brandId, filters),@@ -317,7 +328,7 @@ export async function getResellerPriceAlerts(brandId: string,filters: ShoppingFilters,): Promise<ResellerPriceAlert[]> {- const supabase = await createClient();+ const supabase = await dbClient();const { data, error } = await supabase.rpc('shopping_own_product_offers',windowArgs(brandId, filters),@@ -347,7 +358,7 @@ export async function getShoppingFilterOptions(brandId: string): Promise<{platforms: string[];regions: string[];}> {- const supabase = await createClient();+ const supabase = await dbClient();const { data, error } = await supabase.rpc('shopping_filter_options', { p_brand_id: brandId });if (error) return { platforms: [], regions: [] };const row = (data as { platforms: string[] | null; regions: string[] | null }[] | null)?.[0];@@ -357,7 +368,6 @@ export async function getShoppingFilterOptions(brandId: string): Promise<{// ── Paged card reads ──────────────────────────────────────────────────────────const CARD_PAGE_SIZE = 1000;-const CARD_MAX_ROWS = 50_000;/*** Every row a card query matches, read in `.range()` pages: an unpaged select@@ -1165,7 +1175,7 @@ export async function getShoppingShelf(brandId: string,filters: ShoppingFilters,): Promise<ShoppingShelf> {- const supabase = await createClient();+ const supabase = await dbClient();const [rows, catalog] = await Promise.all([fetchAllCards<Omit<ShelfCardRow, 'prompt_id' | 'prompt_text'> & {@@ -1191,6 +1201,35 @@ export async function getShoppingShelf(};}+/**+ * The AI channels (READINESS_CHANNELS) with the brand's own products on+ * their shelves over the filter window, whatever its platforms: what+ * Readiness's channel cards (ECOM-015) read from the Shelf's stats, as one+ * row a channel instead of every card. The channels are read at once.+ */+export async function getShoppingOwnChannels(+ brandId: string,+ filters: ShoppingFilters,+): Promise<string[]> {+ if (!z.guid().safeParse(brandId).success) throw new Error('invalid');+ const supabase = await dbClient();+ const own = await Promise.all(+ READINESS_CHANNELS.map(async (platform) => {+ const { data, error } = await cardsInWindow(+ supabase,+ brandId,+ { ...filters, platforms: [platform] },+ 'id',+ )+ .eq('matched_brand_role', 'own')+ .limit(1);+ if (error) throw new Error(error.message);+ return (data ?? []).length > 0;+ }),+ );+ return READINESS_CHANNELS.filter((_, i) => own[i]);+}+/** Orders from AI visits (CE-017): the last 30 days, the 30 before, and by AI channel. */export interface ShoppingAiOrders {orders: number;@@ -1267,15 +1306,6 @@ export async function getShoppingAiOrders(brandId: string): Promise<ShoppingAiOr// ── Products (Product Visibility, ECOM-007) ───────────────────────────────────-/** Catalog products the table reads at most. */-const PRODUCTS_TABLE_MAX = 2000;-const CATALOG_PAGE = 1000;-/** Product ids one catalog read filters by: each request's address stays short. */-const IDS_PER_READ = 100;-/** Such reads in flight at once. */-const ID_READS_AT_ONCE = 6;-const IN_STOCK = new Set(['in_stock', 'instock', 'available', 'limited_availability']);-type ServerClient = Awaited<ReturnType<typeof createClient>>;export interface ShoppingProducts {@@ -1284,39 +1314,6 @@ export interface ShoppingProducts {total: number;}-/** Every row of a brand's catalog table, in `.range()` pages, up to `max`. */-async function readCatalogRows<T>(- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- PostgREST builder generics- build: () => any,- max: number,-): Promise<T[]> {- const rows: T[] = [];- for (let start = 0; start < max; start += CATALOG_PAGE) {- const { data, error } = await build().range(start, Math.min(start + CATALOG_PAGE, max) - 1);- if (error) throw new Error(error.message);- rows.push(...((data ?? []) as T[]));- if ((data ?? []).length < CATALOG_PAGE) break;- }- return rows;-}--/** A catalog table's rows for these ids: IDS_PER_READ ids a read, ID_READS_AT_ONCE reads at a time. */-async function readForIds<T>(ids: readonly string[], read: (some: string[]) => Promise<T[]>) {- const slices: string[][] = [];- for (let i = 0; i < ids.length; i += IDS_PER_READ) slices.push(ids.slice(i, i + IDS_PER_READ));- const out: T[][] = [];- let next = 0;- await Promise.all(- Array.from({ length: Math.min(ID_READS_AT_ONCE, slices.length) }, async () => {- while (next < slices.length) {- const at = next++;- out[at] = await read(slices[at]);- }- }),- );- return out.flat();-}-/*** Per product, its AI visits and orders over the window (00361): only the* products with either, every page of them.@@ -1344,7 +1341,7 @@ export async function getShoppingProducts(brandId: string,filters: ShoppingFilters,): Promise<ShoppingProducts | null> {- const supabase = await createClient();+ const supabase = await dbClient();const { count: total, error: countErr } = await supabase.from('catalog_products').select('id', { count: 'exact', head: true })@@ -1446,137 +1443,6 @@ async function tableProductIds(return [...ids];}-/**- * The brand's live catalog products as Product Visibility reads them, with- * their variants' stock, price and GTIN, first photo and category: the- * whole catalog (up to PRODUCTS_TABLE_MAX) for `ids` null, else the products- * `ids` names, their rows read IDS_PER_READ ids at a time.- */-async function readCatalogProducts(- supabase: ServerClient,- brandId: string,- ids: readonly string[] | null,-): Promise<CatalogProductRow[]> {- // Each table read for the whole catalog, or for the ids, a slice at a time.- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- PostgREST builder generics- const each = <T>(column: string, build: () => any, max: number): Promise<T[]> =>- ids === null- ? readCatalogRows<T>(build, max)- : readForIds(ids, (some) =>- readCatalogRows<T>(() => build().in(column, some), CARD_MAX_ROWS),- );- const [products, variants, images, categories] = await Promise.all([- each<{- id: string;- title: string;- url: string | null;- product_type: string | null;- product_brand: string | null;- description: string | null;- }>(- 'id',- () =>- supabase- .from('catalog_products')- .select('id, title, url, product_type, product_brand, description')- .eq('brand_id', brandId)- .is('removed_at', null)- .order('id'),- PRODUCTS_TABLE_MAX,- ),- each<{- product_id: string;- gtin: string | null;- price: number | null;- sale_price: number | null;- currency: string | null;- availability: string | null;- }>(- 'product_id',- () =>- supabase- .from('catalog_variants')- .select('product_id, gtin, price, sale_price, currency, availability')- .eq('brand_id', brandId)- .is('removed_at', null)- .order('id'),- CARD_MAX_ROWS,- ),- each<{ product_id: string; url: string; position: number }>(- 'product_id',- () =>- supabase- .from('catalog_images')- .select('product_id, url, position')- .eq('brand_id', brandId)- .order('id'),- CARD_MAX_ROWS,- ),- each<{ product_id: string; category: { name: string } | null }>(- 'product_id',- () =>- supabase- .from('catalog_product_categories')- .select('product_id, category:category_id ( name )')- .eq('brand_id', brandId)- .order('product_id')- .order('category_id'),- CARD_MAX_ROWS,- ),- ]);-- const variantsOf = new Map<string, typeof variants>();- for (const v of variants) {- if (!variantsOf.has(v.product_id)) variantsOf.set(v.product_id, []);- variantsOf.get(v.product_id)!.push(v);- }- const imageOf = new Map<string, { url: string; position: number }>();- for (const image of images) {- const kept = imageOf.get(image.product_id);- if (!kept || image.position < kept.position) imageOf.set(image.product_id, image);- }- const categoryOf = new Map<string, string>();- for (const row of categories) {- if (row.category?.name && !categoryOf.has(row.product_id)) {- categoryOf.set(row.product_id, row.category.name);- }- }- return products.map((p) => {- const own = variantsOf.get(p.id) ?? [];- const stocked = own.filter((v) =>- IN_STOCK.has(- String(v.availability ?? '')- .toLowerCase()- .replace(/[\s-]+/g, '_'),- ),- );- const priced = (stocked.length ? stocked : own)- .map((v) => ({ price: v.sale_price ?? v.price, currency: v.currency }))- .filter((v): v is { price: number; currency: string | null } => v.price !== null)- .sort((a, b) => a.price - b.price);- return {- id: p.id,- title: p.title,- url: p.url,- productType: p.product_type,- brand: p.product_brand,- description: p.description,- image: imageOf.get(p.id)?.url ?? null,- category: categoryOf.get(p.id) ?? null,- price: priced[0] ? Number(priced[0].price) : null,- currency: priced[0]?.currency ?? null,- // Each variant's price and sale price, in or out of stock.- prices: own.flatMap((v) =>- [v.price, v.sale_price]- .filter((price): price is number => price !== null)- .map((price) => ({ price: Number(price), currency: v.currency })),- ),- inStock: stocked.length > 0,- hasGtin: own.some((v) => !!v.gtin),- };- });-}-// ── Categories (Product Visibility, ECOM-008) ─────────────────────────────────/**@@ -1893,7 +1759,8 @@ const AI_SAYS_CITED = 20;* that showed it, quoted where they name it, and the sources they cited* (lib/shopping/ai-says.ts). Read apart from the product's page, which it* follows: the answers' text is the heavy part. Through the member's- * session (RLS).+ * session (RLS) on the page; the MCP server runs it with the service role,+ * so every read here keeps to the brand by its brand_id filter.*/export async function getProductAiSays(brandId: string,@@ -1903,7 +1770,7 @@ export async function getProductAiSays(if (!z.guid().safeParse(brandId).success || !z.guid().safeParse(productId).success) {throw new Error('invalid');}- const supabase = await createClient();+ const supabase = await dbClient();const [cards, product] = await Promise.all([cardsInWindow(supabase,diff --git a/web/src/lib/mcp/catalog.test.ts b/web/src/lib/mcp/catalog.test.tsnew file mode 100644index 000000000..9fcdfcef4--- /dev/null+++ b/web/src/lib/mcp/catalog.test.ts@@ -0,0 +1,329 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { McpAuthContext } from '@/lib/mcp-auth';++/**+ * The catalog over MCP (B6a): its sources and last syncs, and a page of its+ * products as Product Visibility reads them, each with its readiness, its+ * Merchant Center issues and its page's AI visits and orders.+ */++const brandInOrg = vi.hoisted(() => vi.fn());+vi.mock('@/lib/mcp/data', () => ({ brandInOrg }));++// The paged reads and the Merchant Center check run as they are; the+// Product Visibility reads answer what each test says.+const read = vi.hoisted(() => ({+ readCatalogSources: vi.fn(),+ readCatalogProducts: vi.fn(),+}));+vi.mock('@/lib/shopping/catalog-read', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/lib/shopping/catalog-read')>()),+ ...read,+}));++type Row = Record<string, unknown>;++/** What each table holds, and how many of its rows a count says. */+let tables: Record<string, Row[]>;+let counts: Record<string, number>;+/** Every filter asked, by table. */+let filters: [string, string, unknown][];+let rpcArgs: Record<string, unknown>[];+let stats: Row[];++/**+ * A PostgREST table as the service role reads it: `eq` and `in` filter the+ * rows that have the column, a page is `.range()`, a count is `count`, an+ * answer stops at max_rows' 1,000 rows, and an offset past the rows counted+ * is refused (416, PGRST103).+ */+const MAX_ROWS = 1000;++function query(table: string) {+ const where: [string, (value: unknown) => boolean][] = [];+ let counted = false;+ let head = false;+ const matched = () =>+ (tables[table] ?? []).filter((row) =>+ where.every(([column, keep]) => !(column in row) || keep(row[column])),+ );+ const total = () => counts[table] ?? matched().length;+ const chain = {+ select: (_columns: string, options?: { count?: string; head?: boolean }) => {+ counted = options?.count === 'exact';+ head = options?.head ?? false;+ return chain;+ },+ eq: (column: string, value: unknown) => {+ filters.push([table, column, value]);+ where.push([column, (v) => v === value]);+ return chain;+ },+ in: (column: string, values: unknown[]) => {+ filters.push([table, column, values]);+ where.push([column, (v) => values.includes(v)]);+ return chain;+ },+ is: () => chain,+ regexIMatch: (column: string, pattern: string) => {+ filters.push([table, column, pattern]);+ return chain;+ },+ order: () => chain,+ limit: async (n: number) => ({ data: matched().slice(0, n), error: null }),+ range: async (start: number, end: number) =>+ counted && start > total()+ ? {+ data: null,+ count: null,+ error: { code: 'PGRST103', message: 'Requested range not satisfiable' },+ }+ : {+ data: matched().slice(start, Math.min(end + 1, start + MAX_ROWS)),+ count: counted ? total() : null,+ error: null,+ },+ then: (resolve: (value: unknown) => unknown) =>+ resolve({ data: head ? null : matched().slice(0, MAX_ROWS), count: total(), error: null }),+ };+ return chain;+}++vi.mock('@/lib/supabase/admin', () => ({+ supabaseAdmin: {+ from: (table: string) => query(table),+ rpc: (_fn: string, args: Record<string, unknown>) => {+ rpcArgs.push(args);+ return { order: () => ({ range: async () => ({ data: stats, error: null }) }) };+ },+ },+}));++const { getCatalogSourcesFor, listCatalogProductsFor } = await import('./catalog');++const auth: McpAuthContext = {+ userId: 'user-1',+ email: null,+ organizationId: 'org-1',+ apiKeyId: 'key-1',+ role: 'admin',+};++const product = (id: string, over: Record<string, unknown> = {}) => ({+ id,+ title: `Boots ${id}`,+ url: `https://acme.example/p/${id}`,+ productType: 'Boots',+ brand: 'Acme',+ description: `Boots for the trail, waterproof and light. ${'They keep feet dry and warm on long walks. '.repeat(10)}`,+ image: 'https://acme.example/i.jpg',+ category: 'Shoes > Boots',+ price: 120,+ currency: 'USD',+ inStock: true,+ hasGtin: true,+ ...over,+});++const merchantCenter = (lastStatus = 'ok') => [+ { id: 's1', kind: 'merchant_center', last_status: lastStatus },+];++/** Every table read was the brand's, and only the brand's. */+function expectBrandScoped(brandId: string) {+ const read = new Set(filters.map(([table]) => table));+ for (const table of read) {+ expect(+ filters.filter(([t, column]) => t === table && column === 'brand_id').map(([, , v]) => v),+ table,+ ).toEqual(expect.arrayContaining([brandId]));+ expect(+ filters.some(([t, column, v]) => t === table && column === 'brand_id' && v !== brandId),+ table,+ ).toBe(false);+ }+ for (const args of rpcArgs) expect(args.p_brand_id).toBe(brandId);+}++beforeEach(() => {+ brandInOrg.mockReset().mockResolvedValue(true);+ read.readCatalogSources.mockReset();+ read.readCatalogProducts.mockReset();+ tables = {};+ counts = {};+ filters = [];+ rpcArgs = [];+ stats = [];+});++describe('getCatalogSourcesFor', () => {+ it("gives each source and its last sync in the MCP's names", async () => {+ read.readCatalogSources.mockResolvedValue([+ {+ id: 's1',+ kind: 'merchant_center',+ format: 'auto',+ url: null,+ account: '123456',+ label: 'Acme',+ lastSyncedAt: '2026-10-28T03:00:00Z',+ lastStatus: 'ok',+ lastError: null,+ lastCounts: { format: 'merchant_center', items: 40, skipped: 0 },+ products: 38,+ },+ ]);+ expect(await getCatalogSourcesFor(auth, 'brand-1')).toEqual([+ {+ id: 's1',+ kind: 'merchant_center',+ format: 'auto',+ url: null,+ account: '123456',+ label: 'Acme',+ last_synced_at: '2026-10-28T03:00:00Z',+ last_status: 'ok',+ last_error: null,+ last_counts: { format: 'merchant_center', items: 40, skipped: 0 },+ products: 38,+ },+ ]);+ expect(read.readCatalogSources).toHaveBeenCalledWith(expect.anything(), 'brand-1');+ });++ it("answers null for another organization's brand, without reading it", async () => {+ brandInOrg.mockResolvedValue(false);+ expect(await getCatalogSourcesFor(auth, 'brand-2')).toBeNull();+ expect(read.readCatalogSources).not.toHaveBeenCalled();+ });+});++describe('listCatalogProductsFor', () => {+ it('reads a page of products as Product Visibility does, with readiness, issues and AI stats', async () => {+ tables.catalog_products = [{ id: 'p1' }, { id: 'p2' }];+ counts.catalog_products = 5;+ tables.catalog_sources = merchantCenter();+ tables.catalog_variants = [+ { product_id: 'p1', external_id: 'offer-1' },+ { product_id: 'p2', external_id: 'offer-2' },+ { product_id: 'p2', external_id: 'offer-3' },+ ];+ tables.catalog_item_issues = [+ // One issue in two destinations and on two of its variants: once.+ { external_id: 'offer-2', severity: 'disapproved', code: 'missing_gtin', attribute: 'gtin' },+ { external_id: 'offer-2', severity: 'disapproved', code: 'missing_gtin', attribute: 'gtin' },+ { external_id: 'offer-3', severity: 'disapproved', code: 'missing_gtin', attribute: 'gtin' },+ { external_id: 'offer-3', severity: 'demoted', code: 'image_too_small', attribute: null },+ { external_id: 'offer-3', severity: 'unknown', code: 'odd', attribute: null },+ ];+ stats = [{ product_id: 'p1', ai_visits: 12, orders: 2, revenue: 240, currency: 'USD' }];+ // The catalog reads them in its own order; the page keeps the title order.+ read.readCatalogProducts.mockResolvedValue([+ product('p2', { hasGtin: false, inStock: false }),+ product('p1'),+ ]);++ const page = (await listCatalogProductsFor(auth, { brandId: 'brand-1', limit: 2 }))!;++ expect(read.readCatalogProducts).toHaveBeenCalledWith(expect.anything(), 'brand-1', [+ 'p1',+ 'p2',+ ]);+ expect(page.total).toBe(5);+ expect(page.next_offset).toBe(2);+ expect(page.products.map((p) => p.id)).toEqual(['p1', 'p2']);+ expect(page.products[0]).toMatchObject({+ title: 'Boots p1',+ readiness: { score: 100, missing: [], unknown: [] },+ merchant_center_issues: { disapproved: 0, demoted: 0, not_impacted: 0 },+ ai_visits_30d: 12,+ orders_30d: 2,+ revenue_30d: 240,+ revenue_currency: 'USD',+ });+ expect(page.products[1]).toMatchObject({+ in_stock: false,+ has_gtin: false,+ readiness: { missing: ['gtin', 'inStock'] },+ merchant_center_issues: { disapproved: 1, demoted: 1, not_impacted: 0 },+ ai_visits_30d: 0,+ orders_30d: 0,+ revenue_30d: null,+ });+ expectBrandScoped('brand-1');+ });++ it('finds a search as written: its regex characters, % and _ stay themselves', async () => {+ tables.catalog_products = [{ id: 'p1' }];+ read.readCatalogProducts.mockResolvedValue([product('p1')]);+ await listCatalogProductsFor(auth, { brandId: 'brand-1', search: ' Boots (50%_off)* ' });+ expect(filters).toContainEqual(['catalog_products', 'title', 'Boots \\(50%_off\\)\\*']);+ });++ it('reads every variant and issue past a 1,000-row page, 100 ids a request', async () => {+ const ids = Array.from({ length: 150 }, (_, i) => `p${i}`);+ tables.catalog_products = ids.map((id) => ({ id }));+ tables.catalog_sources = merchantCenter();+ // Ten variants each: the first hundred products' come to 1,000 rows.+ tables.catalog_variants = ids.flatMap((id) =>+ Array.from({ length: 10 }, (_, j) => ({ product_id: id, external_id: `${id}-v${j}` })),+ );+ tables.catalog_item_issues = [+ // 1,100 issues on one offer: past one page.+ ...Array.from({ length: 1100 }, (_, i) => ({+ external_id: 'p0-v0',+ severity: 'disapproved',+ code: `issue-${i}`,+ attribute: null,+ })),+ { external_id: 'p149-v9', severity: 'not_impacted', code: 'gtin_hint', attribute: 'gtin' },+ ];+ read.readCatalogProducts.mockResolvedValue(ids.map((id) => product(id)));++ const page = (await listCatalogProductsFor(auth, { brandId: 'brand-1', limit: 150 }))!;+ const issues = new Map(page.products.map((p) => [p.id, p.merchant_center_issues]));+ expect(issues.get('p0')).toEqual({ disapproved: 1100, demoted: 0, not_impacted: 0 });+ expect(issues.get('p1')).toEqual({ disapproved: 0, demoted: 0, not_impacted: 0 });+ expect(issues.get('p149')).toEqual({ disapproved: 0, demoted: 0, not_impacted: 1 });+ const idLists = filters.filter(([, , v]) => Array.isArray(v)).map(([, , v]) => v as unknown[]);+ expect(Math.max(...idLists.map((list) => list.length))).toBe(100);+ expectBrandScoped('brand-1');+ });++ it('gives no Merchant Center issues without an account whose last sync went through', async () => {+ tables.catalog_products = [{ id: 'p1' }];+ read.readCatalogProducts.mockResolvedValue([product('p1')]);+ tables.catalog_sources = [];+ let page = (await listCatalogProductsFor(auth, { brandId: 'brand-1' }))!;+ expect(page.products[0].merchant_center_issues).toBeNull();+ expect(page.next_offset).toBeNull();++ tables.catalog_sources = merchantCenter('auth_failed');+ page = (await listCatalogProductsFor(auth, { brandId: 'brand-1' }))!;+ expect(page.products[0].merchant_center_issues).toBeNull();+ expect(filters.some(([table]) => table === 'catalog_item_issues')).toBe(false);+ });++ it('answers an empty page past the end, which PostgREST refuses once it counts', async () => {+ counts.catalog_products = 3;+ expect(await listCatalogProductsFor(auth, { brandId: 'brand-1', offset: 10 })).toEqual({+ total: 3,+ products: [],+ next_offset: null,+ });+ // At the end itself PostgREST answers no rows.+ expect(await listCatalogProductsFor(auth, { brandId: 'brand-1', offset: 3 })).toEqual({+ total: 3,+ products: [],+ next_offset: null,+ });+ expect(read.readCatalogProducts).not.toHaveBeenCalled();+ });++ it("answers null for another organization's brand, without reading it", async () => {+ brandInOrg.mockResolvedValue(false);+ expect(await listCatalogProductsFor(auth, { brandId: 'brand-2' })).toBeNull();+ expect(filters).toEqual([]);+ expect(read.readCatalogProducts).not.toHaveBeenCalled();+ });+});diff --git a/web/src/lib/mcp/catalog.ts b/web/src/lib/mcp/catalog.tsnew file mode 100644index 000000000..5a3351174--- /dev/null+++ b/web/src/lib/mcp/catalog.ts@@ -0,0 +1,288 @@+import { supabaseAdmin } from '@/lib/supabase/admin';+import type { McpAuthContext } from '@/lib/mcp-auth';+import { readAllRpcRows } from '@/lib/supabase/rpc-pages';+import {+ CARD_MAX_ROWS,+ hasMerchantCenter,+ readCatalogProducts,+ readCatalogRows,+ readCatalogSources,+ readForIds,+} from '@/lib/shopping/catalog-read';+import { readiness, type ReadinessCheck } from '@/lib/shopping/products';+import { brandInOrg } from './data';++/**+ * A brand's product catalog (#1263) for the MCP tools get_catalog_sources and+ * list_catalog_products and their REST mirrors (MCP plan B6a): where it is+ * read from and how its last sync went, and its products as Product+ * Visibility reads them (readCatalogProducts), each with its readiness for+ * AI shopping, its Google Merchant Center issues (00296) and the AI visits+ * and orders its page brought (00361). Read through the service role once+ * the brand is the key's.+ */++/** A catalog source and its last sync, as Settings › Integrations › Catalog shows it. */+export interface McpCatalogSource {+ id: string;+ /** feed_url, upload, or a store's connector (shopify, merchant_center…). */+ kind: string;+ format: string;+ url: string | null;+ /** A store's account (a shop's domain); null for feeds and uploads. */+ account: string | null;+ label: string | null;+ last_synced_at: string | null;+ /** ok, failed, format_error or auth_failed (the store refused the saved sign-in). */+ last_status: string | null;+ last_error: string | null;+ /** What the last sync read: items, skipped, added/changed/removed, Merchant Center issues, past the plan's cap. */+ last_counts: Record<string, unknown> | null;+ /** Its products in the catalog now. */+ products: number;+}++export async function getCatalogSourcesFor(+ auth: McpAuthContext,+ brandId: string,+): Promise<McpCatalogSource[] | null> {+ if (!(await brandInOrg(auth, brandId))) return null;+ const sources = await readCatalogSources(supabaseAdmin, brandId);+ return sources.map((s) => ({+ id: s.id,+ kind: s.kind,+ format: s.format,+ url: s.url,+ account: s.account,+ label: s.label,+ last_synced_at: s.lastSyncedAt,+ last_status: s.lastStatus,+ last_error: s.lastError,+ last_counts: s.lastCounts as Record<string, unknown> | null,+ products: s.products,+ }));+}++/** A catalog product as list_catalog_products gives it. */+export interface McpCatalogProduct {+ id: string;+ title: string;+ url: string | null;+ brand: string | null;+ product_type: string | null;+ category: string | null;+ image: string | null;+ /** Its lowest price in stock (else of any variant), sale price first. */+ price: number | null;+ currency: string | null;+ in_stock: boolean;+ has_gtin: boolean;+ /**+ * How ready it is for AI shopping, 0–100, the checks it misses, and those+ * that can't be made (left out of the score).+ */+ readiness: { score: number; missing: ReadinessCheck[]; unknown: ReadinessCheck[] };+ /**+ * Google Merchant Center's issues on its offers by severity, each issue+ * (its code and attribute) once however many of its variants and+ * destinations it is on; null without a Merchant Center account whose last+ * sync went through.+ */+ merchant_center_issues: McpIssueCounts | null;+ /** AI-referred visits to its page and the orders they led to, over the last 30 days. */+ ai_visits_30d: number;+ orders_30d: number;+ /** Those orders' revenue, in their main currency; null without orders. */+ revenue_30d: number | null;+ revenue_currency: string | null;+}++export interface McpCatalogPage {+ /** The brand's live products that match. */+ total: number;+ products: McpCatalogProduct[];+ /** The offset of the next page; null on the last. */+ next_offset: number | null;+}++/** A product's AI visits and orders (catalog_product_ai_stats, 00361). */+interface ProductAiStatsRow {+ product_id: string;+ ai_visits: number;+ orders: number;+ revenue: number | null;+ currency: string | null;+}++const SEVERITIES = ['disapproved', 'demoted', 'not_impacted'] as const;+type Severity = (typeof SEVERITIES)[number];+type McpIssueCounts = Record<Severity, number>;++const PRODUCTS_DEFAULT = 50;+const PRODUCTS_MAX = 200;+const STATS_DAYS = 30;+/** PostgREST's answer to an offset past the rows it counted (416). */+const PAST_THE_END = 'PGRST103';++/**+ * `text` as a regular expression that matches it as written. The search is+ * a case-insensitive regex (`~*`), not ilike: PostgREST turns every `*` of+ * a like pattern into `%` before Postgres reads it, so no escape keeps one.+ */+const literal = (text: string) => text.replace(/[\\^$.*+?()[\]{}|]/g, (c) => `\\${c}`);++/**+ * A page of the brand's live catalog products, by title, each read as+ * Product Visibility reads it; `search` narrows to titles containing it.+ * Null for a brand outside the key's organization.+ */+export async function listCatalogProductsFor(+ auth: McpAuthContext,+ params: { brandId: string; search?: string; limit?: number; offset?: number },+): Promise<McpCatalogPage | null> {+ if (!(await brandInOrg(auth, params.brandId))) return null;+ const limit = Math.min(Math.max(params.limit ?? PRODUCTS_DEFAULT, 1), PRODUCTS_MAX);+ const offset = Math.max(params.offset ?? 0, 0);+ const search = params.search?.trim();++ // The brand's live products the search matches; `head` for their count alone.+ const matching = (head: boolean) => {+ const query = supabaseAdmin+ .from('catalog_products')+ .select('id', { count: 'exact', head })+ .eq('brand_id', params.brandId)+ .is('removed_at', null);+ return search ? query.regexIMatch('title', literal(search)) : query;+ };+ const { data, count, error } = await matching(false)+ .order('title')+ .order('id')+ .range(offset, offset + limit - 1);+ if (error?.code === PAST_THE_END) {+ // Past the last match: an empty page, as before it.+ const { count: total, error: countError } = await matching(true);+ if (countError) throw new Error(countError.message);+ return { total: total ?? 0, products: [], next_offset: null };+ }+ if (error) throw new Error(error.message);+ const ids = (data ?? []).map((row) => row.id as string);+ const total = count ?? 0;+ if (!ids.length) return { total, products: [], next_offset: null };++ const since = new Date(Date.now() - STATS_DAYS * 86_400_000).toISOString();+ const [catalog, issues, stats] = await Promise.all([+ readCatalogProducts(supabaseAdmin, params.brandId, ids),+ issuesOf(params.brandId, ids),+ readAllRpcRows<ProductAiStatsRow>(+ (start, end) =>+ supabaseAdmin+ .rpc('catalog_product_ai_stats', { p_brand_id: params.brandId, p_from: since })+ .order('product_id')+ .range(start, end) as unknown as PromiseLike<{+ data: ProductAiStatsRow[] | null;+ error: { message: string } | null;+ }>,+ ),+ ]);+ const statsOf = new Map(stats.map((row) => [row.product_id, row]));+ const byId = new Map(catalog.map((product) => [product.id, product]));++ const products = ids.flatMap((id) => {+ const product = byId.get(id);+ if (!product) return [];+ const stat = statsOf.get(id);+ return [+ {+ id,+ title: product.title,+ url: product.url,+ brand: product.brand,+ product_type: product.productType,+ category: product.category,+ image: product.image,+ price: product.price,+ currency: product.currency,+ in_stock: product.inStock,+ has_gtin: product.hasGtin,+ readiness: readiness(product),+ merchant_center_issues: issues && (issues.get(id) ?? noIssues()),+ ai_visits_30d: Number(stat?.ai_visits ?? 0),+ orders_30d: Number(stat?.orders ?? 0),+ revenue_30d: stat?.revenue == null ? null : Number(stat.revenue),+ revenue_currency: stat?.currency ?? null,+ },+ ];+ });+ return {+ total,+ products,+ next_offset: offset + ids.length < total ? offset + ids.length : null,+ };+}++const noIssues = (): McpIssueCounts => ({ disapproved: 0, demoted: 0, not_impacted: 0 });++/**+ * Merchant Center's issues on the products' offers (00296: a row per issue,+ * destination and offer, an offer being a variant's external id), counted+ * per product by severity, each issue (code and attribute) once: one thing+ * to fix, though it is on every size and in Shopping ads and free listings+ * alike. Every variant and issue read, 100 ids and 1,000 rows a request.+ * Null without a Merchant Center account whose last sync went through+ * (hasMerchantCenter, as the editor's shopping check): its issues aren't+ * current then, if there are any.+ */+async function issuesOf(+ brandId: string,+ productIds: string[],+): Promise<Map<string, McpIssueCounts> | null> {+ if (!(await hasMerchantCenter(supabaseAdmin, brandId))) return null;+ const variants = await readForIds(productIds, (some) =>+ readCatalogRows<{ product_id: string; external_id: string }>(+ () =>+ supabaseAdmin+ .from('catalog_variants')+ .select('product_id, external_id')+ .eq('brand_id', brandId)+ .is('removed_at', null)+ .in('product_id', some)+ .order('id'),+ CARD_MAX_ROWS,+ ),+ );+ const productOf = new Map(variants.map((v) => [v.external_id, v.product_id]));+ const issues = await readForIds([...productOf.keys()], (some) =>+ readCatalogRows<{+ external_id: string;+ severity: string;+ code: string;+ attribute: string | null;+ }>(+ () =>+ supabaseAdmin+ .from('catalog_item_issues')+ .select('external_id, severity, code, attribute')+ .eq('brand_id', brandId)+ .in('external_id', some)+ .order('id'),+ CARD_MAX_ROWS,+ ),+ );++ const seen = new Map<string, Set<string>>();+ const counts = new Map<string, McpIssueCounts>();+ for (const issue of issues) {+ const product = productOf.get(issue.external_id);+ const severity = issue.severity as Severity;+ if (!product || !SEVERITIES.includes(severity)) continue;+ const key = JSON.stringify([severity, issue.code, issue.attribute]);+ const own = seen.get(product) ?? new Set<string>();+ if (own.has(key)) continue;+ own.add(key);+ seen.set(product, own);+ const tally = counts.get(product) ?? noIssues();+ tally[severity] += 1;+ counts.set(product, tally);+ }+ return counts;+}diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.tsindex a9cd0b3c6..3b75fd5fe 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -2472,7 +2472,7 @@ export const SHOPPING_NOT_IN_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> {+export async function planIncludes(organizationId: string, feature: Feature): Promise<boolean> {if (!isCloud()) return true;const { data, error } = await supabaseAdmin.from('organizations')diff --git a/web/src/lib/mcp/product-visibility-scope.test.ts b/web/src/lib/mcp/product-visibility-scope.test.tsnew file mode 100644index 000000000..a52c8b475--- /dev/null+++ b/web/src/lib/mcp/product-visibility-scope.test.ts@@ -0,0 +1,282 @@+// @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';++/**+ * Product Visibility over MCP (B6b), through the MCP client and the page's+ * own loaders: they run with the service role, which skips RLS, so each read+ * must keep to the brand by itself. The member's (RLS) client is never asked+ * for inside an MCP call, and every table read and RPC names the brand.+ */++const BRAND = '11111111-1111-1111-1111-111111111111';+const PRODUCT = '22222222-2222-2222-2222-222222222222';+const ORG = 'org-1';++/** One table read or RPC the service role was asked for: its builder calls, or its arguments. */+interface Read {+ table: string;+ calls: [string, ...unknown[]][];+ args?: Record<string, unknown>;+}++const db = vi.hoisted(() => ({+ reads: [] as Read[],+ tables: {} as Record<string, Record<string, unknown>[]>,+ rpcs: {} as Record<string, unknown>,+}));++// The service role: any PostgREST chain, answered from `db`, rows kept by their `eq` filters.+vi.mock('@/lib/supabase/admin', () => {+ const builder = (read: Read, answer: () => unknown) => {+ const rows = () => {+ const data = answer();+ if (!Array.isArray(data)) return data;+ return data.filter((row: Record<string, unknown>) =>+ read.calls.every(+ ([method, column, value]) =>+ method !== 'eq' || !(String(column) in row) || row[String(column)] === value,+ ),+ );+ };+ const chain: unknown = new Proxy(+ {},+ {+ get(_, prop) {+ if (typeof prop === 'symbol') return undefined;+ if (prop === 'then') {+ return (resolve: (value: unknown) => unknown, reject: (err: unknown) => unknown) => {+ const data = rows();+ const count = Array.isArray(data) ? data.length : null;+ return Promise.resolve({ data, error: null, count }).then(resolve, reject);+ };+ }+ if (prop === 'maybeSingle' || prop === 'single') {+ return async () => {+ const data = rows();+ return { data: Array.isArray(data) ? (data[0] ?? null) : data, error: null };+ };+ }+ return (...args: unknown[]) => {+ read.calls.push([prop, ...args]);+ return chain;+ };+ },+ },+ );+ return chain;+ };+ return {+ supabaseAdmin: {+ from: (table: string) => {+ const read: Read = { table, calls: [] };+ db.reads.push(read);+ return builder(read, () => db.tables[table] ?? []);+ },+ rpc: (name: string, args: Record<string, unknown>) => {+ const read: Read = { table: `rpc:${name}`, calls: [], args };+ db.reads.push(read);+ return builder(read, () => db.rpcs[name] ?? []);+ },+ },+ };+});++// The member's client: asked for inside an MCP call, it fails the read.+const createClient = vi.hoisted(() =>+ vi.fn(async () => {+ throw new Error('the RLS client inside an MCP call');+ }),+);+vi.mock('@/lib/supabase/server', () => ({ createClient }));++const { createMcpServer } = await import('./server');+const { SHOPPING_NOT_IN_PLAN } = await import('./data');++/** A client talking to a server built for one request, as the MCP route builds it. */+async function connect(organizationId = ORG) {+ const server = createMcpServer({+ userId: 'user-1',+ email: null,+ organizationId,+ apiKeyId: 'k',+ 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;++/** Every read keeps to the brand: its brand_id, the brand's own row, or the key's organization. */+const scoped = (read: Read) =>+ read.args+ ? read.args.p_brand_id === BRAND+ : read.calls.some(+ ([method, column, value]) =>+ method === 'eq' &&+ (read.table === 'organizations'+ ? column === 'id' && value === ORG+ : value === BRAND &&+ (column === 'brand_id' ||+ column === 'prompt_sets.brand_id' ||+ (read.table === 'brands' && column === 'id'))),+ );++beforeEach(() => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ createClient.mockClear();+ db.reads.length = 0;+ const now = new Date().toISOString();+ db.tables = {+ organizations: [+ { id: ORG, plan: 'growth', subscription_status: 'active', plan_overrides: null },+ ],+ brands: [{ id: BRAND, organization_id: ORG, openai_product_feed: false }],+ brand_domains: [{ brand_id: BRAND, country: 'US' }],+ prompts: [{ id: 'q1', regions: ['US-CA'] }],+ catalog_products: [+ {+ id: PRODUCT,+ brand_id: BRAND,+ title: 'Ridge Trail 2',+ url: 'https://shop.example/ridge',+ product_type: 'Trail running shoes',+ product_brand: 'Acme',+ description: null,+ },+ ],+ prompt_result_shopping_cards: [+ {+ id: 'c1',+ brand_id: BRAND,+ prompt_result_id: 'r1',+ position: 0,+ created_at: now,+ platform: 'chatgpt-shopping',+ region: 'US',+ product_title: 'Ridge Trail 2',+ product_brand: 'Acme',+ price_amount: 120,+ price_currency: 'USD',+ matched_brand_role: 'own',+ merchant_kind: 'own',+ catalog_product_id: PRODUCT,+ prompt_results: { prompt_id: 'q1', prompt: { id: 'q1', text: 'best trail shoes' } },+ },+ ],+ prompt_results: [+ {+ id: 'r1',+ brand_id: BRAND,+ platform: 'chatgpt-shopping',+ created_at: now,+ response: 'The Ridge Trail 2 grips well on wet rock.',+ prompt: { text: 'best trail shoes' },+ },+ ],+ };+ db.rpcs = {+ shopping_filter_options: [{ platforms: ['chatgpt-shopping'], regions: ['US'] }],+ };+});++afterEach(() => {+ vi.unstubAllEnvs();+ vi.restoreAllMocks();+});++describe('Product Visibility over MCP, with the service role', () => {+ it('reads the page’s loaders without the member’s client, every read naming the brand', async () => {+ const error = vi.spyOn(console, 'error');+ const client = await connect();+ const shelf = await client.callTool({+ name: 'get_shopping_shelf',+ arguments: { brand_id: BRAND },+ });+ const readiness = await client.callTool({+ name: 'get_shopping_readiness',+ arguments: { brand_id: BRAND },+ });+ const says = await client.callTool({+ name: 'get_product_ai_says',+ arguments: { brand_id: BRAND, product_id: PRODUCT },+ });+ for (const result of [shelf, readiness, says]) expect(result.isError, text(result)).toBeFalsy();++ // Readiness logs and leaves out a read that fails: none did.+ expect(JSON.parse(text(readiness))).toMatchObject({ unread: [] });+ expect(error).not.toHaveBeenCalled();+ expect(createClient).not.toHaveBeenCalled();+ expect(JSON.parse(text(shelf)).shelves[0]).toMatchObject({ own_rank: 1, products_total: 1 });+ expect(JSON.parse(text(says))).toMatchObject({ answers: 1 });++ expect(db.reads.filter((read) => !scoped(read))).toEqual([]);+ // What the page reads, read here too.+ expect(new Set(db.reads.map((read) => read.table))).toEqual(+ new Set([+ 'brands',+ 'organizations',+ 'brand_domains',+ 'prompts',+ 'prompt_result_shopping_cards',+ 'catalog_products',+ 'catalog_variants',+ 'catalog_images',+ 'catalog_product_categories',+ 'catalog_sources',+ 'prompt_results',+ 'prompt_result_citations',+ 'rpc:catalog_product_ai_stats',+ 'rpc:shopping_merchant_split',+ 'rpc:shopping_own_product_offers',+ 'rpc:shopping_amazon_share_weekly',+ 'rpc:shopping_filter_options',+ ]),+ );+ });++ it('answers a plan without Product Visibility as an error, before reading the brand’s data', async () => {+ db.tables.organizations[0].plan = 'starter';+ const client = await connect();+ for (const [name, args] of [+ ['get_shopping_shelf', { brand_id: BRAND }],+ ['get_shopping_readiness', { brand_id: BRAND }],+ ['get_product_ai_says', { brand_id: BRAND, product_id: PRODUCT }],+ ] as const) {+ const result = await client.callTool({ name, arguments: args });+ expect(result.isError, name).toBe(true);+ // The answer list_shopping_cards and get_product_visibility give.+ expect(JSON.parse(text(result)), name).toEqual(SHOPPING_NOT_IN_PLAN);+ expect(JSON.parse(text(result)).error, name).toBe('plan_limit');+ }+ expect(new Set(db.reads.map((read) => read.table))).toEqual(+ new Set(['brands', 'organizations']),+ );+ });++ it("answers another organization's brand, and a product not the brand's, as not found", async () => {+ const other = await connect('org-2');+ const shelf = await other.callTool({+ name: 'get_shopping_shelf',+ arguments: { brand_id: BRAND },+ });+ expect(shelf.isError).toBe(true);+ expect(text(shelf)).toBe('Brand not found');++ db.tables.catalog_products[0].brand_id = 'another-brand';+ const client = await connect();+ const says = await client.callTool({+ name: 'get_product_ai_says',+ arguments: { brand_id: BRAND, product_id: PRODUCT },+ });+ expect(says.isError).toBe(true);+ expect(text(says)).toBe('Brand or product not found');+ expect(db.reads.map((read) => read.table)).not.toContain('prompt_result_shopping_cards');+ });+});diff --git a/web/src/lib/mcp/product-visibility.test.ts b/web/src/lib/mcp/product-visibility.test.tsnew file mode 100644index 000000000..6e004651d--- /dev/null+++ b/web/src/lib/mcp/product-visibility.test.ts@@ -0,0 +1,548 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { McpAuthContext } from '@/lib/mcp-auth';+import type { ShoppingShelf } from '@/lib/actions/shopping';+import type { ProductRow } from '@/lib/shopping/products';+import type { ShelfRow } from '@/lib/shopping/shelf';++/**+ * Product Visibility over MCP (B6b): the Shelf with "Why not you?", the+ * Readiness checklist and a product's "What AI says", read by the page's own+ * loaders with the service role, for a brand of the key's organization on a+ * plan with Product Visibility.+ */++const brandInOrg = vi.hoisted(() => vi.fn());+// The plan check and its answer are the other shopping reads' own.+vi.mock('@/lib/mcp/data', async (importOriginal) => {+ const data = await importOriginal<typeof import('@/lib/mcp/data')>();+ return {+ brandInOrg,+ planIncludes: data.planIncludes,+ NOT_IN_PLAN: data.NOT_IN_PLAN,+ SHOPPING_NOT_IN_PLAN: data.SHOPPING_NOT_IN_PLAN,+ };+});++// The organization's plan row, and a catalog product, as the service role reads them.+const tables = vi.hoisted(() => ({+ organizations: [] as Record<string, unknown>[],+ catalog_products: [] as Record<string, unknown>[],+}));+const supabaseAdmin = vi.hoisted(() => ({+ from: (table: 'organizations' | 'catalog_products') => {+ const where: [string, unknown][] = [];+ const chain = {+ select: () => chain,+ eq: (column: string, value: unknown) => {+ where.push([column, value]);+ return chain;+ },+ maybeSingle: async () => ({+ data: tables[table].find((row) => where.every(([c, v]) => row[c] === v)) ?? null,+ error: null,+ }),+ };+ return chain;+ },+}));+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin }));++// The page's loaders; each records the client its dbClient() answers.+const { dbClient } =+ await vi.importActual<typeof import('@/lib/supabase/scoped')>('@/lib/supabase/scoped');+const clients: unknown[] = [];+const loader = <T>(answer: () => T) =>+ vi.fn(async () => {+ clients.push(await dbClient());+ return answer();+ });+const shopping = vi.hoisted(() => ({+ getShoppingShelf: vi.fn(),+ getShoppingProducts: vi.fn(),+ getProductAiSays: vi.fn(),+ getResellerPriceAlerts: vi.fn(),+ getShoppingAmazonShareDropAlert: vi.fn(),+ getShoppingFilterOptions: vi.fn(),+ getShoppingOwnChannels: vi.fn(),+}));+vi.mock('@/lib/actions/shopping', () => shopping);+const getBrandMarketCountries = vi.hoisted(() => vi.fn());+vi.mock('@/lib/actions/shopping-market', () => ({ getBrandMarketCountries }));+const getOpenAiIndexRead = vi.hoisted(() => vi.fn());+vi.mock('@/lib/actions/shopping-openai-index', () => ({ getOpenAiIndexRead }));+const readCatalogSources = vi.hoisted(() => vi.fn());+vi.mock('@/lib/shopping/catalog-read', () => ({ readCatalogSources }));++const { getProductAiSaysFor, getShoppingReadinessFor, getShoppingShelfFor } =+ await import('./product-visibility');+const { NOT_IN_PLAN, planIncludes, SHOPPING_NOT_IN_PLAN } = await import('./data');++const BRAND = '11111111-1111-1111-1111-111111111111';+const PRODUCT = '22222222-2222-2222-2222-222222222222';+const auth: McpAuthContext = {+ userId: 'user-1',+ email: null,+ organizationId: 'org-1',+ apiKeyId: 'key-1',+ role: 'admin',+};++const row = (over: Partial<ShelfRow>): ShelfRow => ({+ key: 'k',+ promptId: 'q1',+ promptText: 'best trail running shoes',+ platform: 'chatgpt-shopping',+ at: '2026-10-28T08:00:00Z',+ cards: [+ {+ rank: 1,+ title: 'Speedgoat 6',+ price: 155,+ currency: 'USD',+ rating: 4.6,+ reviews: 812,+ image: 'https://img.example/s6.jpg',+ merchant: 'hoka.com',+ own: false,+ via: null,+ productId: null,+ },+ ],+ ownRank: null,+ weekShelves: 3,+ weekOwnShelves: 0,+ ...over,+});++const product = (+ id: string,+ title: string,+ readiness = 80,+ kind = 'Trail running shoes',+): ProductRow => ({+ product: {+ id,+ title,+ url: `https://shop.example/${id}`,+ productType: kind,+ brand: 'Acme',+ description: null,+ image: null,+ category: `Apparel > ${kind}`,+ price: 120,+ currency: 'USD',+ inStock: true,+ hasGtin: true,+ },+ shelves: 0,+ winRate: null,+ avgRank: null,+ aiVisits: 0,+ orders: 0,+ revenue: null,+ currency: null,+ readiness,+ missing: readiness < 100 ? ['gtin'] : [],+ wrongPrice: null,+});++const shelf = (rows: ShelfRow[], catalogProducts: number | null = 2): ShoppingShelf => ({+ rows,+ stats: {+ slots: 12,+ ownSlots: 3,+ products: 2,+ fromCatalog: true,+ channels: [{ platform: 'google-aimode', ownSlots: 3 }],+ },+ catalogProducts,+});++beforeEach(() => {+ clients.length = 0;+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ brandInOrg.mockReset().mockResolvedValue(true);+ tables.organizations = [+ { id: 'org-1', plan: 'growth', subscription_status: 'active', plan_overrides: null },+ ];+ tables.catalog_products = [{ id: PRODUCT, brand_id: BRAND, title: 'Ridge Trail 2' }];+ getBrandMarketCountries.mockReset().mockResolvedValue(['US-CA', 'DE']);+ shopping.getShoppingShelf.mockReset();+ // No catalog, unless a test gives one.+ shopping.getShoppingProducts.mockReset().mockResolvedValue(null);+ shopping.getProductAiSays.mockReset();+ shopping.getResellerPriceAlerts.mockReset();+ shopping.getShoppingAmazonShareDropAlert.mockReset();+ shopping.getShoppingFilterOptions.mockReset();+ shopping.getShoppingOwnChannels.mockReset();+ getOpenAiIndexRead.mockReset();+ readCatalogSources.mockReset();+});++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('who may read it', () => {+ it("answers nothing for another organization's brand, and reads nothing", async () => {+ brandInOrg.mockResolvedValue(false);+ expect(await getShoppingShelfFor(auth, { brandId: BRAND })).toBeNull();+ expect(await getShoppingReadinessFor(auth, { brandId: BRAND })).toBeNull();+ expect(await getProductAiSaysFor(auth, { brandId: BRAND, productId: PRODUCT })).toBeNull();+ expect(shopping.getShoppingShelf).not.toHaveBeenCalled();+ expect(shopping.getProductAiSays).not.toHaveBeenCalled();+ });++ it('needs a plan with Product Visibility, as the page’s tabs do', async () => {+ tables.organizations[0].plan = 'starter';+ expect(await getShoppingShelfFor(auth, { brandId: BRAND })).toBe(NOT_IN_PLAN);+ expect(await getShoppingReadinessFor(auth, { brandId: BRAND })).toBe(NOT_IN_PLAN);+ expect(await getProductAiSaysFor(auth, { brandId: BRAND, productId: PRODUCT })).toBe(+ NOT_IN_PLAN,+ );+ expect(shopping.getShoppingShelf).not.toHaveBeenCalled();+ // The same check as the other shopping reads (list_shopping_cards,+ // get_product_visibility), so a client gets one answer: plan_limit.+ expect(await planIncludes('org-1', 'shopping_analytics')).toBe(false);+ expect(SHOPPING_NOT_IN_PLAN.error).toBe('plan_limit');+ });++ it('reads on for a trial that ended, as the read-only page does, and on a self-hosted one', async () => {+ shopping.getShoppingShelf.mockImplementation(loader(() => shelf([])));+ tables.organizations[0] = {+ ...tables.organizations[0],+ plan: 'growth',+ subscription_status: 'canceled',+ };+ expect(await getShoppingShelfFor(auth, { brandId: BRAND })).toMatchObject({ total: 0 });+ // Its own plan, ended, without Product Visibility stays locked.+ tables.organizations[0].plan = 'starter';+ expect(await getShoppingShelfFor(auth, { brandId: BRAND })).toBe(NOT_IN_PLAN);+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'false');+ expect(await getShoppingShelfFor(auth, { brandId: BRAND })).toMatchObject({ total: 0 });+ });+});++describe('get_shopping_shelf', () => {+ it("reads the page's shelves with the service role, on the brand's market", async () => {+ shopping.getShoppingShelf.mockImplementation(+ loader(() => shelf([row({ ownRank: 2, weekOwnShelves: 2 })])),+ );+ const page = await getShoppingShelfFor(auth, { brandId: BRAND, platform: 'chatgpt-shopping' });+ expect(clients).toEqual([supabaseAdmin]);+ expect(shopping.getShoppingShelf).toHaveBeenCalledWith(BRAND, {+ datePreset: '30d',+ platforms: ['chatgpt-shopping'],+ // A US state among the brand's countries opens the US market.+ chatgptMarket: 'us',+ });+ expect(page).toMatchObject({+ period: '30d',+ market: 'us',+ stats: {+ slots: 12,+ own_slots: 3,+ products: 2,+ from_catalog: true,+ channels: [{ platform: 'google-aimode', own_slots: 3 }],+ },+ catalog_products: 2,+ total: 1,+ next_offset: null,+ });+ expect(page !== NOT_IN_PLAN && page && 'shelves' in page && page.shelves[0]).toEqual({+ prompt_id: 'q1',+ prompt: 'best trail running shoes',+ platform: 'chatgpt-shopping',+ read_at: '2026-10-28T08:00:00Z',+ own_rank: 2,+ week_shelves: 3,+ week_own_shelves: 2,+ products: [+ {+ rank: 1,+ title: 'Speedgoat 6',+ price: 155,+ currency: 'USD',+ rating: 4.6,+ reviews: 812,+ merchant: 'hoka.com',+ own: false,+ via: null,+ product_id: null,+ },+ ],+ products_total: 1,+ why_not_you: null,+ });+ // The products for "Why not you?" are read beside the shelves, as the page does.+ expect(shopping.getShoppingProducts).toHaveBeenCalledWith(BRAND, {+ datePreset: '30d',+ platforms: ['chatgpt-shopping'],+ chatgptMarket: 'us',+ });+ });++ it('reads the products beside the shelves, and waits for them only when a shelf lacks the brand', async () => {+ let shelfDone: (value: ShoppingShelf) => void = () => {};+ shopping.getShoppingShelf.mockReturnValue(+ new Promise<ShoppingShelf>((resolve) => (shelfDone = resolve)),+ );+ shopping.getShoppingProducts.mockRejectedValue(new Error('timeout'));+ const read = getShoppingShelfFor(auth, { brandId: BRAND });+ await vi.waitFor(() => expect(shopping.getShoppingProducts).toHaveBeenCalled());+ // Every shelf has the brand: a failed products read is none of its business.+ shelfDone(shelf([row({ ownRank: 1 })]));+ expect(await read).toMatchObject({ total: 1 });+ // A shelf without it needs them: their read's failure is the call's.+ shopping.getShoppingShelf.mockResolvedValue(shelf([row({})]));+ await expect(getShoppingShelfFor(auth, { brandId: BRAND })).rejects.toThrow('timeout');+ });++ it("gives a shelf's first 10 products, and pages 10 shelves at a time, 50 at most", async () => {+ const cards = Array.from({ length: 12 }, (_, i) => ({ ...row({}).cards[0], rank: i + 1 }));+ shopping.getShoppingShelf.mockResolvedValue(+ shelf(+ Array.from({ length: 60 }, (_, i) =>+ row({ key: `k${i}`, promptId: `q${i}`, ownRank: 1, cards }),+ ),+ ),+ );+ const page = await getShoppingShelfFor(auth, { brandId: BRAND });+ if (!page || page === NOT_IN_PLAN || !('shelves' in page)) throw new Error('no shelves');+ expect(page).toMatchObject({ total: 60, next_offset: 10 });+ expect(page.shelves).toHaveLength(10);+ expect(page.shelves[0].products.map((p) => p.rank)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);+ expect(page.shelves[0].products_total).toBe(12);+ const most = await getShoppingShelfFor(auth, { brandId: BRAND, limit: 500 });+ expect(most !== NOT_IN_PLAN && most && 'shelves' in most && most.shelves).toHaveLength(50);+ });++ it('says which of its products a shelf it isn’t on asks for most', async () => {+ shopping.getShoppingShelf.mockResolvedValue(shelf([row({})]));+ shopping.getShoppingProducts.mockResolvedValue({+ total: 2,+ // The readier tee isn't what the question asks for.+ rows: [+ product('p-tee', 'Logo Tee', 100, 'T-shirts'),+ product('p-ridge', 'Ridge Trail 2 Running Shoes', 70),+ ],+ });+ const page = await getShoppingShelfFor(auth, { brandId: BRAND, market: 'europe' });+ expect(getBrandMarketCountries).not.toHaveBeenCalled();+ expect(shopping.getShoppingProducts).toHaveBeenCalledWith(BRAND, {+ datePreset: '30d',+ platforms: undefined,+ chatgptMarket: 'europe',+ });+ expect(+ page !== NOT_IN_PLAN && page && 'shelves' in page && page.shelves[0].why_not_you,+ ).toEqual({+ product_id: 'p-ridge',+ title: 'Ridge Trail 2 Running Shoes',+ url: 'https://shop.example/p-ridge',+ price: 120,+ currency: 'USD',+ readiness: { score: 70, missing: ['gtin'] },+ });+ });++ it('pages the shelves, keeps those it isn’t on when asked, and reads no market it can’t tell', async () => {+ getBrandMarketCountries.mockResolvedValue(['BR']);+ shopping.getShoppingShelf.mockResolvedValue(+ shelf(+ [+ row({ key: 'a', promptId: 'a' }),+ row({ key: 'b', promptId: 'b' }),+ row({ key: 'c', promptId: 'c', ownRank: 1 }),+ ],+ null,+ ),+ );+ const first = await getShoppingShelfFor(auth, { brandId: BRAND, limit: 2, period: '7d' });+ expect(first).toMatchObject({ market: null, period: '7d', total: 3, next_offset: 2 });+ expect(shopping.getShoppingShelf).toHaveBeenCalledWith(BRAND, {+ datePreset: '7d',+ platforms: undefined,+ chatgptMarket: undefined,+ });+ // No catalog: no "Why not you?" to give.+ expect(+ first !== NOT_IN_PLAN && first && 'shelves' in first && first.shelves[0].why_not_you,+ ).toBeNull();+ const absent = await getShoppingShelfFor(auth, { brandId: BRAND, absentOnly: true, offset: 1 });+ expect(absent).toMatchObject({ total: 2, next_offset: null });+ expect(+ absent !== NOT_IN_PLAN &&+ absent &&+ 'shelves' in absent &&+ absent.shelves.map((s) => s.prompt_id),+ ).toEqual(['b']);+ });+});++describe('get_shopping_readiness', () => {+ const source = { id: 's1', kind: 'shopify', format: 'shopify', products: 2 };++ beforeEach(() => {+ readCatalogSources.mockResolvedValue([source]);+ shopping.getShoppingProducts.mockResolvedValue({+ total: 2,+ rows: [product('p1', 'Ridge Trail 2'), product('p2', 'Logo Tee', 100)],+ });+ getOpenAiIndexRead.mockResolvedValue({ directFeed: false, ownCards: 4 });+ shopping.getResellerPriceAlerts.mockResolvedValue([{ product: 'Ridge Trail 2' }]);+ shopping.getShoppingAmazonShareDropAlert.mockResolvedValue(null);+ shopping.getShoppingFilterOptions.mockResolvedValue({+ platforms: ['chatgpt-shopping', 'google-aimode'],+ regions: [],+ });+ shopping.getShoppingOwnChannels.mockImplementation(loader(() => ['google-aimode']));+ });++ it('checks the catalog as the Readiness tab does, in its words, with where each fix starts', async () => {+ const read = await getShoppingReadinessFor(auth, { brandId: BRAND });+ expect(clients).toEqual([supabaseAdmin]);+ expect(readCatalogSources).toHaveBeenCalledWith(supabaseAdmin, BRAND);+ expect(getOpenAiIndexRead).toHaveBeenCalledWith(BRAND, '30d');+ if (!read || read === NOT_IN_PLAN || !('checks' in read)) throw new Error('no readiness');+ expect(read.market).toBe('us');+ expect(read.unread).toEqual([]);+ expect(typeof read.score).toBe('number');+ const check = (key: string) => read.checks.find((c) => c.key === key);+ expect(check('catalog')).toEqual({+ key: 'catalog',+ state: 'pass',+ title: 'Catalog connected',+ detail: '2 products from your feed, file or store.',+ fix: null,+ });+ expect(check('merchantCenter')).toMatchObject({ state: 'warn', fix: 'settings' });+ expect(check('openAiIndex')).toMatchObject({+ state: 'warn',+ title: "Catalog in OpenAI's product index",+ });+ expect(check('resellerCheaper')).toMatchObject({+ state: 'fail',+ title: 'Reseller cheaper than you · 1 product',+ });+ expect(check('amazonShare')).toBeUndefined();+ expect(read.channels).toEqual([+ { platform: 'chatgpt-shopping', state: 'notShowing' },+ { platform: 'google-aio', state: 'notTracked' },+ { platform: 'google-aimode', state: 'showing' },+ { platform: 'gemini-web', state: 'notTracked' },+ { platform: 'copilot-web', state: 'notTracked' },+ ]);+ // The channels from one row each, not the shelves' every card.+ expect(shopping.getShoppingOwnChannels).toHaveBeenCalledWith(BRAND, {+ datePreset: '30d',+ chatgptMarket: 'us',+ });+ expect(shopping.getShoppingShelf).not.toHaveBeenCalled();+ });++ it("says so when the channels can't be read, and keeps the checklist", async () => {+ shopping.getShoppingOwnChannels.mockRejectedValue(new Error('timeout'));+ vi.spyOn(console, 'error').mockImplementation(() => {});+ const read = await getShoppingReadinessFor(auth, { brandId: BRAND });+ if (!read || read === NOT_IN_PLAN || !('checks' in read)) throw new Error('no readiness');+ expect(read.channels).toBeNull();+ expect(read.unread).toEqual(['channels']);+ expect(typeof read.score).toBe('number');+ });++ it('writes a wrong price as a price', async () => {+ shopping.getShoppingProducts.mockResolvedValue({+ total: 1,+ rows: [+ {+ ...product('p1', 'Ridge Trail 2'),+ wrongPrice: { seen: 99, currency: 'USD', platform: 'chatgpt-shopping' },+ },+ ],+ });+ const read = await getShoppingReadinessFor(auth, { brandId: BRAND });+ if (!read || read === NOT_IN_PLAN || !('checks' in read)) throw new Error('no readiness');+ expect(read.checks.find((c) => c.key === 'wrongPrice')).toMatchObject({+ state: 'fail',+ detail: 'AI shows $99 for Ridge Trail 2, your price is $120.',+ fix: 'products',+ });+ });++ it("checks Europe without OpenAI's index, and gives no score when the products can't be read", async () => {+ shopping.getShoppingProducts.mockRejectedValue(new Error('timeout'));+ vi.spyOn(console, 'error').mockImplementation(() => {});+ const read = await getShoppingReadinessFor(auth, { brandId: BRAND, market: 'europe' });+ if (!read || read === NOT_IN_PLAN || !('checks' in read)) throw new Error('no readiness');+ expect(getOpenAiIndexRead).not.toHaveBeenCalled();+ expect(read.market).toBe('europe');+ expect(read.score).toBeNull();+ expect(read.unread).toEqual(['products']);+ expect(read.checks.map((c) => c.key)).not.toContain('openAiIndex');+ expect(read.checks.find((c) => c.key === 'merchantCenter')).toMatchObject({ state: 'fail' });+ });++ it("checks a brand with no market as the US's, without reading OpenAI's index for it", async () => {+ getBrandMarketCountries.mockResolvedValue(['BR']);+ const read = await getShoppingReadinessFor(auth, { brandId: BRAND });+ if (!read || read === NOT_IN_PLAN || !('checks' in read)) throw new Error('no readiness');+ expect(read.market).toBe('us');+ expect(getOpenAiIndexRead).not.toHaveBeenCalled();+ expect(read.checks.map((c) => c.key)).not.toContain('openAiIndex');+ expect(read.checks.map((c) => c.key)).toContain('verifiedSeller');+ });+});++describe('get_product_ai_says', () => {+ it("quotes what AI said about the brand's product, as its page does", async () => {+ shopping.getProductAiSays.mockImplementation(+ loader(() => ({+ answers: 3,+ quotes: [+ {+ text: 'The Ridge Trail 2 grips well on wet rock.',+ platform: 'chatgpt-shopping',+ at: '2026-10-27T10:00:00Z',+ promptText: 'best trail running shoes',+ },+ ],+ sources: [+ { url: 'https://runrepeat.com/ridge', domain: 'runrepeat.com', title: null, answers: 2 },+ ],+ })),+ );+ const says = await getProductAiSaysFor(auth, {+ brandId: BRAND,+ productId: PRODUCT,+ period: '90d',+ });+ expect(clients).toEqual([supabaseAdmin]);+ expect(shopping.getProductAiSays).toHaveBeenCalledWith(BRAND, PRODUCT, { datePreset: '90d' });+ expect(says).toEqual({+ product_id: PRODUCT,+ title: 'Ridge Trail 2',+ period: '90d',+ answers: 3,+ quotes: [+ {+ text: 'The Ridge Trail 2 grips well on wet rock.',+ platform: 'chatgpt-shopping',+ at: '2026-10-27T10:00:00Z',+ prompt: 'best trail running shoes',+ },+ ],+ sources: [+ { url: 'https://runrepeat.com/ridge', domain: 'runrepeat.com', title: null, answers: 2 },+ ],+ });+ });++ it("answers nothing for a product that isn't the brand's", async () => {+ tables.catalog_products = [{ id: PRODUCT, brand_id: 'another-brand', title: 'Ridge Trail 2' }];+ expect(await getProductAiSaysFor(auth, { brandId: BRAND, productId: PRODUCT })).toBeNull();+ expect(shopping.getProductAiSays).not.toHaveBeenCalled();+ });+});diff --git a/web/src/lib/mcp/product-visibility.ts b/web/src/lib/mcp/product-visibility.tsnew file mode 100644index 000000000..5fcde0665--- /dev/null+++ b/web/src/lib/mcp/product-visibility.ts@@ -0,0 +1,409 @@+import { createTranslator } from 'next-intl';+import messages from '../../../messages/en.json';+import {+ getProductAiSays,+ getResellerPriceAlerts,+ getShoppingAmazonShareDropAlert,+ getShoppingFilterOptions,+ getShoppingOwnChannels,+ getShoppingProducts,+ getShoppingShelf,+ type ShoppingDatePreset,+ type ShoppingFilters,+} from '@/lib/actions/shopping';+import { getBrandMarketCountries } from '@/lib/actions/shopping-market';+import { getOpenAiIndexRead } from '@/lib/actions/shopping-openai-index';+import type { McpAuthContext } from '@/lib/mcp-auth';+import { readCatalogSources } from '@/lib/shopping/catalog-read';+import { defaultMarket, type ShoppingMarket } from '@/lib/shopping/markets';+import type { ProductRow, ReadinessCheck } from '@/lib/shopping/products';+import {+ READINESS_CHANNELS,+ channelState,+ copyValues,+ readinessChecklist,+ type ChannelState,+ type CheckState,+ type ReadinessKey,+} from '@/lib/shopping/readiness';+import { whyNotYou } from '@/lib/shopping/shelf';+import { supabaseAdmin } from '@/lib/supabase/admin';+import { dbClient, withDbClient } from '@/lib/supabase/scoped';+import { NOT_IN_PLAN, brandInOrg, planIncludes } from './data';++/**+ * Product Visibility over MCP (plan B6b): the Shelf with "Why not you?", the+ * Readiness checklist and a product's "What AI says", read by the page's own+ * loaders (lib/actions/shopping*.ts) with the service role once the brand is+ * the key's, so the tools and the page can't drift apart. Like the page's+ * tabs they need a plan with Product Visibility (shopping_analytics).+ */++/** The windows a read takes, as the page's date filter. */+export const PV_PERIODS: readonly ShoppingDatePreset[] = ['7d', '30d', '90d', 'all'];++const SHELVES_DEFAULT = 10;+const SHELVES_MAX = 50;+/** A shelf's products given, from the top; `products_total` counts them all. */+const SHELF_PRODUCTS = 10;++/** The page's loaders, with the service role in their dbClient(). */+const asService = <T>(read: () => Promise<T>) =>+ withDbClient(supabaseAdmin as unknown as Awaited<ReturnType<typeof dbClient>>, read);++/**+ * Null for another organization's brand, NOT_IN_PLAN without Product+ * Visibility, else nothing in the way. The plan check is the other shopping+ * reads' (planIncludes): the plan the organization is on, as the page reads+ * it, so a trial or subscription that ended leaves the reads open.+ */+async function access(+ auth: McpAuthContext,+ brandId: string,+): Promise<null | typeof NOT_IN_PLAN | true> {+ if (!(await brandInOrg(auth, brandId))) return null;+ return (await planIncludes(auth.organizationId!, 'shopping_analytics')) ? true : NOT_IN_PLAN;+}++/**+ * The ChatGPT Shopping market to read: the one asked, else the brand's own+ * (its domains' and prompts' countries), as the page opens on. A failed read+ * makes no claim, as on the page: no market.+ */+async function marketOf(brandId: string, asked?: ShoppingMarket): Promise<ShoppingMarket | null> {+ if (asked) return asked;+ return getBrandMarketCountries(brandId).then(defaultMarket, (err: unknown) => {+ console.error('[mcp] Failed to read the brand market:', err);+ return null;+ });+}++// ─── The Shelf (ECOM-006) and "Why not you?" ───++/** A product on a shelf. */+export interface McpShelfProduct {+ /** Its place on the shelf, from 1. */+ rank: number;+ title: string;+ price: number | null;+ currency: string | null;+ rating: number | null;+ reviews: number | null;+ merchant: string | null;+ /** One of the brand's own products. */+ own: boolean;+ /** The marketplace an own product was linked through ("Amazon"), else null. */+ via: string | null;+ /** Its catalog product, when matched. */+ product_id: string | null;+}++/** "Why not you?": the brand's product the question asks for most, on a shelf it isn't on. */+export interface McpWhyNotYou {+ product_id: string;+ title: string;+ url: string | null;+ price: number | null;+ currency: string | null;+ /** Its readiness for AI shopping, 0–100, and the checks it misses. */+ readiness: { score: number; missing: ReadinessCheck[] };+}++/** One shopping question on one channel: its latest shelf, and the brand's last 7 days on it. */+export interface McpShelf {+ prompt_id: string;+ prompt: string;+ platform: string;+ /** When its latest shelf was read. */+ read_at: string;+ /** The brand's best place on the latest shelf; null when it isn't on it. */+ own_rank: number | null;+ week_shelves: number;+ week_own_shelves: number;+ /** Its first SHELF_PRODUCTS products, from the top. */+ products: McpShelfProduct[];+ /** Every product on the shelf. */+ products_total: number;+ why_not_you: McpWhyNotYou | null;+}++export interface McpShelfPage {+ period: ShoppingDatePreset;+ /** The ChatGPT Shopping market read; null when the brand has none. */+ market: ShoppingMarket | null;+ /** The brand's place on every shelf in the period. */+ stats: {+ slots: number;+ own_slots: number;+ /** Its distinct products on the shelves: catalog products when matched, else titles. */+ products: number;+ from_catalog: boolean;+ channels: { platform: string; own_slots: number }[];+ };+ /** The brand's live catalog products; null without a catalog. */+ catalog_products: number | null;+ /** The shelves that match, those it isn't on first, then where it ranks lowest. */+ total: number;+ shelves: McpShelf[];+ next_offset: number | null;+}++export async function getShoppingShelfFor(+ auth: McpAuthContext,+ params: {+ brandId: string;+ period?: ShoppingDatePreset;+ platform?: string;+ market?: ShoppingMarket;+ absentOnly?: boolean;+ limit?: number;+ offset?: number;+ },+): Promise<McpShelfPage | typeof NOT_IN_PLAN | null> {+ const allowed = await access(auth, params.brandId);+ if (allowed !== true) return allowed;+ const period = params.period ?? '30d';+ const limit = Math.min(Math.max(params.limit ?? SHELVES_DEFAULT, 1), SHELVES_MAX);+ const offset = Math.max(params.offset ?? 0, 0);++ return asService(async () => {+ const market = await marketOf(params.brandId, params.market);+ const filters: ShoppingFilters = {+ datePreset: period,+ platforms: params.platform ? [params.platform] : undefined,+ chatgptMarket: market ?? undefined,+ };+ // "Why not you?" picks from the products the page's Products table reads+ // over the same window: read beside the shelves, as the page does, and+ // waited for only when a shelf on this page lacks the brand's products.+ const productsRead = getShoppingProducts(params.brandId, filters).then(+ (read) => ({ rows: read?.rows ?? [] }),+ (err: unknown) => ({ err }),+ );+ const shelf = await getShoppingShelf(params.brandId, filters);+ const rows = params.absentOnly ? shelf.rows.filter((row) => row.ownRank === null) : shelf.rows;+ const page = rows.slice(offset, offset + limit);+ let products: readonly ProductRow[] = [];+ if (shelf.catalogProducts && page.some((row) => row.ownRank === null)) {+ const read = await productsRead;+ if ('err' in read) throw read.err;+ products = read.rows;+ }++ return {+ period,+ market,+ stats: {+ slots: shelf.stats.slots,+ own_slots: shelf.stats.ownSlots,+ products: shelf.stats.products,+ from_catalog: shelf.stats.fromCatalog,+ channels: shelf.stats.channels.map((c) => ({+ platform: c.platform,+ own_slots: c.ownSlots,+ })),+ },+ catalog_products: shelf.catalogProducts,+ total: rows.length,+ shelves: page.map((row) => {+ const missing = whyNotYou(row, products);+ return {+ prompt_id: row.promptId,+ prompt: row.promptText,+ platform: row.platform,+ read_at: row.at,+ own_rank: row.ownRank,+ week_shelves: row.weekShelves,+ week_own_shelves: row.weekOwnShelves,+ products: row.cards.slice(0, SHELF_PRODUCTS).map((card) => ({+ rank: card.rank,+ title: card.title,+ price: card.price,+ currency: card.currency,+ rating: card.rating,+ reviews: card.reviews,+ merchant: card.merchant,+ own: card.own,+ via: card.via,+ product_id: card.productId,+ })),+ products_total: row.cards.length,+ why_not_you: missing && {+ product_id: missing.product.id,+ title: missing.product.title,+ url: missing.product.url,+ price: missing.product.price,+ currency: missing.product.currency,+ readiness: { score: missing.readiness, missing: missing.missing },+ },+ };+ }),+ next_offset: offset + page.length < rows.length ? offset + page.length : null,+ };+ });+}++// ─── Readiness (ECOM-015) ───++const checkCopy = createTranslator({+ locale: 'en',+ messages,+ namespace: 'shopping.readiness.checks',+});++export interface McpReadinessCheck {+ key: ReadinessKey;+ state: CheckState;+ /** The check and what it found, as the Readiness tab writes them. */+ title: string;+ detail: string | null;+ /** Where its fix starts: the Products tab, or Settings › Integrations › Catalog. */+ fix: 'products' | 'settings' | null;+}++export interface McpReadiness {+ /** The market the checks are for: OpenAI's index and the verified seller are the US's. */+ market: ShoppingMarket;+ period: ShoppingDatePreset;+ /** 0–100 over the checks that could be made; null when a read below failed. */+ score: number | null;+ checks: McpReadinessCheck[];+ /** Each AI channel: the brand's products on its shelves, shelves without them, or none read. */+ channels: { platform: string; state: ChannelState }[] | null;+ /**+ * The reads that failed: the catalog's sources or its products (no score:+ * it would be another one without them), or which channels hold its+ * products (no channels).+ */+ unread: ('sources' | 'products' | 'channels')[];+}++/** A read the checklist can do without: null, logged, when it fails. */+const orNull = <T>(what: string, read: Promise<T>): Promise<T | null> =>+ read.catch((err: unknown) => {+ console.error(`[mcp] Readiness: failed to read ${what}:`, err);+ return null;+ });++export async function getShoppingReadinessFor(+ auth: McpAuthContext,+ params: { brandId: string; period?: ShoppingDatePreset; market?: ShoppingMarket },+): Promise<McpReadiness | typeof NOT_IN_PLAN | null> {+ const allowed = await access(auth, params.brandId);+ if (allowed !== true) return allowed;+ const period = params.period ?? '30d';+ const { brandId } = params;++ return asService(async () => {+ const own = await marketOf(brandId, params.market);+ const market = own ?? 'us';+ const filters: ShoppingFilters = { datePreset: period, chatgptMarket: own ?? undefined };+ const [sources, products, openAi, cheaper, amazonDrop, options, ownOn] = await Promise.all([+ orNull('catalog sources', readCatalogSources(supabaseAdmin, brandId)),+ getShoppingProducts(brandId, filters).then(+ (read) => read?.rows ?? null,+ (err: unknown) => {+ console.error('[mcp] Readiness: failed to read the products:', err);+ return 'failed' as const;+ },+ ),+ // As on the page: only for a brand in the US market, not one that just falls back to it.+ own === 'us' ? orNull('the OpenAI index', getOpenAiIndexRead(brandId, period)) : null,+ orNull('reseller prices', getResellerPriceAlerts(brandId, filters)),+ orNull('the Amazon share', getShoppingAmazonShareDropAlert(brandId)),+ getShoppingFilterOptions(brandId),+ // Which channels hold its products: one row a channel, not every card on the shelves.+ orNull('the channels', getShoppingOwnChannels(brandId, filters)),+ ]);+ const { score, items } = readinessChecklist({+ market,+ catalog: sources,+ products: products === 'failed' ? null : products,+ openAi,+ cheaperResellers: cheaper?.length ?? null,+ amazonDrop: amazonDrop ? { from: amazonDrop.fromShare, to: amazonDrop.toShare } : null,+ });+ const unread: McpReadiness['unread'] = [+ ...(sources === null ? (['sources'] as const) : []),+ ...(products === 'failed' ? (['products'] as const) : []),+ ...(ownOn === null ? (['channels'] as const) : []),+ ];+ // channelState asks for the brand's slots on each channel: one at least, where it has any.+ const ownSlots = new Map((ownOn ?? []).map((platform) => [platform, 1]));++ return {+ market,+ period,+ score: sources === null || products === 'failed' ? null : score,+ checks: items.map((item) => {+ const values = copyValues(item);+ const detail = `${item.key}.${item.state}` as const;+ return {+ key: item.key,+ state: item.state,+ title: checkCopy(`${item.key}.title` as never, values as never),+ detail: checkCopy.has(detail as never)+ ? checkCopy(detail as never, values as never)+ : null,+ fix: item.action ?? null,+ };+ }),+ channels: ownOn+ ? READINESS_CHANNELS.map((platform) => ({+ platform,+ state: channelState(platform, options.platforms, ownSlots),+ }))+ : null,+ unread,+ };+ });+}++// ─── What AI says (ECOM-012) ───++export interface McpProductAiSays {+ product_id: string;+ title: string;+ period: ShoppingDatePreset;+ /** The AI answers that showed the product in the period. */+ answers: number;+ /** Where they name it, in their own words, the latest first. */+ quotes: { text: string; platform: string; at: string; prompt: string | null }[];+ /** The pages they cited most, with how many of those answers cited each. */+ sources: { url: string; domain: string; title: string | null; answers: number }[];+}++export async function getProductAiSaysFor(+ auth: McpAuthContext,+ params: { brandId: string; productId: string; period?: ShoppingDatePreset },+): Promise<McpProductAiSays | typeof NOT_IN_PLAN | null> {+ const allowed = await access(auth, params.brandId);+ if (allowed !== true) return allowed;+ const { data: product, error } = await supabaseAdmin+ .from('catalog_products')+ .select('id, title')+ .eq('brand_id', params.brandId)+ .eq('id', params.productId)+ .maybeSingle();+ if (error) throw new Error(error.message);+ if (!product) return null;+ const period = params.period ?? '30d';++ // As the product's page reads it: every market.+ const says = await asService(() =>+ getProductAiSays(params.brandId, params.productId, { datePreset: period }),+ );+ return {+ product_id: product.id as string,+ title: product.title as string,+ period,+ answers: says.answers,+ quotes: says.quotes.map((quote) => ({+ text: quote.text,+ platform: quote.platform,+ at: quote.at,+ prompt: quote.promptText,+ })),+ sources: says.sources,+ };+}diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex ec9c8f7c2..d47b81018 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -83,6 +83,12 @@ import { getActionScorecardFor } from './learning';import { getContentPlanFor } from './content-plan';import { markContentDraftPublishedFor } from './content-delivery';import { PLAN_CARDS, PLAN_PERIODS } from '@/lib/content/plan';+import { getCatalogSourcesFor, listCatalogProductsFor } from './catalog';+import {+ getProductAiSaysFor,+ getShoppingReadinessFor,+ getShoppingShelfFor,+} from './product-visibility';/*** Build a fresh MCP server bound to a single authenticated request.@@ -1902,5 +1908,165 @@ export function createMcpServer(auth: McpAuthContext): McpServer {},);+ // ─── The product catalog (B6a) ───++ server.registerTool(+ 'get_catalog_sources',+ {+ title: 'Catalog sources',+ description:+ "Where the brand's product catalog is read from, as Settings › Integrations › Catalog shows it: each source's kind (a feed URL, an upload, or a connected store such as Shopify or Google Merchant Center), its address or account, and its last sync — when, its status (ok, failed, format_error, or auth_failed when the store refused the saved sign-in), the error, and what it read (items, skipped and why, products added/changed/removed, Merchant Center issues, products past the plan's cap) — and how many of its products are in the catalog now. Empty for a brand with no catalog.",+ inputSchema: {+ brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),+ },+ annotations: { readOnlyHint: true, openWorldHint: false },+ },+ async (args) => {+ const sources = await getCatalogSourcesFor(auth, args.brand_id);+ return sources ? json(sources) : notFound('Brand');+ },+ );++ server.registerTool(+ 'list_catalog_products',+ {+ title: 'Catalog products',+ description:+ "The brand's live catalog products, by title, as Product Visibility reads them: title, page, brand, product type, category, photo, lowest price in stock, in stock, GTIN; `readiness` for AI shopping (`score` 0–100; `missing`, the checks it fails: gtin, image, inStock, price, description, typeFirst — what the product is in its description's first 40 words — category, brand; `unknown`, those that can't be made, such as typeFirst without a product type, left out of the score); its Google Merchant Center issues by severity (disapproved, demoted, not_impacted), each issue once however many of its variants and destinations it is on (null without a Merchant Center account whose last sync went through); and over the last 30 days the AI visits its page got, the orders they led to and their revenue (`revenue_30d` in `revenue_currency`, null without orders). `search` narrows to titles containing it, as written. Paged: `limit` (default 50, max 200) and `offset`; `next_offset` is null on the last page, `total` counts the matches.",+ inputSchema: {+ brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),+ search: z.string().max(200).optional().describe('Only products whose title contains it.'),+ limit: z+ .number()+ .int()+ .min(1)+ .max(200)+ .optional()+ .describe('Products 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 page = await listCatalogProductsFor(auth, {+ brandId: args.brand_id,+ search: args.search,+ limit: args.limit,+ offset: args.offset,+ });+ return page ? json(page) : notFound('Brand');+ },+ );++ // ─── Product Visibility: Shelf, Readiness, What AI says (B6b) ───++ const periodInput = z+ .enum(['7d', '30d', '90d', 'all'])+ .optional()+ .describe("The window, as the page's date filter: 7d, 30d (default), 90d or all.");+ const marketInput = z+ .enum(['us', 'europe'])+ .optional()+ .describe(+ "ChatGPT Shopping's market: us or europe. Defaults to the brand's own (its domains' and prompts' countries), as the page opens on.",+ );+ /** A brand outside the key's organization, or a plan without Product Visibility. */+ const pvAnswer = <T>(read: T | typeof NOT_IN_PLAN | null, missing = 'Brand') =>+ read === null+ ? notFound(missing)+ : read === NOT_IN_PLAN+ ? {+ content: [+ { type: 'text' as const, text: JSON.stringify(SHOPPING_NOT_IN_PLAN, null, 2) },+ ],+ isError: true,+ }+ : json(read);++ server.registerTool(+ 'get_shopping_shelf',+ {+ title: 'Product Visibility shelf',+ description:+ "Product Visibility's Shelf: for each shopping question the brand tracks, on each AI channel, the first 10 products the latest answer put on its \"shelf\", in order (rank, title, price, rating, reviews, merchant; `own` for the brand's own, `via` the marketplace it was linked through, `product_id` its catalog product when matched) and `products_total`, every product on it; the brand's best place on it (`own_rank`, which can be past the first 10; null when it isn't on it) and its last 7 days there (`week_own_shelves` of `week_shelves`). The shelves it isn't on come first, then where it ranks lowest. A shelf it isn't on has `why_not_you`: its catalog product the question asks for most, with its readiness for AI shopping (score 0–100 and the checks it misses: gtin, image, inStock, price, description, typeFirst, category, brand); null when none fits. `stats` counts the product slots in the period's answers, those holding the brand's products, its distinct products there, and its slots by channel; `catalog_products` the live catalog (null without one). `absent_only` keeps the shelves it isn't on. Paged: `limit` (default 10, max 50) and `offset`; `total` counts the matching shelves. Needs a plan with Product Visibility (Growth and above): on Starter it answers plan_limit.",+ inputSchema: {+ brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),+ period: periodInput,+ platform: z+ .string()+ .max(64)+ .optional()+ .describe('One AI channel, e.g. "chatgpt-shopping", "google-aimode", "google-aio".'),+ market: marketInput,+ absent_only: z+ .boolean()+ .optional()+ .describe("Only the shelves the brand's products aren't on."),+ limit: z.number().int().min(1).max(50).optional().describe('Shelves a page (default 10).'),+ offset: z.number().int().min(0).optional().describe('Where the page starts (default 0).'),+ },+ annotations: { readOnlyHint: true, openWorldHint: false },+ },+ async (args) =>+ pvAnswer(+ await getShoppingShelfFor(auth, {+ brandId: args.brand_id,+ period: args.period,+ platform: args.platform,+ market: args.market,+ absentOnly: args.absent_only,+ limit: args.limit,+ offset: args.offset,+ }),+ ),+ );++ server.registerTool(+ 'get_shopping_readiness',+ {+ title: 'Product Visibility readiness',+ description:+ "Product Visibility's Readiness: how ready the brand is for AI shopping, as the Readiness tab checks it, scored 0–100 over the checks that can be made (`score`; null when its catalog's sources or products couldn't be read, listed in `unread`). Each check has its `key` (catalog, merchantCenter, openAiIndex and verifiedSeller in the US, firstWords, feedFields, feedLinks, wrongPrice, resellerCheaper, amazonShare), its `state` (pass, warn, fail, or unknown when it can't be made), its `title` and `detail` as the page writes them, and `fix`: where it starts (products = the Products tab, settings = Settings › Integrations › Catalog). `channels` says for each AI channel (chatgpt-shopping, google-aio, google-aimode, gemini-web, copilot-web) whether the brand's products are on its shelves (showing), its shelves are read without them (notShowing), or it isn't tracked (notTracked). Needs a plan with Product Visibility (Growth and above): on Starter it answers plan_limit.",+ inputSchema: {+ brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),+ period: periodInput,+ market: marketInput,+ },+ annotations: { readOnlyHint: true, openWorldHint: false },+ },+ async (args) =>+ pvAnswer(+ await getShoppingReadinessFor(auth, {+ brandId: args.brand_id,+ period: args.period,+ market: args.market,+ }),+ ),+ );++ server.registerTool(+ 'get_product_ai_says',+ {+ title: 'What AI says about a product',+ description:+ "What AI says about one of the brand's catalog products, as its Product Visibility page shows it: how many AI answers showed it in the period, up to 5 quotes where they name it (their own words, the latest first, with the channel, when, and the question asked) and up to 5 pages they cited most (url, domain, title, and how many of those answers cited each). Answers are quoted, not summed up. The product_id comes from list_catalog_products or a shelf's product_id. Needs a plan with Product Visibility (Growth and above): on Starter it answers plan_limit.",+ inputSchema: {+ brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),+ product_id: relaxedUuid.describe('Catalog product UUID, from list_catalog_products.'),+ period: periodInput,+ },+ annotations: { readOnlyHint: true, openWorldHint: false },+ },+ async (args) =>+ pvAnswer(+ await getProductAiSaysFor(auth, {+ brandId: args.brand_id,+ productId: args.product_id,+ period: args.period,+ }),+ 'Brand or product',+ ),+ );+return server;}diff --git a/web/src/lib/mcp/subscription-gate.test.ts b/web/src/lib/mcp/subscription-gate.test.tsindex ad6c7c997..50a224090 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(40);+ expect(names.filter(isReadTool)).toHaveLength(45);expect(names.filter((name) => !isReadTool(name)).sort()).toEqual(['accept_prompt_suggestion','accept_topic_suggestion',diff --git a/web/src/lib/shopping/catalog-read.ts b/web/src/lib/shopping/catalog-read.tsnew file mode 100644index 000000000..7c66bdf77--- /dev/null+++ b/web/src/lib/shopping/catalog-read.ts@@ -0,0 +1,261 @@+import type { SupabaseClient } from '@supabase/supabase-js';+import {+ MERCHANT_CENTER_KIND,+ catalogSourceKey,+ type CatalogCounts,+ type CatalogFormat,+ type CatalogSource,+ type CatalogSourceKind,+ type CatalogSyncStatus,+} from '@/lib/catalog';+import type { CatalogProductRow } from '@/lib/shopping/products';++/**+ * A brand's catalog as Product Visibility reads it (#1263, 00278): its live+ * products with their variants' stock, price and GTIN, first photo and+ * category, in `.range()` pages. Through the client given: the member's+ * session for Product Visibility, the service role for the MCP's+ * list_catalog_products once the brand is the key's.+ */++/** Catalog products the table reads at most. */+export const PRODUCTS_TABLE_MAX = 2000;+const CATALOG_PAGE = 1000;+/** Product ids one catalog read filters by: each request's address stays short. */+const IDS_PER_READ = 100;+/** Such reads in flight at once. */+const ID_READS_AT_ONCE = 6;+const IN_STOCK = new Set(['in_stock', 'instock', 'available', 'limited_availability']);+/**+ * Rows one paged read takes at most, so a pathological brand can't pin the+ * server action: Product Visibility's card reads and a catalog read for some ids.+ */+export const CARD_MAX_ROWS = 50_000;++/** Every row of a brand's catalog table, in `.range()` pages, up to `max`. */+export async function readCatalogRows<T>(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- PostgREST builder generics+ build: () => any,+ max: number,+): Promise<T[]> {+ const rows: T[] = [];+ for (let start = 0; start < max; start += CATALOG_PAGE) {+ const { data, error } = await build().range(start, Math.min(start + CATALOG_PAGE, max) - 1);+ if (error) throw new Error(error.message);+ rows.push(...((data ?? []) as T[]));+ if ((data ?? []).length < CATALOG_PAGE) break;+ }+ return rows;+}++/** A catalog table's rows for these ids: IDS_PER_READ ids a read, ID_READS_AT_ONCE reads at a time. */+export async function readForIds<T>(+ ids: readonly string[],+ read: (some: string[]) => Promise<T[]>,+) {+ const slices: string[][] = [];+ for (let i = 0; i < ids.length; i += IDS_PER_READ) slices.push(ids.slice(i, i + IDS_PER_READ));+ const out: T[][] = [];+ let next = 0;+ await Promise.all(+ Array.from({ length: Math.min(ID_READS_AT_ONCE, slices.length) }, async () => {+ while (next < slices.length) {+ const at = next++;+ out[at] = await read(slices[at]);+ }+ }),+ );+ return out.flat();+}++/**+ * The brand's live catalog products as Product Visibility reads them, with+ * their variants' stock, price and GTIN, first photo and category: the+ * whole catalog (up to PRODUCTS_TABLE_MAX) for `ids` null, else the products+ * `ids` names, their rows read IDS_PER_READ ids at a time.+ */+export async function readCatalogProducts(+ supabase: SupabaseClient,+ brandId: string,+ ids: readonly string[] | null,+): Promise<CatalogProductRow[]> {+ // Each table read for the whole catalog, or for the ids, a slice at a time.+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- PostgREST builder generics+ const each = <T>(column: string, build: () => any, max: number): Promise<T[]> =>+ ids === null+ ? readCatalogRows<T>(build, max)+ : readForIds(ids, (some) =>+ readCatalogRows<T>(() => build().in(column, some), CARD_MAX_ROWS),+ );+ const [products, variants, images, categories] = await Promise.all([+ each<{+ id: string;+ title: string;+ url: string | null;+ product_type: string | null;+ product_brand: string | null;+ description: string | null;+ }>(+ 'id',+ () =>+ supabase+ .from('catalog_products')+ .select('id, title, url, product_type, product_brand, description')+ .eq('brand_id', brandId)+ .is('removed_at', null)+ .order('id'),+ PRODUCTS_TABLE_MAX,+ ),+ each<{+ product_id: string;+ gtin: string | null;+ price: number | null;+ sale_price: number | null;+ currency: string | null;+ availability: string | null;+ }>(+ 'product_id',+ () =>+ supabase+ .from('catalog_variants')+ .select('product_id, gtin, price, sale_price, currency, availability')+ .eq('brand_id', brandId)+ .is('removed_at', null)+ .order('id'),+ CARD_MAX_ROWS,+ ),+ each<{ product_id: string; url: string; position: number }>(+ 'product_id',+ () =>+ supabase+ .from('catalog_images')+ .select('product_id, url, position')+ .eq('brand_id', brandId)+ .order('id'),+ CARD_MAX_ROWS,+ ),+ each<{ product_id: string; category: { name: string } | null }>(+ 'product_id',+ () =>+ supabase+ .from('catalog_product_categories')+ .select('product_id, category:category_id ( name )')+ .eq('brand_id', brandId)+ .order('product_id')+ .order('category_id'),+ CARD_MAX_ROWS,+ ),+ ]);++ const variantsOf = new Map<string, typeof variants>();+ for (const v of variants) {+ if (!variantsOf.has(v.product_id)) variantsOf.set(v.product_id, []);+ variantsOf.get(v.product_id)!.push(v);+ }+ const imageOf = new Map<string, { url: string; position: number }>();+ for (const image of images) {+ const kept = imageOf.get(image.product_id);+ if (!kept || image.position < kept.position) imageOf.set(image.product_id, image);+ }+ const categoryOf = new Map<string, string>();+ for (const row of categories) {+ if (row.category?.name && !categoryOf.has(row.product_id)) {+ categoryOf.set(row.product_id, row.category.name);+ }+ }+ return products.map((p) => {+ const own = variantsOf.get(p.id) ?? [];+ const stocked = own.filter((v) =>+ IN_STOCK.has(+ String(v.availability ?? '')+ .toLowerCase()+ .replace(/[\s-]+/g, '_'),+ ),+ );+ const priced = (stocked.length ? stocked : own)+ .map((v) => ({ price: v.sale_price ?? v.price, currency: v.currency }))+ .filter((v): v is { price: number; currency: string | null } => v.price !== null)+ .sort((a, b) => a.price - b.price);+ return {+ id: p.id,+ title: p.title,+ url: p.url,+ productType: p.product_type,+ brand: p.product_brand,+ description: p.description,+ image: imageOf.get(p.id)?.url ?? null,+ category: categoryOf.get(p.id) ?? null,+ price: priced[0] ? Number(priced[0].price) : null,+ currency: priced[0]?.currency ?? null,+ // Each variant's price and sale price, in or out of stock.+ prices: own.flatMap((v) =>+ [v.price, v.sale_price]+ .filter((price): price is number => price !== null)+ .map((price) => ({ price: Number(price), currency: v.currency })),+ ),+ inStock: stocked.length > 0,+ hasGtin: own.some((v) => !!v.gtin),+ };+ });+}++/** The brand's sources, oldest first, each with its live products in the catalog. */+export async function readCatalogSources(+ supabase: SupabaseClient,+ brandId: string,+): Promise<CatalogSource[]> {+ const { data, error } = await supabase+ .from('catalog_sources')+ .select(+ 'id, kind, format, url, account, label, last_synced_at, last_status, last_error, last_counts',+ )+ .eq('brand_id', brandId)+ .order('created_at', { ascending: true });+ if (error) throw new Error(error.message);+ return Promise.all(+ (data ?? []).map(async (row) => {+ const { count } = await supabase+ .from('catalog_products')+ .select('id', { count: 'exact', head: true })+ .eq('brand_id', brandId)+ .eq('source', catalogSourceKey(row.id))+ .is('removed_at', null);+ return {+ id: row.id,+ kind: row.kind as CatalogSourceKind,+ format: row.format as CatalogFormat,+ url: row.url,+ account: row.account,+ label: row.label,+ lastSyncedAt: row.last_synced_at,+ lastStatus: row.last_status as CatalogSyncStatus | null,+ lastError: row.last_error,+ lastCounts: row.last_counts as unknown as CatalogCounts | null,+ products: count ?? 0,+ };+ }),+ );+}++/**+ * Whether the brand reads a Google Merchant Center account into its catalog,+ * its last sync read: only then are its products' Merchant Center issues+ * current. None when it can't be read: the caller then says less, never more.+ */+export async function hasMerchantCenter(+ supabase: SupabaseClient,+ brandId: string,+): Promise<boolean> {+ const { data, error } = await supabase+ .from('catalog_sources')+ .select('id')+ .eq('brand_id', brandId)+ .eq('kind', MERCHANT_CENTER_KIND)+ .eq('last_status', 'ok')+ .limit(1);+ if (error) {+ console.error('Failed to read the brand’s catalog sources:', error.message);+ return false;+ }+ return (data ?? []).length > 0;+}diff --git a/web/src/lib/shopping/readiness.ts b/web/src/lib/shopping/readiness.tsindex a57d3f102..8368d6f96 100644--- a/web/src/lib/shopping/readiness.ts+++ b/web/src/lib/shopping/readiness.ts@@ -2,6 +2,7 @@ import type { CatalogSource } from '@/lib/catalog';import type { ShoppingMarket } from '@/lib/shopping/markets';import { openAiIndexStatus, type OpenAiIndexRead } from '@/lib/shopping/openai-index';import type { ProductRow, ReadinessCheck } from '@/lib/shopping/products';+import { priceText } from '@/lib/shopping/price';/*** Product Visibility's Readiness (ECOM-015, spec §3.4 / §3.4b): how ready@@ -186,6 +187,17 @@ export function readinessChecklist(input: ReadinessInput): {};}+/** The values a check's copy reads (en.json shopping.readiness.checks), prices written as prices. */+export function copyValues(item: ReadinessItem): Record<string, string | number> {+ const values = { ...(item.values ?? {}) };+ if (item.key === 'wrongPrice' && typeof values.seen === 'number') {+ const currency = String(values.currency ?? 'USD');+ values.seen = priceText(Number(values.seen), currency);+ values.yours = priceText(Number(values.yours), currency);+ }+ return values;+}+/** The AI channels a shop sells through, in the spec's priority order. */export const READINESS_CHANNELS = ['chatgpt-shopping',