From 43bf56fdedc345889f97537a1f15adb556daa78a Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:59:49 +0700 Subject: [PATCH 1/2] feat(web): add read-only Rate Shopping MCP server and /llms.txt Add stateless Streamable HTTP JSON-RPC 2.0 MCP endpoint (/api/mcp) with 5 Zod-4 validated read-only tools across 22 Vietnamese retail platforms, self-hosted discovery routes (/llms.txt and /.well-known/mcp.json), proxy/robots bypass rules, trilingual /developers docs (vi, en, cs), and comprehensive security and data-truth regression tests. Closes #1866 --- apps/web/locales/cs.json | 27 + apps/web/locales/en.json | 27 + apps/web/locales/vi.json | 27 + apps/web/package.json | 2 +- .../web/src/app/.well-known/mcp.json/route.ts | 17 + apps/web/src/app/[locale]/developers/page.tsx | 169 + apps/web/src/app/api/mcp/route.ts | 22 + apps/web/src/app/llms.txt/route.ts | 18 + apps/web/src/app/robots.ts | 20 +- .../src/lib/__tests__/developers-copy.test.ts | 137 + apps/web/src/lib/__tests__/proxy.test.ts | 104 +- apps/web/src/proxy.ts | 20 +- .../web/src/server/rate/__tests__/mcp.test.ts | 1925 +++++++++++ apps/web/src/server/rate/mcp.ts | 3008 +++++++++++++++++ 14 files changed, 5508 insertions(+), 15 deletions(-) create mode 100644 apps/web/src/app/.well-known/mcp.json/route.ts create mode 100644 apps/web/src/app/api/mcp/route.ts create mode 100644 apps/web/src/app/llms.txt/route.ts create mode 100644 apps/web/src/server/rate/__tests__/mcp.test.ts create mode 100644 apps/web/src/server/rate/mcp.ts diff --git a/apps/web/locales/cs.json b/apps/web/locales/cs.json index ea5b02d30..d1a5f5d1c 100644 --- a/apps/web/locales/cs.json +++ b/apps/web/locales/cs.json @@ -1545,6 +1545,33 @@ "connectivity": "Komunikace a konektivita", "battery": "Baterie a nabíjení", "misc": "Senzory, SAR a předpisy" + }, + "btnMcpDocs": "MCP a /llms.txt pro AI agenty", + "authPublicMcp": "Veřejné pouze pro čtení (limit na IP)", + "cacheNoStoreMcp": "no-store (čtení přes withRateDataCache)", + "ep20Params": "Tělo JSON-RPC 2.0: initialize, ping, tools/list, tools/call (<= 16 KB)", + "ep20Summary": "Bezstavový MCP server přes HTTP s 5 čtecími nástroji napříč 22 obchody ve Vietnamu a povinnou citací rate.vn.", + "ep21Params": "Bez parametrů", + "ep21Summary": "Popisovač automatického zjištění MCP serveru (verze protokolu 2025-06-18, adresa HTTP, limity požadavků a seznam nástrojů).", + "ep22Params": "Bez parametrů", + "ep22Summary": "Stručný přehled v Markdownu (/llms.txt) pro AI asistenty a čtečky webu o 22 obchodech, 5 kategoriích, 6osém modelu důvěry recenzí a nástrojích MCP.", + "mcpBadge": "Protokol MCP (2025-06-18)", + "mcpTitle": "MCP server Rate.vn a /llms.txt pro AI agenty", + "mcpSubtitle": "Připojte AI asistenty, IDE agenty, ChatGPT nebo DOSClaw přímo k ověřeným cenám z 22 obchodů ve Vietnamu a 6osému hodnocení důvěry recenzí bez API klíče.", + "mcpBtnLlmsTxt": "Otevřít /llms.txt", + "mcpBtnWellKnown": "Zobrazit /.well-known/mcp.json", + "mcpGuardNote": "Bezpečnostní limity pouze pro čtení: JSON-RPC 2.0 přes POST /api/mcp, tělo <= 16 KB, max. 10 položek na volání, klouzavý limit podle IP (60 požadavků/min, 30 kontrol URL/min) a povinné pole canonical_citation_url s časovým razítkem observed_at u každé položky.", + "mcpToolsHeading": "5 čtecích nástrojů MCP", + "mcpReadOnlyBadge": "Pouze čtení", + "mcpConfigHeading": "Rychlé připojení (.mcp.json / .cursor/mcp.json / claude_desktop_config.json / DOSClaw)", + "mcpClientConfigLabel": ".mcp.json / .cursor/mcp.json / claude_desktop_config.json / DOSClaw", + "mcpCurlConfigLabel": "JSON-RPC 2.0 přes HTTP (POST /api/mcp)", + "mcpTools": { + "search_verified_catalog": "Hledání v 5 technologických kategoriích s filtry značky a ceny ve VND (max. 10 položek, bez vyprodaných a návnadových nabídek).", + "get_22_store_offers_and_price_truth": "Vrátí ověřené nabídky skladem z 22 obchodů, historické minimum a medián, bayesovské skóre, 6osou důvěru recenzí a příznaky falešných slev.", + "compare_devices_by_use_case": "Porovná 2 až 4 modely stejné kategorie v 10 skupinách parametrů, minimálních cenách a 5 kritériích s volitelnými vlastními vahami.", + "audit_listing_url": "Prověří URL nabídky z 22 podporovaných obchodů, spáruje katalogový model a vrátí 5stupňový verdikt ceny i riziko prodejce.", + "get_genuine_deals": "Vypíše ověřené nabídky pod mediánem a cenová minima napříč obchody (limit <= 10) s filtry kategorie, platformy a rozpočtu." } }, "staticPages": { diff --git a/apps/web/locales/en.json b/apps/web/locales/en.json index 4fb58a61f..459a0871a 100644 --- a/apps/web/locales/en.json +++ b/apps/web/locales/en.json @@ -1545,6 +1545,33 @@ "connectivity": "Comms & connectivity", "battery": "Battery & charging", "misc": "Sensors, SAR & regulatory" + }, + "btnMcpDocs": "MCP & /llms.txt for AI agents", + "authPublicMcp": "Public read-only (per-IP rate limit)", + "cacheNoStoreMcp": "no-store (withRateDataCache BFF)", + "ep20Params": "Body JSON-RPC 2.0: initialize, ping, tools/list, tools/call (<= 16 KB)", + "ep20Summary": "Stateless streamable HTTP MCP server exposing 5 read-only tools across 22 stores in Vietnam with mandatory rate.vn citations.", + "ep21Params": "No parameters", + "ep21Summary": "Self-hosted MCP server discovery descriptor (protocol version 2025-06-18, streamable HTTP endpoint, rate limits and tool list).", + "ep22Params": "No parameters", + "ep22Summary": "Concise Markdown context guide (/llms.txt) for AI assistants and web readers covering 22 retail platforms, 5 categories, 6-axis review trust and MCP tools.", + "mcpBadge": "MCP protocol (2025-06-18)", + "mcpTitle": "Rate.vn MCP server & /llms.txt for AI agents", + "mcpSubtitle": "Connect AI assistants, IDE agents, ChatGPT or DOSClaw directly to verified 22-store prices in Vietnam and 6-axis review trust with zero API keys.", + "mcpBtnLlmsTxt": "Open /llms.txt", + "mcpBtnWellKnown": "View /.well-known/mcp.json", + "mcpGuardNote": "Read-only guardrails: JSON-RPC 2.0 over POST /api/mcp, body <= 16 KB, max 10 items per call, per-IP sliding-window rate limit (60 req/min, 30 URL audits/min), and mandatory canonical_citation_url + observed_at provenance on every item.", + "mcpToolsHeading": "5 read-only MCP tools", + "mcpReadOnlyBadge": "Read-only", + "mcpConfigHeading": "Quick connect (.mcp.json / .cursor/mcp.json / claude_desktop_config.json / DOSClaw)", + "mcpClientConfigLabel": ".mcp.json / .cursor/mcp.json / claude_desktop_config.json / DOSClaw", + "mcpCurlConfigLabel": "JSON-RPC 2.0 over HTTP (POST /api/mcp)", + "mcpTools": { + "search_verified_catalog": "Search across 5 tech categories with brand and VND price bounds (max 10 items, bait and sold-out listings excluded).", + "get_22_store_offers_and_price_truth": "Fetch verified in-stock offers across 22 stores, historical floor/median prices, Bayesian rating, 6-axis review trust and fake-sale flags.", + "compare_devices_by_use_case": "Compare 2 to 4 same-category slugs side-by-side across 10 spec groups, floor prices and 5 criteria with optional custom weights.", + "audit_listing_url": "Inspect a marketplace listing URL across the 22 supported platforms for catalog match, 5-level price verdict and seller risk scores.", + "get_genuine_deals": "List verified below-median and multi-store floor deals (limit <= 10) with optional category, platform and budget filters." } }, "staticPages": { diff --git a/apps/web/locales/vi.json b/apps/web/locales/vi.json index 72f4ea0eb..41a345627 100644 --- a/apps/web/locales/vi.json +++ b/apps/web/locales/vi.json @@ -1545,6 +1545,33 @@ "connectivity": "Kết nối", "battery": "Pin và sạc", "misc": "Cảm biến, SAR và quy chuẩn" + }, + "btnMcpDocs": "MCP & /llms.txt cho AI agent", + "authPublicMcp": "Công khai chỉ đọc (giới hạn theo IP)", + "cacheNoStoreMcp": "no-store (đọc qua withRateDataCache)", + "ep20Params": "Body JSON-RPC 2.0: initialize, ping, tools/list, tools/call (<= 16 KB)", + "ep20Summary": "Máy chủ MCP qua HTTP không trạng thái, cung cấp 5 công cụ chỉ đọc trên 22 sàn tại Việt Nam kèm trích dẫn nguồn rate.vn.", + "ep21Params": "Không có tham số", + "ep21Summary": "Tệp mô tả tự động nhận diện máy chủ MCP (phiên bản giao thức 2025-06-18, địa chỉ HTTP, giới hạn tần suất và danh sách công cụ).", + "ep22Params": "Không có tham số", + "ep22Summary": "Tài liệu ngữ cảnh Markdown gọn nhẹ (/llms.txt) cho trợ lý AI và trình đọc web về 22 sàn bán lẻ, 5 ngành hàng, mô hình tin cậy đánh giá 6 trục và bộ công cụ MCP.", + "mcpBadge": "Giao thức MCP (2025-06-18)", + "mcpTitle": "Máy chủ MCP của Rate.vn & /llms.txt cho AI agent", + "mcpSubtitle": "Kết nối trực tiếp trợ lý AI, trình sửa mã IDE, ChatGPT hoặc DOSClaw với giá thật từ 22 sàn tại Việt Nam và mô hình lọc đánh giá 6 trục mà không cần khóa API.", + "mcpBtnLlmsTxt": "Mở /llms.txt", + "mcpBtnWellKnown": "Xem /.well-known/mcp.json", + "mcpGuardNote": "Chốt an toàn chỉ đọc: JSON-RPC 2.0 qua POST /api/mcp, kích thước body <= 16 KB, tối đa 10 kết quả mỗi lần gọi, giới hạn tần suất theo IP (60 yêu cầu/phút, 30 lần kiểm tra URL/phút), bắt buộc đính kèm canonical_citation_url và mốc thời gian observed_at trên mọi mục trả về.", + "mcpToolsHeading": "5 công cụ MCP chỉ đọc", + "mcpReadOnlyBadge": "Chỉ đọc", + "mcpConfigHeading": "Cấu hình kết nối nhanh (.mcp.json / .cursor/mcp.json / claude_desktop_config.json / DOSClaw)", + "mcpClientConfigLabel": ".mcp.json / .cursor/mcp.json / claude_desktop_config.json / DOSClaw", + "mcpCurlConfigLabel": "JSON-RPC 2.0 qua HTTP (POST /api/mcp)", + "mcpTools": { + "search_verified_catalog": "Tìm kiếm trên 5 ngành hàng công nghệ theo hãng và khoảng giá VNĐ (tối đa 10 mục, đã loại tin hết hàng và giá mồi).", + "get_22_store_offers_and_price_truth": "Lấy danh sách nơi bán còn hàng trên 22 sàn, giá đáy và trung vị lịch sử, điểm Bayes, độ tin cậy đánh giá 6 trục và cờ giảm giá ảo.", + "compare_devices_by_use_case": "So sánh trực tiếp 2 đến 4 mẫu máy cùng ngành hàng trên 10 nhóm thông số, giá đáy đa sàn và 5 tiêu chí kèm trọng số tùy chỉnh.", + "audit_listing_url": "Kiểm tra đường dẫn tin bán trên 22 sàn được hỗ trợ để ghép mẫu máy chuẩn, chấm kết luận giá 5 mức và điểm rủi ro người bán.", + "get_genuine_deals": "Liệt kê các deal dưới giá trung vị và chạm đáy đa sàn đã kiểm chứng (tối đa 10 mục), lọc theo ngành hàng, sàn và ngân sách." } }, "staticPages": { diff --git a/apps/web/package.json b/apps/web/package.json index 830346b25..27165a493 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -8,7 +8,7 @@ "lint": "eslint . --max-warnings 0", "preview": "next build && next start", "start": "next start", - "test": "pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/server/rate/__tests__/core-rate-architecture.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/server/rate/__tests__/item-model.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/server/rate/__tests__/item-directory.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/server/rate/__tests__/compare-selection.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/app/api/v1/rate/__tests__/write-paths.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/app/api/v1/rate/__tests__/spec-scope.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/app/api/v1/rate/__tests__/versus-parity.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/app/api/v1/rate/__tests__/item-fields.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/logger.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/review-display.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/review-form-v2.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/review-value-display.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/concurrency.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/merchant-profile-reads.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/merchant-review-risk.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/item-directory.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/home-deals-item-grouping.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/watchlist-sizes.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/item-compare.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/product-variant-links.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/compare-params.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/catalog-listing.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/discount-verdict-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/product-detail-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/product-competitors.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/analyzer-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/sold-count.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/content-lang.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/image-url.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/client-messages.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/seo.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/offer-plausibility.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/product-market-stats.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/sitemap-lastmod.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/leaderboard-badge-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/leaderboard-criteria.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/trust-depth-v2.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/rating-score.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/rating-display.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/focus-trap.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/display-truth.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/spec-template.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/product-spec-rows.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/sale-state.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/csp.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/proxy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/device-images.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/render-timing.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/model-match.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/developers-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/plural-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/locale-format.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/paged-reads.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/server-timing.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/hero-products.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/components/elementary/__tests__/locale-switcher-a11y.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/components/compare/__tests__/quick-toggle-a11y.test.ts", + "test": "pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/server/rate/__tests__/core-rate-architecture.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/server/rate/__tests__/mcp.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/server/rate/__tests__/item-model.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/server/rate/__tests__/item-directory.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/server/rate/__tests__/compare-selection.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/app/api/v1/rate/__tests__/write-paths.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/app/api/v1/rate/__tests__/spec-scope.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/app/api/v1/rate/__tests__/versus-parity.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/app/api/v1/rate/__tests__/item-fields.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/logger.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/review-display.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/review-form-v2.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/review-value-display.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/concurrency.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/merchant-profile-reads.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/merchant-review-risk.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/item-directory.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/home-deals-item-grouping.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/watchlist-sizes.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/item-compare.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/product-variant-links.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/compare-params.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/catalog-listing.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/discount-verdict-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/product-detail-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/product-competitors.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/analyzer-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/sold-count.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/content-lang.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/image-url.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/client-messages.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/seo.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/offer-plausibility.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/product-market-stats.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/sitemap-lastmod.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/leaderboard-badge-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/leaderboard-criteria.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/trust-depth-v2.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/rating-score.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/rating-display.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/focus-trap.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/display-truth.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/spec-template.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/product-spec-rows.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/sale-state.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/csp.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/proxy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/device-images.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/render-timing.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/model-match.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/developers-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/plural-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/locale-format.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/paged-reads.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/server-timing.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/hero-products.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/components/elementary/__tests__/locale-switcher-a11y.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/components/compare/__tests__/quick-toggle-a11y.test.ts", "typecheck": "tsc --noEmit" }, "browserslist": [ diff --git a/apps/web/src/app/.well-known/mcp.json/route.ts b/apps/web/src/app/.well-known/mcp.json/route.ts new file mode 100644 index 000000000..2169d75ae --- /dev/null +++ b/apps/web/src/app/.well-known/mcp.json/route.ts @@ -0,0 +1,17 @@ +import { NextResponse } from 'next/server'; +import { + MCP_DISCOVERY_CORS_HEADERS, + buildRateWellKnownMcpDescriptor, +} from '@/server/rate/mcp'; + +export const dynamic = 'force-static'; + +export async function GET() { + return NextResponse.json(buildRateWellKnownMcpDescriptor(), { + status: 200, + headers: { + ...MCP_DISCOVERY_CORS_HEADERS, + 'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400', + }, + }); +} diff --git a/apps/web/src/app/[locale]/developers/page.tsx b/apps/web/src/app/[locale]/developers/page.tsx index 1b8827e49..1a8e2f7cd 100644 --- a/apps/web/src/app/[locale]/developers/page.tsx +++ b/apps/web/src/app/[locale]/developers/page.tsx @@ -94,6 +94,51 @@ const TEN_FIELD_GROUPS = [ }, ] as const; +const MCP_TOOL_KEYS = [ + 'search_verified_catalog', + 'get_22_store_offers_and_price_truth', + 'compare_devices_by_use_case', + 'audit_listing_url', + 'get_genuine_deals', +] as const; + +const MCP_CLIENT_CONFIG_SNIPPET = [ + '// .mcp.json / .cursor/mcp.json / DOSClaw (native HTTP)', + JSON.stringify( + { + mcpServers: { + 'rate-vn': { + type: 'streamable-http', + url: 'https://rate.vn/api/mcp', + }, + }, + }, + null, + 2 + ), + '', + '// claude_desktop_config.json (stdio bridge)', + JSON.stringify( + { + mcpServers: { + 'rate-vn': { + command: 'npx', + args: ['-y', 'mcp-remote', 'https://rate.vn/api/mcp'], + }, + }, + }, + null, + 2 + ), +].join('\n'); + +const MCP_JSON_RPC_CURL_SNIPPET = [ + "curl -sS -X POST 'https://rate.vn/api/mcp' \\", + " -H 'Content-Type: application/json' \\", + " -H 'Accept: application/json, text/event-stream' \\", + ' --data-raw \'{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_genuine_deals","arguments":{"category":"smartphones","limit":3}}}\'', +].join('\n'); + export default async function DevelopersPage({ params, }: { @@ -244,6 +289,30 @@ export default async function DevelopersPage({ queryParams: t('ep12Params'), summary: t('ep12Summary'), }, + { + method: 'POST', + path: '/api/mcp', + auth: t('authPublicMcp'), + cache: t('cacheNoStoreMcp'), + queryParams: t('ep20Params'), + summary: t('ep20Summary'), + }, + { + method: 'GET', + path: '/.well-known/mcp.json', + auth: t('authPublic'), + cache: 's-maxage=3600, stale-while-revalidate=86400', + queryParams: t('ep21Params'), + summary: t('ep21Summary'), + }, + { + method: 'GET', + path: '/llms.txt', + auth: t('authPublic'), + cache: 's-maxage=3600, stale-while-revalidate=86400', + queryParams: t('ep22Params'), + summary: t('ep22Summary'), + }, { method: 'POST', path: '/api/v1/rate/reviews', @@ -292,6 +361,12 @@ export default async function DevelopersPage({ > {t('btnPlayground')} + + {t('btnMcpDocs')} + + {/* Rate Shopping MCP Server & /llms.txt Section */} +
+
+
+
+ + {t('mcpBadge')} + +

{t('mcpTitle')}

+

{t('mcpSubtitle')}

+

{t('mcpGuardNote')}

+
+
+
+ + {t('mcpBtnLlmsTxt')} + + + {t('mcpBtnWellKnown')} + +
+
+
+ +
+
+

+ {t('mcpToolsHeading')} +

+
+ {MCP_TOOL_KEYS.map((toolKey) => ( +
+
+ + {toolKey} + + + {t('mcpReadOnlyBadge')} + +
+
+ {t(`mcpTools.${toolKey}`)} +
+
+ ))} +
+
+ +
+

+ {t('mcpConfigHeading')} +

+
+
+
+ {t('mcpClientConfigLabel')} +
+
+                      {MCP_CLIENT_CONFIG_SNIPPET}
+                    
+
+
+
+ {t('mcpCurlConfigLabel')} +
+
+                      {MCP_JSON_RPC_CURL_SNIPPET}
+                    
+
+
+
+
+
+
+ {/* Endpoint Reference Table */}
diff --git a/apps/web/src/app/api/mcp/route.ts b/apps/web/src/app/api/mcp/route.ts new file mode 100644 index 000000000..d16355a3d --- /dev/null +++ b/apps/web/src/app/api/mcp/route.ts @@ -0,0 +1,22 @@ +import type { NextRequest } from 'next/server'; +import { + buildMcpCorsPreflightResponse, + buildMcpMethodNotAllowedResponse, + handleMcpHttpPost, +} from '@/server/rate/mcp'; + +export async function OPTIONS() { + return buildMcpCorsPreflightResponse(); +} + +export async function GET() { + return buildMcpMethodNotAllowedResponse(); +} + +export async function DELETE() { + return buildMcpMethodNotAllowedResponse(); +} + +export async function POST(request: NextRequest) { + return handleMcpHttpPost(request); +} diff --git a/apps/web/src/app/llms.txt/route.ts b/apps/web/src/app/llms.txt/route.ts new file mode 100644 index 000000000..6f4749e43 --- /dev/null +++ b/apps/web/src/app/llms.txt/route.ts @@ -0,0 +1,18 @@ +import { NextResponse } from 'next/server'; +import { + MCP_DISCOVERY_CORS_HEADERS, + buildRateLlmsTxt, +} from '@/server/rate/mcp'; + +export const dynamic = 'force-static'; + +export async function GET() { + return new NextResponse(buildRateLlmsTxt(), { + status: 200, + headers: { + ...MCP_DISCOVERY_CORS_HEADERS, + 'Content-Type': 'text/plain; charset=utf-8', + 'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400', + }, + }); +} diff --git a/apps/web/src/app/robots.ts b/apps/web/src/app/robots.ts index 56c9b75c9..c6af4a46b 100644 --- a/apps/web/src/app/robots.ts +++ b/apps/web/src/app/robots.ts @@ -1,24 +1,24 @@ -import { env } from "@/env.mjs" +import { env } from '@/env.mjs'; -import type { MetadataRoute } from "next" +import type { MetadataRoute } from 'next'; -import { isProduction } from "@/lib/general-helpers" +import { isProduction } from '@/lib/general-helpers'; -const baseUrl = env.APP_PUBLIC_URL +const baseUrl = env.APP_PUBLIC_URL; export default function robots(): MetadataRoute.Robots { return isProduction() ? { rules: { - userAgent: "*", - allow: "/", + userAgent: '*', + allow: ['/', '/llms.txt', '/.well-known/mcp.json', '/api/mcp'], }, - sitemap: new URL("sitemap.xml", baseUrl).toString(), + sitemap: new URL('sitemap.xml', baseUrl).toString(), } : { rules: { - userAgent: "*", - disallow: "/", + userAgent: '*', + disallow: '/', }, - } + }; } diff --git a/apps/web/src/lib/__tests__/developers-copy.test.ts b/apps/web/src/lib/__tests__/developers-copy.test.ts index 2d27c741d..fc0fae7af 100644 --- a/apps/web/src/lib/__tests__/developers-copy.test.ts +++ b/apps/web/src/lib/__tests__/developers-copy.test.ts @@ -129,6 +129,143 @@ for (const locale of ['vi', 'cs']) { console.warn(' ✅ /developers table and group titles are localized (#1372)'); +// --------------------------------------------------------------------------- +// DOS/Rate#1866: Rate Shopping MCP Server (/api/mcp), /.well-known/mcp.json & +// /llms.txt documentation parity across vi, en, cs (zero em-dash / en-dash). +// --------------------------------------------------------------------------- +const mcpToolKeys = [ + 'search_verified_catalog', + 'get_22_store_offers_and_price_truth', + 'compare_devices_by_use_case', + 'audit_listing_url', + 'get_genuine_deals', +] as const; + +const mcpFlatKeys = [ + 'btnMcpDocs', + 'authPublicMcp', + 'cacheNoStoreMcp', + 'ep20Params', + 'ep20Summary', + 'ep21Params', + 'ep21Summary', + 'ep22Params', + 'ep22Summary', + 'mcpBadge', + 'mcpTitle', + 'mcpSubtitle', + 'mcpBtnLlmsTxt', + 'mcpBtnWellKnown', + 'mcpGuardNote', + 'mcpToolsHeading', + 'mcpReadOnlyBadge', + 'mcpConfigHeading', + 'mcpClientConfigLabel', + 'mcpCurlConfigLabel', +] as const; + +const enDevTopKeys = Object.keys(messages.en!).sort(); +for (const locale of ['vi', 'en', 'cs'] as const) { + const dev = messages[locale]!; + assert.deepEqual( + Object.keys(dev).sort(), + enDevTopKeys, + `${locale}.developers top-level key parity` + ); + for (const k of mcpFlatKeys) { + const val = dev[k]; + assert.ok( + typeof val === 'string' && val.trim().length > 0, + `${locale}.developers.${k} must be a non-empty string` + ); + assert.equal( + /[\u2013\u2014]/.test(val), + false, + `${locale}.developers.${k} must contain zero em-dashes or en-dashes` + ); + } + const mcpTools = dev.mcpTools as Record; + assert.ok( + mcpTools && typeof mcpTools === 'object', + `${locale}.developers.mcpTools must exist` + ); + assert.deepEqual( + Object.keys(mcpTools).sort(), + [...mcpToolKeys].sort(), + `${locale}.developers.mcpTools key parity` + ); + for (const toolKey of mcpToolKeys) { + const desc = mcpTools[toolKey]; + assert.ok( + typeof desc === 'string' && desc.trim().length > 0, + `${locale}.developers.mcpTools.${toolKey} must be non-empty` + ); + assert.equal( + /[\u2013\u2014]/.test(desc), + false, + `${locale}.developers.mcpTools.${toolKey} must contain zero em-dashes or en-dashes` + ); + } +} + +for (const locale of ['vi', 'cs'] as const) { + const dev = messages[locale]!; + for (const proseKey of [ + 'authPublicMcp', + 'ep20Summary', + 'ep21Summary', + 'ep22Summary', + 'mcpTitle', + 'mcpSubtitle', + 'mcpGuardNote', + 'mcpReadOnlyBadge', + ] as const) { + assert.notEqual( + dev[proseKey], + messages.en![proseKey], + `${locale}.developers.${proseKey} must be localized` + ); + } + for (const toolKey of mcpToolKeys) { + assert.notEqual( + (dev.mcpTools as Record)[toolKey], + (messages.en!.mcpTools as Record)[toolKey], + `${locale}.developers.mcpTools.${toolKey} must be localized` + ); + } +} + +assert.equal( + /[\u2013\u2014]/.test(page), + false, + 'developers/page.tsx must contain zero em-dashes or en-dashes' +); +for (const expectedPageToken of [ + "'/api/mcp'", + "'/.well-known/mcp.json'", + "'/llms.txt'", + 't(`mcpTools.${toolKey}`)', + 'https://rate.vn/api/mcp', + 'mcp-remote', + 'Accept: application/json, text/event-stream', + 'btn-outline-dark', + ...mcpToolKeys.map((k) => `'${k}'`), +]) { + assert.ok( + page.includes(expectedPageToken), + `developers/page.tsx must include ${expectedPageToken}` + ); +} +assert.equal( + page.includes('btn-outline-secondary'), + false, + 'developers/page.tsx must not use low-contrast dark-mode btn-outline-secondary' +); + +console.warn( + ' ✅ /developers MCP & /llms.txt localization parity passed (#1866)' +); + // --------------------------------------------------------------------------- // DOS/Rate#1747: Runnable POST snippets, non-JSON HTTP status preservation, // preset state synchronization, decorative icon a11y, th scope & telemetry formatting. diff --git a/apps/web/src/lib/__tests__/proxy.test.ts b/apps/web/src/lib/__tests__/proxy.test.ts index 93846cb5e..9356e93c9 100644 --- a/apps/web/src/lib/__tests__/proxy.test.ts +++ b/apps/web/src/lib/__tests__/proxy.test.ts @@ -31,7 +31,12 @@ async function main() { }; const { CSP_HEADER } = await import('../csp'); - const { config: proxyConfig, localeProxy } = await import('../../proxy'); + const { + config: proxyConfig, + isDirectNonLocalePath, + localeProxy, + proxy, + } = await import('../../proxy'); const nextConfigSrc = fs.readFileSync( path.join(__dirname, '../../../next.config.mjs'), @@ -176,6 +181,8 @@ async function main() { '/_VERCEL/insights/script.js', '/api/health', '/API/health', + '/api/mcp', + '/API/mcp', '/api/v1/rate/openapi.json', '/api/v1/rate/merchants/anker.vn', '/API/v1/rate/merchants/anker.vn', @@ -302,7 +309,100 @@ async function main() { ); } - console.warn(' ✅ proxy dotted-slug routing & CSP suite passed'); + // DOS/Rate#1866: /api/mcp, /llms.txt, and /.well-known/mcp.json skip + // middleware, receive static CSP headers, never locale-redirect or rewrite, + // and are explicitly allowed in production robots.ts. + for (const discoveryPath of [ + '/llms.txt', + '/LLMS.TXT', + '/.well-known/mcp.json', + '/.WELL-KNOWN/mcp.json', + '/api/mcp', + '/API/mcp', + ]) { + assert.equal( + byMiddleware(discoveryPath), + false, + `${discoveryPath} must skip compiled Next.js middleware matcher` + ); + assert.equal( + staticCspRegex.test(discoveryPath), + true, + `${discoveryPath} must carry static CSP header` + ); + assert.equal( + isDirectNonLocalePath(discoveryPath), + true, + `${discoveryPath} is a direct non-locale path` + ); + + const directRes = localeProxy( + new NextRequest(`https://rate.vn${discoveryPath}`, { + headers: { + host: 'rate.vn', + 'x-forwarded-proto': 'https', + 'accept-language': 'en-US,en;q=0.9', + cookie: 'NEXT_LOCALE=cs', + }, + }) + ); + assert.equal( + directRes.status, + 200, + `${discoveryPath} returns 200 pass-through` + ); + assert.equal( + directRes.headers.get('location'), + null, + `${discoveryPath} must not redirect` + ); + assert.equal( + directRes.headers.get('x-middleware-rewrite'), + null, + `${discoveryPath} must not rewrite to a locale prefix` + ); + assert.equal( + directRes.cookies.get('NEXT_LOCALE'), + undefined, + `${discoveryPath} must not mutate NEXT_LOCALE cookie` + ); + + const asyncProxyRes = await proxy( + new NextRequest(`https://rate.vn${discoveryPath}`, { + headers: { + host: 'rate.vn', + 'x-forwarded-proto': 'https', + }, + }) + ); + assert.equal(asyncProxyRes.status, 200); + assert.equal(asyncProxyRes.headers.get('x-middleware-rewrite'), null); + } + + for (const pagePath of ['/', '/developers', '/smartphones/nokia-8.1']) { + assert.equal(isDirectNonLocalePath(pagePath), false); + } + + const { default: robots } = await import('../../app/robots'); + const prevVercelEnv = process.env.VERCEL_ENV; + try { + process.env.VERCEL_ENV = 'production'; + const prodRobots = robots(); + assert.deepEqual(prodRobots.rules, { + userAgent: '*', + allow: ['/', '/llms.txt', '/.well-known/mcp.json', '/api/mcp'], + }); + } finally { + if (prevVercelEnv === undefined) { + delete process.env.VERCEL_ENV; + } else { + process.env.VERCEL_ENV = prevVercelEnv; + } + } + + console.warn( + ' ✅ proxy dotted-slug routing, AI discovery & CSP suite passed' + ); } main().catch((err) => { diff --git a/apps/web/src/proxy.ts b/apps/web/src/proxy.ts index 4b4997d88..cda4aa111 100644 --- a/apps/web/src/proxy.ts +++ b/apps/web/src/proxy.ts @@ -43,6 +43,13 @@ async function refreshSupabaseSession( } } +/** Direct API and AI discovery endpoints that never undergo locale rewriting. */ +export function isDirectNonLocalePath(pathname: string): boolean { + return /^\/(?:api(?:\/|$)|llms\.txt\/?$|(?:\.well-known)(?:\/|$))/i.test( + pathname + ); +} + /** HTTPS + locale routing (synchronous, so it is testable without a network). */ export function localeProxy(req: NextRequest): NextResponse { const xForwardedProtoHeader = req.headers.get('x-forwarded-proto'); @@ -63,6 +70,10 @@ export function localeProxy(req: NextRequest): NextResponse { // Strip any explicit /vi, /en, /cs URL prefix so URLs never contain a locale slug const pathname = req.nextUrl.pathname; + if (isDirectNonLocalePath(pathname)) { + req.headers.delete('content-security-policy'); + return NextResponse.next(); + } const localePrefixMatch = pathname.match(/^\/(vi|en|cs)(\/.*)?$/i); if (localePrefixMatch) { const matchedLocale = localePrefixMatch[1]!.toLowerCase(); @@ -109,8 +120,13 @@ export function localeProxy(req: NextRequest): NextResponse { export async function proxy(req: NextRequest): Promise { const response = localeProxy(req); - // Redirects carry no page; refresh the session on the request that renders. - if (response.status >= 300 && response.status < 400) return response; + // Redirects and stateless API / AI discovery routes skip cookie session refresh. + if ( + isDirectNonLocalePath(req.nextUrl.pathname) || + (response.status >= 300 && response.status < 400) + ) { + return response; + } await refreshSupabaseSession(req, response); return response; } diff --git a/apps/web/src/server/rate/__tests__/mcp.test.ts b/apps/web/src/server/rate/__tests__/mcp.test.ts new file mode 100644 index 000000000..cea051a73 --- /dev/null +++ b/apps/web/src/server/rate/__tests__/mcp.test.ts @@ -0,0 +1,1925 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { NextRequest } from 'next/server'; +import { BoundedSlidingWindowRateLimiter } from '../api-handler'; +import { + CANONICAL_RATE_ORIGIN, + MAX_MCP_BODY_BYTES, + MAX_MCP_RESULT_ITEMS, + MCP_LATEST_PROTOCOL_VERSION, + MCP_TOOL_DEFINITIONS, + buildRateLlmsTxt, + buildRateWellKnownMcpDescriptor, + handleMcpHttpPost, + type McpDataReaders, +} from '../mcp'; +import { + DELETE as deleteMcpRoute, + GET as getMcpRoute, + OPTIONS as optionsMcpRoute, + POST as postMcpRoute, +} from '../../../app/api/mcp/route'; +import { GET as getLlmsTxtRoute } from '../../../app/llms.txt/route'; +import { GET as getWellKnownMcpRoute } from '../../../app/.well-known/mcp.json/route'; +import { + parseEcommerceUrlOrQuery, + type MasterProduct, + type MasterProductPriceHistorySummary, + type MerchantOffer, + type ReviewAnalysisSummary, + type UrlInspectionResult, +} from '../../../lib/rate-api'; +import type { CrossPlatformDealRadarResponse } from '../deals'; + +const FIXED_NOW_ISO = '2026-11-22T14:30:00.000Z'; + +function makeProduct( + overrides: Partial & { id: string; slug: string; name: string } +): MasterProduct { + return { + brand: 'Apple', + model: overrides.name, + model_key: overrides.slug, + has_5g: true, + specifications: { + display: { refresh_rate_hz: 120, type: 'LTPO OLED' }, + hardware: { chipset: 'Apple A18 Pro', ram_gb: 8 }, + battery: { capacity_mah: 4685, fast_charging_w: 30 }, + }, + key_specs: { + chipset: 'Apple A18 Pro', + ram_gb: 8, + storage_gb: 256, + }, + images: ['/img/devices/apple-iphone-16-pro-max-256gb.jpg'], + colors: ['Natural Titanium'], + min_price: 28_990_000, + max_price: 32_990_000, + merchant_count: 4, + total_reviews: 48, + average_rating: 4.8, + rating_score: 4.82, + user_rating_weighted: 4.82, + expert_rating: 9.4, + authentic_review_count: 42, + criteria_scores: { + screen: { score: 4.8, writers: 12 }, + performance: { score: 4.9, writers: 12 }, + camera: { score: 4.9, writers: 12 }, + battery: { score: 4.6, writers: 12 }, + value: { score: 4.2, writers: 12 }, + }, + status: 'published', + metadata: { category_slug: 'smartphones' }, + updated_at: '2026-11-22T12:00:00.000Z', + ...overrides, + } as MasterProduct; +} + +function makeOffer( + overrides: Partial & { + id: string; + platform: string; + price_current: number; + } +): MerchantOffer { + return { + title: 'Apple iPhone 16 Pro Max 256GB Chính hãng VN/A', + price_original: 34_990_000, + stock: 15, + rating_star: 4.9, + rating_count: 120, + url: `https://${overrides.platform}.vn/product/${overrides.id}`, + availability: 'in_stock', + merchant: { + id: `merchant-${overrides.platform}`, + name: `${overrides.platform.toUpperCase()} Official`, + platform: overrides.platform, + is_official: true, + rating_star: 4.9, + follower_count: 50_000, + location: 'Ho Chi Minh City', + risk_score: 8, + dosafe_risk_score: 0, + review_risk_score: 8, + review_risk_breakdown: { total_reviews: 25 }, + }, + ...overrides, + }; +} + +const iphoneProduct = makeProduct({ + id: '11111111-1111-4111-8111-000000000001', + slug: 'apple-iphone-16-pro-max-256gb', + name: 'Apple iPhone 16 Pro Max 256GB', + brand: 'Apple', +}); + +const galaxyProduct = makeProduct({ + id: '11111111-1111-4111-8111-000000000002', + slug: 'samsung-galaxy-s25-ultra-256gb', + name: 'Samsung Galaxy S25 Ultra 256GB', + brand: 'Samsung', + min_price: 26_490_000, + max_price: 30_990_000, + rating_score: 4.78, + user_rating_weighted: 4.78, + expert_rating: 9.2, + criteria_scores: { + screen: { score: 4.9, writers: 10 }, + performance: { score: 4.95, writers: 10 }, + camera: { score: 4.6, writers: 10 }, + battery: { score: 4.85, writers: 10 }, + value: { score: 4.7, writers: 10 }, + }, +}); + +const macbookProduct = makeProduct({ + id: '11111111-1111-4111-8111-000000000003', + slug: 'apple-macbook-air-m3-16gb-256gb', + name: 'Apple MacBook Air M3 16GB 256GB', + brand: 'Apple', + metadata: { category_slug: 'laptops' }, +}); + +const sampleOffersForIphone: MerchantOffer[] = [ + // Bait-price silicone case trap (must be excluded from floor!) + makeOffer({ + id: 'offer-bait-case', + platform: 'shopee', + title: 'Ốp lưng silicon iPhone 16 Pro Max', + price_current: 89_000, + price_original: 150_000, + merchant: { + id: 'merchant-random', + name: 'Random Case Shop', + platform: 'shopee', + is_official: false, + rating_star: 4.2, + follower_count: 100, + location: 'Hanoi', + risk_score: 45, + dosafe_risk_score: 0, + // No analysed reviews -> must be nulled by withPublicOfferReviewRisk + review_risk_score: 25, + review_risk_breakdown: { total_reviews: 0 }, + }, + }), + // Sold-out stale cheap listing (must be excluded from floor!) + makeOffer({ + id: 'offer-sold-out', + platform: 'tiki', + price_current: 25_990_000, + availability: 'out_of_stock', + }), + // Valid Official Mall floor offer + makeOffer({ + id: 'offer-cps-official', + platform: 'cellphones', + price_current: 28_990_000, + price_original: 34_990_000, + url: 'https://cellphones.com.vn/iphone-16-pro-max.html', + }), + makeOffer({ + id: 'offer-shopee-mall', + platform: 'shopee', + price_current: 29_490_000, + price_original: 34_990_000, + url: 'https://shopee.vn/Apple-iPhone-16-Pro-Max-i.88201679.27110898667', + merchant: { + id: 'merchant-shopee-unanalysed', + name: 'Apple Flagship Store', + platform: 'shopee', + is_official: true, + rating_star: 4.9, + follower_count: 900_000, + location: 'Ho Chi Minh City', + risk_score: 5, + dosafe_risk_score: 0, + dosafe_risk_known: false, + review_risk_score: 12, + review_risk_breakdown: { total_reviews: 0 }, + } as MerchantOffer['merchant'] & { dosafe_risk_known: boolean }, + }), + makeOffer({ + id: 'offer-tgdd', + platform: 'tgdd', + price_current: 30_990_000, + price_original: 34_990_000, + url: 'https://www.thegioididong.com/dtdd/iphone-16-pro-max', + }), +]; + +const sampleOffersForGalaxy: MerchantOffer[] = [ + makeOffer({ + id: 'offer-galaxy-cps', + platform: 'cellphones', + title: 'Samsung Galaxy S25 Ultra 256GB', + price_current: 26_490_000, + price_original: 31_990_000, + url: 'https://cellphones.com.vn/samsung-galaxy-s25-ultra.html', + }), + makeOffer({ + id: 'offer-galaxy-fpt', + platform: 'fptshop', + title: 'Samsung Galaxy S25 Ultra 256GB', + price_current: 27_990_000, + price_original: 31_990_000, + url: 'https://fptshop.com.vn/dien-thoai/samsung-galaxy-s25-ultra', + }), + makeOffer({ + id: 'offer-galaxy-hhm', + platform: 'hoangha', + title: 'Samsung Galaxy S25 Ultra 256GB', + price_current: 26_790_000, + price_original: 31_990_000, + url: 'https://hoanghamobile.com/dien-thoai/samsung-galaxy-s25-ultra', + }), +]; + +function createMockReaders(): McpDataReaders { + const catalog = Array.from({ length: 14 }, (_, i) => + i === 0 + ? iphoneProduct + : i === 1 + ? galaxyProduct + : makeProduct({ + id: `11111111-1111-4111-8111-0000000000${String(i + 10).padStart(2, '0')}`, + slug: `sample-phone-${i + 1}`, + name: `Sample Phone ${i + 1}`, + min_price: 10_000_000 + i * 500_000, + }) + ); + + return { + nowIso: () => FIXED_NOW_ISO, + resolveCompareTokenTarget: async (rawToken) => { + const trimmed = rawToken.trim(); + if (trimmed.includes('@')) { + const [base, vKey] = trimmed.split('@'); + if ( + base?.toLowerCase() === 'iphone-16-pro-max' && + vKey?.toLowerCase() === '256gb' + ) { + return { + variantSlug: iphoneProduct.slug, + itemId: 'item-iphone-16-pro-max', + }; + } + return { variantSlug: null, itemId: null }; + } + if (trimmed.toLowerCase() === 'iphone-16-pro-max') { + return { + variantSlug: iphoneProduct.slug, + itemId: 'item-iphone-16-pro-max', + }; + } + if (trimmed.toLowerCase() === iphoneProduct.slug) { + return { + variantSlug: iphoneProduct.slug, + itemId: 'item-iphone-16-pro-max', + }; + } + return { variantSlug: trimmed.toLowerCase(), itemId: null }; + }, + getCachedMasterProducts: async (params) => { + const lim = params?.limit ?? 24; + return catalog + .filter((p) => + params?.search + ? p.name.toLowerCase().includes(params.search.toLowerCase()) + : true + ) + .slice(0, lim); + }, + getCachedMasterProductBySlug: async (slug) => { + const lower = slug.toLowerCase(); + if (lower === iphoneProduct.slug) return iphoneProduct; + if (lower === galaxyProduct.slug) return galaxyProduct; + if (lower === macbookProduct.slug) return macbookProduct; + return null; + }, + getCachedMasterProductOffers: async (id) => { + if (id === iphoneProduct.id) return sampleOffersForIphone; + if (id === galaxyProduct.id) return sampleOffersForGalaxy; + return [ + makeOffer({ + id: `offer-${id}-1`, + platform: 'cellphones', + price_current: 15_990_000, + }), + makeOffer({ + id: `offer-${id}-2`, + platform: 'fptshop', + price_current: 16_490_000, + }), + ]; + }, + getCachedMasterProductReviews: async () => [], + getCachedMasterProductReviewSummary: + async (): Promise => ({ + total_analyzed: 48, + authentic_pct: 88, + suspicious_pct: 8, + fake_pct: 4, + pros: [ + 'Excellent 5x tetraprism camera', + 'Cool thermals under sustained load', + ], + cons: ['30W wired charging is slower than peers'], + ai_summary: + 'Verified buyers praise camera consistency and battery life.', + }), + getCachedMasterProductPriceHistory: + async (): Promise => ({ + points: [ + { + id: 1, + product_id: 'offer-cps-official', + merchant_name: 'CELLPHONES Official', + platform: 'cellphones', + is_official: true, + price: 28_990_000, + price_original: 34_990_000, + recorded_at: '2026-11-22T13:45:00.000Z', + source: 'crawler', + }, + ], + byOffer: { + 'offer-cps-official': { + product_id: 'offer-cps-official', + merchant_name: 'CELLPHONES Official', + platform: 'cellphones', + price_current: 28_990_000, + price_original: 34_990_000, + claimed_discount_pct: 17, + real_discount_vs_median_pct: 4.9, + historical_min_price: 28_790_000, + historical_max_price: 33_990_000, + historical_median_price: 30_490_000, + observation_count: 14, + verdict: 'genuine_deal', + badge_label: 'Genuine Deal', + explanation: '4.9% below historical median.', + }, + }, + lowestEverPrice: 28_790_000, + lowestEverDate: '2026-11-11T00:00:00.000Z', + lowestEverMerchant: 'CELLPHONES Official', + highestEverPrice: 33_990_000, + currentMinPrice: 28_990_000, + fakeDiscountCount: 0, + genuineDealCount: 2, + }), + getCachedCompareMasterProducts: async (csv) => { + const slugs = csv.split(',').map((s) => s.trim().toLowerCase()); + const matched = slugs + .map((s) => { + if (s === iphoneProduct.slug) return iphoneProduct; + if (s === galaxyProduct.slug) return galaxyProduct; + if (s === macbookProduct.slug) return macbookProduct; + return null; + }) + .filter((p): p is MasterProduct => p !== null); + if (matched.length === 0) return []; + const firstCat = + (matched[0]!.metadata as { category_slug?: string })?.category_slug ?? + 'smartphones'; + return matched.filter( + (p) => + ((p.metadata as { category_slug?: string })?.category_slug ?? + 'smartphones') === firstCat + ); + }, + getCachedFilteredReviewCountsByMaster: async () => ({ + [iphoneProduct.id]: 6, + [galaxyProduct.id]: 3, + }), + getCachedInspectProductOrShopUrl: async ( + rawQuery + ): Promise => ({ + query: rawQuery, + matchedType: 'product_listing', + parsedUrl: parseEcommerceUrlOrQuery(rawQuery), + masterProduct: iphoneProduct, + matchedOffer: sampleOffersForIphone[3]!, + allOffers: sampleOffersForIphone, + discountAnalysis: null, + priceHistory: null, + reviewSummary: null, + merchantProfile: null, + suggestions: [galaxyProduct], + }), + getCrossPlatformDealRadar: async ( + opts + ): Promise => { + const deals = Array.from({ length: 12 }, (_, idx) => ({ + id: `deal-phone-${idx + 1}`, + verdict: + idx === 0 + ? ('genuine_all_time_low' as const) + : ('best_market_deal' as const), + verdictBadgeVi: 'Giá Tốt Nhất Hiện Có', + productSlug: idx === 0 ? iphoneProduct.slug : `sample-phone-${idx + 1}`, + productName: idx === 0 ? iphoneProduct.name : `Sample Phone ${idx + 1}`, + brand: idx % 2 === 0 ? 'Apple' : 'Samsung', + categorySlug: 'smartphones' as const, + productHref: `/smartphones/${idx === 0 ? iphoneProduct.slug : `sample-phone-${idx + 1}`}`, + imageUrl: '/img/devices/apple-iphone-16-pro-max-256gb.jpg', + platform: idx % 2 === 0 ? 'cellphones' : 'shopee', + merchantId: `merchant-${idx + 1}`, + merchantName: + idx % 2 === 0 ? 'CellphoneS Official' : 'Third-Party Shop', + isOfficialMall: idx % 2 === 0, + merchantRiskScore: 8, + offerUrl: 'https://cellphones.com.vn/iphone-16-pro-max.html', + priceCurrent: 18_000_000 + idx * 2_000_000, + priceOriginal: 22_000_000 + idx * 2_000_000, + marketMedianPrice: 20_500_000 + idx * 2_000_000, + marketMinPrice: 18_000_000 + idx * 2_000_000, + marketMaxPrice: 23_000_000 + idx * 2_000_000, + savingsVsMedianVnd: 2_500_000, + savingsVsMedianPct: 11.2, + marketOfferCount: 6, + claimedDiscountPct: 18, + fakeMarkupPct: 0, + jreviewsScore10: 9.4, + explanationVi: 'Rẻ hơn trung vị.', + })); + return { + generatedAt: FIXED_NOW_ISO, + categoryFilter: opts?.categorySlug ?? 'all', + platformFilter: opts?.platform ?? 'all', + totalClustersAnalyzed: 28, + totalOffersAnalyzed: 164, + totalMerchantsAnalyzed: 22, + genuineDeals: deals, + fakeSaleTraps: [], + priceSpreadLeaders: [], + }; + }, + }; +} + +function makeMcpRequest( + body: string | ReadableStream, + headers?: Record +): NextRequest { + const init: RequestInit & { duplex?: 'half' } = { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'x-forwarded-for': '203.0.113.10', + ...headers, + }, + body, + ...(typeof body !== 'string' ? { duplex: 'half' } : {}), + }; + return new NextRequest('https://rate.vn/api/mcp', init as never); +} + +async function runMcpTestSuite() { + console.warn( + '🧪 Running Rate Shopping MCP Server & AI Discovery Test Suite...' + ); + + // 0. Source-level server-only and zero em-dash / en-dash check + const mcpSourcePath = path.resolve(__dirname, '../mcp.ts'); + const mcpSource = fs.readFileSync(mcpSourcePath, 'utf8'); + assert.ok( + mcpSource.startsWith("import 'server-only';"), + "mcp.ts must start with import 'server-only';" + ); + for (const [label, text] of [ + ['mcp.ts', mcpSource], + ['/llms.txt', buildRateLlmsTxt()], + [ + '/.well-known/mcp.json', + JSON.stringify(buildRateWellKnownMcpDescriptor()), + ], + ] as const) { + assert.equal( + /[\u2013\u2014]/.test(text), + false, + `${label} must contain zero em-dashes or en-dashes` + ); + } + + // 1. Route HTTP method guards (GET -> 405, DELETE -> 405, OPTIONS -> 204) + const getRes = await getMcpRoute(); + assert.equal(getRes.status, 405); + assert.equal(getRes.headers.get('allow'), 'POST, OPTIONS'); + assert.equal(getRes.headers.get('access-control-allow-origin'), '*'); + const getErrJson = (await getRes.json()) as { + jsonrpc: string; + error: { code: number }; + }; + assert.equal(getErrJson.jsonrpc, '2.0'); + assert.equal(getErrJson.error.code, -32600); + + const deleteRes = await deleteMcpRoute(); + assert.equal(deleteRes.status, 405); + assert.equal(deleteRes.headers.get('allow'), 'POST, OPTIONS'); + + const optRes = await optionsMcpRoute(); + assert.equal(optRes.status, 204); + assert.equal(optRes.headers.get('allow'), 'POST, OPTIONS'); + assert.equal( + optRes.headers.get('access-control-allow-methods'), + 'POST, OPTIONS' + ); + + const readers = createMockReaders(); + const limiter = new BoundedSlidingWindowRateLimiter({ + windowMs: 60_000, + maxRequests: 100, + }); + const auditLimiter = new BoundedSlidingWindowRateLimiter({ + windowMs: 60_000, + maxRequests: 100, + }); + + // 2. initialize (2025-06-18, 2025-03-26 backward compatibility, and unknown version negotiation) + const initRes = await postMcpRoute( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: '2025-06-18', + capabilities: {}, + clientInfo: { name: 'claude-desktop', version: '1.2.0' }, + }, + }) + ) + ); + assert.equal(initRes.status, 200); + assert.equal( + initRes.headers.get('mcp-protocol-version'), + MCP_LATEST_PROTOCOL_VERSION + ); + const initBody = (await initRes.json()) as { + jsonrpc: string; + id: number; + result: { + protocolVersion: string; + capabilities: { tools: { listChanged: boolean } }; + serverInfo: { name: string }; + }; + }; + assert.equal(initBody.jsonrpc, '2.0'); + assert.equal(initBody.id, 1); + assert.equal(initBody.result.protocolVersion, '2025-06-18'); + assert.equal(initBody.result.capabilities.tools.listChanged, false); + assert.equal(initBody.result.serverInfo.name, 'rate-vn-shopping-mcp'); + + const initLegacyRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'init-legacy', + method: 'initialize', + params: { protocolVersion: '2025-03-26' }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(initLegacyRes.status, 200); + assert.equal(initLegacyRes.headers.get('mcp-protocol-version'), '2025-03-26'); + const initLegacyJson = (await initLegacyRes.json()) as { + result: { protocolVersion: string }; + }; + assert.equal(initLegacyJson.result.protocolVersion, '2025-03-26'); + + const initFutureRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'init-future', + method: 'initialize', + params: { protocolVersion: '2099-01-01' }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(initFutureRes.status, 200); + const initFutureJson = (await initFutureRes.json()) as { + result: { protocolVersion: string }; + }; + assert.equal(initFutureJson.result.protocolVersion, '2025-06-18'); + + // 3. notifications/initialized (202 Accepted without id, 200 JSON-RPC ack with id) & ping + const notifRes = await postMcpRoute( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + method: 'notifications/initialized', + }) + ) + ); + assert.equal(notifRes.status, 202); + assert.equal(await notifRes.text(), ''); + + const notifWithIdRes = await postMcpRoute( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'notif-1', + method: 'notifications/initialized', + }) + ) + ); + assert.equal(notifWithIdRes.status, 200); + assert.deepEqual(await notifWithIdRes.json(), { + jsonrpc: '2.0', + id: 'notif-1', + result: {}, + }); + + const pingRes = await postMcpRoute( + makeMcpRequest(JSON.stringify({ jsonrpc: '2.0', id: 7, method: 'ping' })) + ); + assert.equal(pingRes.status, 200); + assert.deepEqual(await pingRes.json(), { + jsonrpc: '2.0', + id: 7, + result: {}, + }); + + // 4. tools/list & Zod 4 JSON Schema verification + const listRes = await postMcpRoute( + makeMcpRequest( + JSON.stringify({ jsonrpc: '2.0', id: 'list-1', method: 'tools/list' }) + ) + ); + assert.equal(listRes.status, 200); + const listJson = (await listRes.json()) as { + result: { tools: typeof MCP_TOOL_DEFINITIONS }; + }; + assert.equal(listJson.result.tools.length, 5); + assert.deepEqual( + listJson.result.tools.map((t) => t.name), + [ + 'search_verified_catalog', + 'get_22_store_offers_and_price_truth', + 'compare_devices_by_use_case', + 'audit_listing_url', + 'get_genuine_deals', + ] + ); + for (const tool of listJson.result.tools) { + assert.equal(tool.inputSchema.type, 'object'); + assert.equal(tool.inputSchema.additionalProperties, false); + assert.equal(tool.annotations.readOnlyHint, true); + assert.equal(tool.annotations.destructiveHint, false); + } + const offersSchema = listJson.result.tools.find( + (t) => t.name === 'get_22_store_offers_and_price_truth' + )!.inputSchema as { + required?: string[]; + properties: Record; + }; + assert.deepEqual(offersSchema.required, ['slug']); + assert.equal(offersSchema.properties.limit?.maximum, MAX_MCP_RESULT_ITEMS); + + // 5. Tool 1: search_verified_catalog (caps <= 10, excludes bait/sold-out, includes citations + freshness) + const searchRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'call-search', + method: 'tools/call', + params: { + name: 'search_verified_catalog', + arguments: { category: 'smartphones', limit: 10 }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(searchRes.status, 200); + const searchJson = (await searchRes.json()) as { + result: { + isError?: boolean; + content: Array<{ type: string; text: string }>; + structuredContent: { + ok: boolean; + returned_count: number; + canonical_citation_url: string; + observed_at: string; + items: Array<{ + slug: string; + verified_min_price_vnd: number | null; + excluded_unavailable_offer_count: number; + excluded_bait_offer_count: number; + canonical_citation_url: string; + observed_at: string; + price_observed_at: string; + }>; + }; + }; + }; + assert.equal(searchJson.result.isError, undefined); + assert.equal(searchJson.result.structuredContent.ok, true); + assert.equal(searchJson.result.structuredContent.returned_count, 10); + assert.equal( + searchJson.result.structuredContent.canonical_citation_url, + 'https://rate.vn/smartphones' + ); + const firstSearchItem = searchJson.result.structuredContent.items[0]!; + assert.equal(firstSearchItem.slug, 'apple-iphone-16-pro-max-256gb'); + // Bait 89k case and 25.99M sold-out listing must be excluded -> floor is 28,990,000 VND! + assert.equal(firstSearchItem.verified_min_price_vnd, 28_990_000); + assert.equal(firstSearchItem.excluded_unavailable_offer_count, 1); + assert.equal(firstSearchItem.excluded_bait_offer_count, 1); + for (const item of searchJson.result.structuredContent.items) { + assert.ok( + item.canonical_citation_url.startsWith(`${CANONICAL_RATE_ORIGIN}/`) + ); + assert.ok(Date.parse(item.observed_at) > 0); + assert.ok(Date.parse(item.price_observed_at) > 0); + } + assert.deepEqual( + JSON.parse(searchJson.result.content[0]!.text), + searchJson.result.structuredContent + ); + + // 6. Tool 2: get_22_store_offers_and_price_truth + const offersRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'call-offers', + method: 'tools/call', + params: { + name: 'get_22_store_offers_and_price_truth', + arguments: { + slug: 'apple-iphone-16-pro-max-256gb', + officialOnly: true, + limit: 10, + }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(offersRes.status, 200); + const offersBody = (await offersRes.json()) as { + result: { + structuredContent: { + ok: boolean; + canonical_citation_url: string; + price_observed_at: string; + price_truth: { + verified_min_price_vnd: number; + excluded_unavailable_offer_count: number; + excluded_bait_offer_count: number; + }; + review_trust_summary: { + trust_model: string; + authentic_pct: number; + }; + offers: Array<{ + id: string; + price_current_vnd: number; + merchant: { review_risk_score: number | null }; + canonical_citation_url: string; + price_observed_at: string; + }>; + }; + }; + }; + const offersData = offersBody.result.structuredContent; + assert.equal(offersData.ok, true); + assert.equal( + offersData.canonical_citation_url, + 'https://rate.vn/smartphones/apple-iphone-16-pro-max-256gb' + ); + assert.equal(offersData.price_observed_at, '2026-11-22T13:45:00.000Z'); + assert.equal(offersData.price_truth.verified_min_price_vnd, 28_990_000); + assert.equal(offersData.price_truth.excluded_unavailable_offer_count, 1); + assert.equal(offersData.price_truth.excluded_bait_offer_count, 1); + assert.equal( + offersData.review_trust_summary.trust_model, + 'review_trust_v2_6_axis' + ); + assert.equal(offersData.review_trust_summary.authentic_pct, 88); + assert.equal(offersData.offers.length, 3); + assert.equal(offersData.offers[0]!.id, 'offer-cps-official'); + // Merchant with 0 analysed reviews must report null review_risk_score (#1376) + const shopeeOffer = offersData.offers.find( + (o) => o.id === 'offer-shopee-mall' + )!; + assert.equal(shopeeOffer.merchant.review_risk_score, null); + for (const offer of offersData.offers) { + assert.equal( + offer.canonical_citation_url, + 'https://rate.vn/smartphones/apple-iphone-16-pro-max-256gb#offers-table' + ); + assert.ok(Date.parse(offer.price_observed_at) > 0); + } + + // Not-found slug returns domain isError: true with citation URL + const missingSlugRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'call-missing-slug', + method: 'tools/call', + params: { + name: 'get_22_store_offers_and_price_truth', + arguments: { slug: 'unknown-device-slug-2026' }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + const missingSlugJson = (await missingSlugRes.json()) as { + result: { + isError: boolean; + structuredContent: { ok: boolean; canonical_citation_url: string }; + }; + }; + assert.equal(missingSlugJson.result.isError, true); + assert.equal(missingSlugJson.result.structuredContent.ok, false); + assert.equal( + missingSlugJson.result.structuredContent.canonical_citation_url, + CANONICAL_RATE_ORIGIN + ); + + // 7. Tool 3: compare_devices_by_use_case (weight overrides shift winner & cross-category check) + const comparePhotoRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'call-compare-photo', + method: 'tools/call', + params: { + name: 'compare_devices_by_use_case', + arguments: { + slugs: [ + 'apple-iphone-16-pro-max-256gb', + 'samsung-galaxy-s25-ultra-256gb', + ], + weights: { + camera: 90, + screen: 0, + performance: 0, + battery: 0, + value: 10, + }, + }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + const comparePhotoJson = (await comparePhotoRes.json()) as { + result: { + structuredContent: { + ok: boolean; + recommended_slug_for_use_case: string; + canonical_citation_url: string; + devices: Array<{ + slug: string; + canonical_citation_url: string; + observed_at: string; + }>; + }; + }; + }; + assert.equal(comparePhotoJson.result.structuredContent.ok, true); + assert.equal( + comparePhotoJson.result.structuredContent.recommended_slug_for_use_case, + 'apple-iphone-16-pro-max-256gb' + ); + assert.ok( + comparePhotoJson.result.structuredContent.canonical_citation_url.startsWith( + 'https://rate.vn/compare?cat=smartphones&slugs=' + ) + ); + + const compareValueRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'call-compare-value', + method: 'tools/call', + params: { + name: 'compare_devices_by_use_case', + arguments: { + slugs: [ + 'apple-iphone-16-pro-max-256gb', + 'samsung-galaxy-s25-ultra-256gb', + ], + weights: { + camera: 0, + screen: 0, + performance: 10, + battery: 40, + value: 50, + }, + }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + const compareValueJson = (await compareValueRes.json()) as { + result: { structuredContent: { recommended_slug_for_use_case: string } }; + }; + assert.equal( + compareValueJson.result.structuredContent.recommended_slug_for_use_case, + 'samsung-galaxy-s25-ultra-256gb' + ); + + const crossCatRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'call-compare-cross', + method: 'tools/call', + params: { + name: 'compare_devices_by_use_case', + arguments: { + slugs: [ + 'apple-iphone-16-pro-max-256gb', + 'apple-macbook-air-m3-16gb-256gb', + ], + }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + const crossCatJson = (await crossCatRes.json()) as { + result: { + isError: boolean; + structuredContent: { excluded_cross_category_slugs: string[] }; + }; + }; + assert.equal(crossCatJson.result.isError, true); + assert.deepEqual( + crossCatJson.result.structuredContent.excluded_cross_category_slugs, + ['apple-macbook-air-m3-16gb-256gb'] + ); + + // 8. Tool 4: audit_listing_url + SSRF / unsupported host rejection + const auditRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'call-audit', + method: 'tools/call', + params: { + name: 'audit_listing_url', + arguments: { + url: 'https://shopee.vn/Apple-iPhone-16-Pro-Max-i.88201679.27110898667?utm_source=fb&sp_atk=xyz', + observedPriceVnd: 29_490_000, + observedOriginalPriceVnd: 45_990_000, + }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + const auditJson = (await auditRes.json()) as { + result: { + structuredContent: { + ok: boolean; + canonical_listing_url: string; + canonical_citation_url: string; + inspect_citation_url: string; + observed_at: string; + merchant_risk_summary: { review_risk_score: number | null }; + top_competing_offers: Array<{ canonical_citation_url: string }>; + }; + }; + }; + assert.equal(auditJson.result.structuredContent.ok, true); + assert.ok( + !auditJson.result.structuredContent.canonical_listing_url.includes( + 'utm_source' + ) + ); + assert.equal( + auditJson.result.structuredContent.canonical_citation_url, + 'https://rate.vn/smartphones/apple-iphone-16-pro-max-256gb' + ); + assert.equal( + auditJson.result.structuredContent.merchant_risk_summary.review_risk_score, + null + ); + assert.ok( + auditJson.result.structuredContent.top_competing_offers.length <= 5 + ); + + for (const badUrl of [ + 'http://localhost:3000/secret', + 'http://127.0.0.1/admin', + 'javascript:alert(1)', + 'https://evil.example/product/123', + ]) { + const badUrlRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'bad-url', + method: 'tools/call', + params: { name: 'audit_listing_url', arguments: { url: badUrl } }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + const badUrlJson = (await badUrlRes.json()) as { error: { code: number } }; + assert.equal( + badUrlJson.error.code, + -32602, + `must reject unsafe URL ${badUrl}` + ); + } + + // 9. Tool 5: get_genuine_deals (caps <= 10, filters officialOnly & maxBudgetVnd) + const dealsRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'call-deals', + method: 'tools/call', + params: { + name: 'get_genuine_deals', + arguments: { + category: 'smartphones', + officialOnly: true, + maxBudgetVnd: 30_000_000, + limit: 10, + }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + const dealsJson = (await dealsRes.json()) as { + result: { + structuredContent: { + ok: boolean; + canonical_citation_url: string; + deals: Array<{ + is_official_mall: boolean; + price_current_vnd: number; + canonical_citation_url: string; + observed_at: string; + }>; + }; + }; + }; + assert.equal(dealsJson.result.structuredContent.ok, true); + assert.equal( + dealsJson.result.structuredContent.canonical_citation_url, + 'https://rate.vn/deals' + ); + assert.ok( + dealsJson.result.structuredContent.deals.length > 0 && + dealsJson.result.structuredContent.deals.length <= MAX_MCP_RESULT_ITEMS + ); + for (const deal of dealsJson.result.structuredContent.deals) { + assert.equal(deal.is_official_mall, true); + assert.ok(deal.price_current_vnd <= 30_000_000); + assert.ok( + deal.canonical_citation_url.startsWith('https://rate.vn/smartphones/') + ); + assert.equal(deal.observed_at, FIXED_NOW_ISO); + } + + // 10. Security & anti-DoS guards: oversize body (413 / -32600), streamed oversize, Content-Type (415), + // batch arrays, invalid JSON-RPC, prototype keys, lone surrogates, rate limit 429, and error sanitization + const oversizeHeaderRes = await handleMcpHttpPost( + makeMcpRequest('{"jsonrpc":"2.0","id":1,"method":"ping"}', { + 'content-length': String(MAX_MCP_BODY_BYTES + 1), + }), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(oversizeHeaderRes.status, 413); + const oversizeHeaderJson = (await oversizeHeaderRes.json()) as { + error: { code: number; data: { code: string } }; + }; + assert.equal(oversizeHeaderJson.error.code, -32600); + assert.equal(oversizeHeaderJson.error.data.code, 'PAYLOAD_TOO_LARGE'); + + let streamedBytes = 0; + const hugeStream = new ReadableStream({ + pull(controller) { + streamedBytes += 4096; + if (streamedBytes > 128 * 1024) controller.close(); + else controller.enqueue(new Uint8Array(4096).fill(65)); + }, + }); + const oversizeStreamRes = await handleMcpHttpPost( + makeMcpRequest(hugeStream), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(oversizeStreamRes.status, 413); + assert.ok( + streamedBytes <= MAX_MCP_BODY_BYTES + 8192, + `oversize stream cancelled early at ${streamedBytes} bytes` + ); + + // Exact 16384-byte valid JSON body passes size guard + const padPrefix = '{"jsonrpc":"2.0","id":"'; + const padSuffix = '","method":"ping"}'; + const exact16kId = 'x'.repeat(200); + const exactPadded = + `${padPrefix}${exact16kId}${padSuffix}` + + ' '.repeat( + MAX_MCP_BODY_BYTES - + Buffer.byteLength(`${padPrefix}${exact16kId}${padSuffix}`, 'utf8') + ); + assert.equal(Buffer.byteLength(exactPadded, 'utf8'), MAX_MCP_BODY_BYTES); + const exact16kRes = await handleMcpHttpPost(makeMcpRequest(exactPadded), { + readers, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + }); + assert.equal(exact16kRes.status, 200); + + // Wrong Content-Type -> 415 + const wrongCtRes = await handleMcpHttpPost( + makeMcpRequest('{"jsonrpc":"2.0","id":1,"method":"ping"}', { + 'content-type': 'text/plain', + }), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(wrongCtRes.status, 415); + + // Batch array -> 400 -32600 + const batchRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify([ + { jsonrpc: '2.0', id: 1, method: 'ping' }, + { jsonrpc: '2.0', id: 2, method: 'ping' }, + ]) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(batchRes.status, 400); + assert.equal( + ((await batchRes.json()) as { error: { code: number } }).error.code, + -32600 + ); + + // Invalid JSON & invalid JSON-RPC envelopes + const badJsonRes = await handleMcpHttpPost(makeMcpRequest('{broken'), { + readers, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + }); + assert.equal(badJsonRes.status, 400); + assert.equal( + ((await badJsonRes.json()) as { error: { code: number } }).error.code, + -32700 + ); + + for (const invalidEnvelope of [ + '{"jsonrpc":"1.0","id":1,"method":"ping"}', + '{"jsonrpc":"2.0","id":null,"method":"ping"}', + '{"jsonrpc":"2.0","method":"tools/list"}', + '{"jsonrpc":"2.0","id":{},"method":"ping"}', + ]) { + const res = await handleMcpHttpPost(makeMcpRequest(invalidEnvelope), { + readers, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + }); + assert.equal(res.status, 400); + assert.equal( + ((await res.json()) as { error: { code: number } }).error.code, + -32600 + ); + } + + // Prototype pollution keys rejected at root, params, and nested arguments + for (const protoPayload of [ + '{"jsonrpc":"2.0","id":1,"method":"ping","__proto__":{"polluted":true}}', + '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_genuine_deals","arguments":{"constructor":{"prototype":{"polluted":true}}}}}', + '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"prototype":{}}}', + ]) { + const protoRes = await handleMcpHttpPost(makeMcpRequest(protoPayload), { + readers, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + }); + assert.equal(protoRes.status, 400); + assert.equal( + ((await protoRes.json()) as { error: { code: number } }).error.code, + -32600 + ); + assert.equal( + ({} as Record).polluted, + undefined, + 'Object.prototype must never be polluted' + ); + } + + // Lone UTF-16 surrogate sanitization via .toWellFormed() + let capturedWellFormedSearch = ''; + const surrogateRes = await handleMcpHttpPost( + makeMcpRequest( + '{"jsonrpc":"2.0","id":"surr-1","method":"tools/call","params":{"name":"search_verified_catalog","arguments":{"query":"iPhone \\uD800 16"}}}' + ), + { + readers: { + ...readers, + getCachedMasterProducts: async (p) => { + capturedWellFormedSearch = p?.search ?? ''; + return [iphoneProduct]; + }, + }, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + } + ); + assert.equal(surrogateRes.status, 200); + assert.equal(capturedWellFormedSearch, 'iPhone \uFFFD 16'); + + // Strict Zod 4 rejection of limit > 10 and unknown extra arguments + for (const invalidCallArgs of [ + { category: 'smartphones', limit: 11 }, + { category: 'smartphones', offset: 20 }, + { minPriceVnd: 30_000_000, maxPriceVnd: 10_000_000 }, + ]) { + const badArgsRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'bad-args', + method: 'tools/call', + params: { + name: 'search_verified_catalog', + arguments: invalidCallArgs, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(badArgsRes.status, 200); + assert.equal( + ((await badArgsRes.json()) as { error: { code: number } }).error.code, + -32602 + ); + } + + // Unknown method (-32601) and unknown tool (-32602) + const unknownMethodRes = await handleMcpHttpPost( + makeMcpRequest('{"jsonrpc":"2.0","id":9,"method":"resources/list"}'), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal( + ((await unknownMethodRes.json()) as { error: { code: number } }).error.code, + -32601 + ); + + const unknownToolRes = await handleMcpHttpPost( + makeMcpRequest( + '{"jsonrpc":"2.0","id":10,"method":"tools/call","params":{"name":"drop_database","arguments":{}}}' + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal( + ((await unknownToolRes.json()) as { error: { code: number } }).error.code, + -32602 + ); + + // Internal DB error sanitization (never leak PGRST / table / schema names) + const dbFailRes = await handleMcpHttpPost( + makeMcpRequest( + '{"jsonrpc":"2.0","id":"db-err","method":"tools/call","params":{"name":"get_genuine_deals","arguments":{}}}' + ), + { + readers: { + ...readers, + getCrossPlatformDealRadar: async () => { + throw new Error( + 'PGRST116: relation "rate.master_products" does not exist in schema "rate" on supabase' + ); + }, + }, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + } + ); + assert.equal(dbFailRes.status, 200); + const dbFailText = await dbFailRes.text(); + assert.doesNotMatch( + dbFailText, + /PGRST|master_products|schema|supabase/i, + 'must never leak internal database details' + ); + const dbFailParsed = JSON.parse(dbFailText) as { + result: { isError: boolean }; + }; + assert.equal(dbFailParsed.result.isError, true); + + // Rate limit 429 + Retry-After on both overall MCP limiter and audit_listing_url limiter + const strictLimiter = new BoundedSlidingWindowRateLimiter({ + windowMs: 60_000, + maxRequests: 2, + }); + for (let i = 0; i < 2; i++) { + const ok = await handleMcpHttpPost( + makeMcpRequest('{"jsonrpc":"2.0","id":1,"method":"ping"}', { + 'x-forwarded-for': '198.51.100.77', + }), + { readers, rateLimiter: strictLimiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(ok.status, 200); + } + const rlRes = await handleMcpHttpPost( + makeMcpRequest('{"jsonrpc":"2.0","id":3,"method":"ping"}', { + 'x-forwarded-for': '198.51.100.77', + }), + { readers, rateLimiter: strictLimiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(rlRes.status, 429); + assert.equal(rlRes.headers.get('retry-after'), '60'); + assert.match( + rlRes.headers.get('access-control-expose-headers') ?? '', + /Retry-After/ + ); + const rlJson = (await rlRes.json()) as { + error: { code: number; data: { code: string } }; + }; + assert.equal(rlJson.error.code, -32029); + assert.equal(rlJson.error.data.code, 'RATE_LIMIT_EXCEEDED'); + + const strictAuditLimiter = new BoundedSlidingWindowRateLimiter({ + windowMs: 60_000, + maxRequests: 1, + }); + const auditOk = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'a1', + method: 'tools/call', + params: { + name: 'audit_listing_url', + arguments: { + url: 'https://cellphones.com.vn/iphone-16-pro-max.html', + }, + }, + }), + { 'x-forwarded-for': '198.51.100.88' } + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: strictAuditLimiter } + ); + assert.equal(auditOk.status, 200); + const auditRl = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'a2', + method: 'tools/call', + params: { + name: 'audit_listing_url', + arguments: { + url: 'https://cellphones.com.vn/iphone-16-pro-max.html', + }, + }, + }), + { 'x-forwarded-for': '198.51.100.88' } + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: strictAuditLimiter } + ); + assert.equal(auditRl.status, 429); + assert.equal(auditRl.headers.get('retry-after'), '60'); + + // 11. /llms.txt and /.well-known/mcp.json route handlers + const llmsRes = await getLlmsTxtRoute(); + assert.equal(llmsRes.status, 200); + assert.equal( + llmsRes.headers.get('content-type'), + 'text/plain; charset=utf-8' + ); + assert.equal( + llmsRes.headers.get('cache-control'), + 'public, s-maxage=3600, stale-while-revalidate=86400' + ); + const llmsAllowHeaders = + llmsRes.headers.get('access-control-allow-headers') ?? ''; + assert.match(llmsAllowHeaders, /MCP-Protocol-Version/); + assert.match(llmsAllowHeaders, /Accept/); + const llmsBody = await llmsRes.text(); + for (const expectedFragment of [ + 'https://rate.vn/api/mcp', + 'https://rate.vn/.well-known/mcp.json', + 'https://rate.vn/api/v1/rate/openapi.json', + 'search_verified_catalog', + 'get_22_store_offers_and_price_truth', + 'compare_devices_by_use_case', + 'audit_listing_url', + 'get_genuine_deals', + '6-axis Review Trust Model v2', + 'anphatpc', + 'availability', + 'design', + 'display', + 'hardware', + 'battery', + 'camera', + 'connectivity', + 'cellular', + 'multimedia', + 'regulatory', + ]) { + assert.ok( + llmsBody.includes(expectedFragment), + `/llms.txt must mention ${expectedFragment}` + ); + } + + const wkRes = await getWellKnownMcpRoute(); + assert.equal(wkRes.status, 200); + assert.match(wkRes.headers.get('content-type') ?? '', /application\/json/); + assert.match( + wkRes.headers.get('access-control-allow-headers') ?? '', + /MCP-Protocol-Version/ + ); + assert.equal( + wkRes.headers.get('cache-control'), + 'public, s-maxage=3600, stale-while-revalidate=86400' + ); + const wkJson = (await wkRes.json()) as { + mcpVersion: string; + transport: string; + url: string; + endpoints: { mcp: string; transport: string }; + tools: Array<{ name: string }>; + }; + assert.equal(wkJson.mcpVersion, '2025-06-18'); + assert.equal(wkJson.transport, 'streamable-http'); + assert.equal(wkJson.url, 'https://rate.vn/api/mcp'); + assert.equal(wkJson.endpoints.mcp, 'https://rate.vn/api/mcp'); + assert.equal(wkJson.endpoints.transport, 'streamable-http'); + assert.equal(wkJson.tools.length, 5); + + // 12. Round-1 review regressions (protocol headers, stream errors, IDs, price filters, synthetic points, DOSafe masking, compare deduplication) + // 12a. audit_listing_url canonicalizes tracking params BEFORE getCachedInspectProductOrShopUrl and handles rate.vn dotted paths safely + let capturedInspectQuery = ''; + const canonicalAuditRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'audit-canon', + method: 'tools/call', + params: { + name: 'audit_listing_url', + arguments: { + url: 'https://shopee.vn/Apple-iPhone-16-Pro-Max-i.88201679.27110898667?utm_source=zalo&sp_atk=abc123&fbclid=xyz', + }, + }, + }) + ), + { + readers: { + ...readers, + getCachedInspectProductOrShopUrl: async (rawQuery) => { + capturedInspectQuery = rawQuery; + return readers.getCachedInspectProductOrShopUrl(rawQuery); + }, + }, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + } + ); + assert.equal(canonicalAuditRes.status, 200); + assert.ok( + !capturedInspectQuery.includes('utm_source') && + !capturedInspectQuery.includes('sp_atk') && + !capturedInspectQuery.includes('fbclid'), + `expected canonicalized URL before cache reader, got: ${capturedInspectQuery}` + ); + + for (const allowedRateUrl of [ + 'https://rate.vn/smartphones/nokia-8.1', + 'https://rate.vn/merchants/anker.vn', + ]) { + const okRateUrlRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'ok-rate-url', + method: 'tools/call', + params: { + name: 'audit_listing_url', + arguments: { url: allowedRateUrl }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + const okRateUrlJson = (await okRateUrlRes.json()) as { + result?: { structuredContent: { ok: boolean } }; + error?: unknown; + }; + assert.equal( + okRateUrlJson.error, + undefined, + `must allow ${allowedRateUrl}` + ); + assert.equal(okRateUrlJson.result?.structuredContent.ok, true); + } + + for (const rejectedRateUrl of [ + 'https://rate.vn/merchants/..', + 'https://rate.vn/api/mcp', + ]) { + const rejRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'rej-rate-url', + method: 'tools/call', + params: { + name: 'audit_listing_url', + arguments: { url: rejectedRateUrl }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal( + ((await rejRes.json()) as { error: { code: number } }).error.code, + -32602, + `must reject ${rejectedRateUrl}` + ); + } + + // 12b. Aborted/errored ReadableStream returns 400 JSON-RPC -32700 (never unhandled 500) + const abortedStream = new ReadableStream({ + pull(controller) { + controller.error(new Error('client socket reset mid-stream')); + }, + }); + const abortedRes = await handleMcpHttpPost(makeMcpRequest(abortedStream), { + readers, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + }); + assert.equal(abortedRes.status, 400); + assert.equal( + ((await abortedRes.json()) as { error: { code: number } }).error.code, + -32700 + ); + + // 12c. MCP-Protocol-Version header negotiation on initialize vs strict check on ping + const initFutureHeaderRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'init-hdr', + method: 'initialize', + params: { protocolVersion: '2099-01-01' }, + }), + { 'mcp-protocol-version': '2099-01-01' } + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(initFutureHeaderRes.status, 200); + assert.equal( + initFutureHeaderRes.headers.get('mcp-protocol-version'), + '2025-06-18' + ); + + const ping202503Res = await handleMcpHttpPost( + makeMcpRequest('{"jsonrpc":"2.0","id":1,"method":"ping"}', { + 'mcp-protocol-version': '2025-03-26', + }), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(ping202503Res.status, 200); + assert.equal(ping202503Res.headers.get('mcp-protocol-version'), '2025-03-26'); + + const pingUnsupportedVerRes = await handleMcpHttpPost( + makeMcpRequest('{"jsonrpc":"2.0","id":1,"method":"ping"}', { + 'mcp-protocol-version': '2099-01-01', + }), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(pingUnsupportedVerRes.status, 400); + assert.equal( + ((await pingUnsupportedVerRes.json()) as { error: { code: number } }).error + .code, + -32600 + ); + + // 12d. search_verified_catalog enforces minPriceVnd/maxPriceVnd & price_asc on verified_min_price_vnd (never bait stored min_price) + const baitStoredFloorProduct = makeProduct({ + id: '11111111-1111-4111-8111-000000000099', + slug: 'bait-stored-floor-phone', + name: 'Bait Stored Floor Phone', + // Stored min_price polluted by 89k case, while real offer is 28.99M + min_price: 89_000, + max_price: 30_990_000, + }); + const searchPriceFilterRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'search-price-truth', + method: 'tools/call', + params: { + name: 'search_verified_catalog', + arguments: { + category: 'smartphones', + maxPriceVnd: 27_000_000, + sort: 'price_asc', + limit: 10, + }, + }, + }) + ), + { + readers: { + ...readers, + getCachedMasterProducts: async () => [ + baitStoredFloorProduct, + galaxyProduct, + ], + getCachedMasterProductOffers: async (id) => + id === baitStoredFloorProduct.id + ? sampleOffersForIphone + : sampleOffersForGalaxy, + }, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + } + ); + const searchPriceFilterJson = (await searchPriceFilterRes.json()) as { + result: { + structuredContent: { + items: Array<{ slug: string; verified_min_price_vnd: number }>; + }; + }; + }; + assert.deepEqual( + searchPriceFilterJson.result.structuredContent.items.map((i) => i.slug), + ['samsung-galaxy-s25-ultra-256gb'] + ); + + // 12e. get_22_store_offers_and_price_truth ignores synthetic live_listing / id < 0 points and sold-out offer timestamps, and masks dosafe_risk_known: false -> null (#1465) + const syntheticHistRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'offers-synth', + method: 'tools/call', + params: { + name: 'get_22_store_offers_and_price_truth', + arguments: { slug: 'apple-iphone-16-pro-max-256gb' }, + }, + }) + ), + { + readers: { + ...readers, + getCachedMasterProductPriceHistory: async () => ({ + points: [ + { + id: -1, + product_id: 'offer-cps-official', + merchant_name: 'CELLPHONES Official', + platform: 'cellphones', + is_official: true, + price: 28_990_000, + price_original: 34_990_000, + recorded_at: '2099-01-01T00:00:00.000Z', + source: 'live_listing', + }, + { + id: 2, + product_id: 'offer-sold-out', + merchant_name: 'TIKI Sold Out', + platform: 'tiki', + is_official: true, + price: 25_990_000, + price_original: 34_990_000, + recorded_at: '2098-01-01T00:00:00.000Z', + source: 'crawler', + }, + { + id: 3, + product_id: 'offer-cps-official', + merchant_name: 'CELLPHONES Official', + platform: 'cellphones', + is_official: true, + price: 28_990_000, + price_original: 34_990_000, + recorded_at: '2026-11-22T11:15:00.000Z', + source: 'crawler', + }, + ], + byOffer: {}, + lowestEverPrice: 28_790_000, + lowestEverDate: '2026-11-11T00:00:00.000Z', + lowestEverMerchant: 'CELLPHONES Official', + highestEverPrice: 33_990_000, + currentMinPrice: 28_990_000, + fakeDiscountCount: 0, + genuineDealCount: 1, + }), + }, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + } + ); + const syntheticHistJson = (await syntheticHistRes.json()) as { + result: { + structuredContent: { + price_observed_at: string; + offers: Array<{ + id: string; + merchant: { + dosafe_risk_score: number | null; + review_risk_score: number | null; + }; + }>; + }; + }; + }; + assert.equal( + syntheticHistJson.result.structuredContent.price_observed_at, + '2026-11-22T11:15:00.000Z' + ); + const shopeeMasked = syntheticHistJson.result.structuredContent.offers.find( + (o) => o.id === 'offer-shopee-mall' + )!; + assert.equal(shopeeMasked.merchant.dosafe_risk_score, null); + assert.equal(shopeeMasked.merchant.review_risk_score, null); + + // 12f. JSON-RPC numeric IDs (0 and -5 allowed, fractional 1.5 & >53-bit integer rejected), Accept q=0 -> 406, enum message, and compare deduplication/not_found/unrated + for (const validNumericId of [0, -5]) { + const idOkRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ jsonrpc: '2.0', id: validNumericId, method: 'ping' }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(idOkRes.status, 200); + assert.equal(((await idOkRes.json()) as { id: number }).id, validNumericId); + } + + for (const unsafeIdBody of [ + '{"jsonrpc":"2.0","id":1.5,"method":"ping"}', + '{"jsonrpc":"2.0","id":9007199254740993,"method":"ping"}', + ]) { + const badIdRes = await handleMcpHttpPost(makeMcpRequest(unsafeIdBody), { + readers, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + }); + assert.equal(badIdRes.status, 400); + assert.equal( + ((await badIdRes.json()) as { error: { code: number } }).error.code, + -32600 + ); + } + + const qZeroAcceptRes = await handleMcpHttpPost( + makeMcpRequest('{"jsonrpc":"2.0","id":1,"method":"ping"}', { + accept: 'application/json;q=0, text/event-stream;q=1', + }), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(qZeroAcceptRes.status, 406); + + const invalidPlatformRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'bad-plat', + method: 'tools/call', + params: { + name: 'get_genuine_deals', + arguments: { platform: 'amazon' }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + const invalidPlatformJson = (await invalidPlatformRes.json()) as { + error: { code: number; message: string }; + }; + assert.equal(invalidPlatformJson.error.code, -32602); + assert.match(invalidPlatformJson.error.message, /platform/i); + + const compareDedupRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'cmp-dedup', + method: 'tools/call', + params: { + name: 'compare_devices_by_use_case', + arguments: { + slugs: [ + 'iphone-16-pro-max', + 'apple-iphone-16-pro-max-256gb', + 'iphone-16-pro-max@999tb', + 'samsung-galaxy-s25-ultra-256gb', + ], + }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + const compareDedupJson = (await compareDedupRes.json()) as { + result: { + structuredContent: { + ok: boolean; + deduplicated_slugs: string[]; + not_found_slugs: string[]; + }; + }; + }; + assert.equal(compareDedupJson.result.structuredContent.ok, true); + assert.deepEqual( + compareDedupJson.result.structuredContent.deduplicated_slugs, + ['apple-iphone-16-pro-max-256gb'] + ); + assert.deepEqual(compareDedupJson.result.structuredContent.not_found_slugs, [ + 'iphone-16-pro-max@999tb', + ]); + + // Unrated devices return recommended_slug_for_use_case: null rather than fabricating a winner + const unratedA = makeProduct({ + id: '11111111-1111-4111-8111-000000000091', + slug: 'unrated-phone-a', + name: 'Unrated Phone A', + total_reviews: 0, + average_rating: 0, + rating_score: 0, + user_rating_weighted: 0, + expert_rating: 0, + authentic_review_count: 0, + criteria_scores: {}, + }); + const unratedB = makeProduct({ + id: '11111111-1111-4111-8111-000000000092', + slug: 'unrated-phone-b', + name: 'Unrated Phone B', + total_reviews: 0, + average_rating: 0, + rating_score: 0, + user_rating_weighted: 0, + expert_rating: 0, + authentic_review_count: 0, + criteria_scores: {}, + }); + const compareUnratedRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'cmp-unrated', + method: 'tools/call', + params: { + name: 'compare_devices_by_use_case', + arguments: { slugs: ['unrated-phone-a', 'unrated-phone-b'] }, + }, + }) + ), + { + readers: { + ...readers, + getCachedCompareMasterProducts: async () => [unratedA, unratedB], + getCachedFilteredReviewCountsByMaster: async () => ({}), + }, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + } + ); + const compareUnratedJson = (await compareUnratedRes.json()) as { + result: { + structuredContent: { + ok: boolean; + recommended_slug_for_use_case: string | null; + }; + }; + }; + assert.equal(compareUnratedJson.result.structuredContent.ok, true); + assert.equal( + compareUnratedJson.result.structuredContent.recommended_slug_for_use_case, + null + ); + + console.warn( + ' ✅ Rate Shopping MCP Server (/api/mcp), /llms.txt & /.well-known/mcp.json suite passed (#1866)' + ); +} + +runMcpTestSuite().catch((err) => { + console.error(err); + process.exit(1); +}); diff --git a/apps/web/src/server/rate/mcp.ts b/apps/web/src/server/rate/mcp.ts new file mode 100644 index 000000000..f056a730c --- /dev/null +++ b/apps/web/src/server/rate/mcp.ts @@ -0,0 +1,3008 @@ +import 'server-only'; +import { NextResponse } from 'next/server'; +import { z } from 'zod'; +import { + applyCategorySpecTemplate, + normalizeOfferId, + plausibleOffers, +} from '@repo/shared-data/rules'; +import { + MAX_VALID_VND_PRICE, + getMasterProductCategorySlug, + getMasterProductHref, + normalizeOfferOriginalPrice, + parseEcommerceUrlOrQuery, + type CanonicalCategorySlug, + type MasterProduct, + type MasterProductFilterParams, + type MasterProductPriceHistorySummary, + type MerchantOffer, + type ReviewAnalysisSummary, + type ReviewItem, + type UrlInspectionResult, +} from '@/lib/rate-api'; +import { radarExportFields } from '@/lib/deal-radar'; +import { compareTarget, lookupSlugAnyCase } from '@/lib/item-compare'; +import { + LEADERBOARD_SCORE_CRITERIA, + displayedScore5, + leaderboardCriteriaForCategory, + scoreMasterProductForLeaderboard, + sharedScoredCriteria, + weightedCriteriaScore5, + type FilteredReviewCountsByMaster, + type LeaderboardCriteriaWeights, + type LeaderboardScoreCriterion, +} from '@/lib/leaderboard-engine'; +import { isOfferUnavailable } from '@/lib/product-market-stats'; +import { productRatingScore5 } from '@/lib/rate-domain'; +import { roundScore } from '@/lib/rating-display'; +import { listingCountForSaleState, saleStateOfMaster } from '@/lib/sale-state'; +import { + getCachedCompareMasterProducts, + getCachedFilteredReviewCountsByMaster, + getCachedInspectProductOrShopUrl, + getCachedMasterProductBySlug, + getCachedMasterProductOffers, + getCachedMasterProductPriceHistory, + getCachedMasterProductReviewSummary, + getCachedMasterProductReviews, + getCachedMasterProducts, + sanitizeCachedEntityId, +} from './index'; +import { + BoundedSlidingWindowRateLimiter, + SUPPORTED_PLATFORM_SLUGS, + extractClientRateLimitKey, + inspectRateLimiter, + isSafeCrowdIngestHttpUrl, + parseFiniteDecimalInput, + resolveInspectObservedPrices, + splitComparePinToken, + withPublicOfferReviewRisk, + withPublicReviewRisk, +} from './api-handler'; +import { + computeProductRadarSignal, + getCrossPlatformDealRadar, + type CrossPlatformDealRadarResponse, +} from './deals'; +import { + canonicalizeProductUrl, + detectAccessoryOrJunk, + detectPlatformFromInput, + evaluateExtensionPriceVerdict, +} from './extension'; +import { isItemModelOn } from './item-model'; +import { + getCachedCatalogSlugResolution, + getCachedItemVariants, +} from './item-route'; + +export const CANONICAL_RATE_ORIGIN = 'https://rate.vn'; +export const MCP_LATEST_PROTOCOL_VERSION = '2025-06-18'; +export const SUPPORTED_MCP_PROTOCOL_VERSIONS = [ + '2025-06-18', + '2025-03-26', + '2024-11-05', +] as const; + +export const MAX_MCP_BODY_BYTES = 16_384; +export const MAX_MCP_RESULT_ITEMS = 10; +export const MCP_RATE_LIMIT_WINDOW_MS = 60_000; +export const MCP_RATE_LIMIT_MAX_REQUESTS = 60; +export const MCP_RETRY_AFTER_SECONDS = 60; + +const MAX_JSON_NESTING_DEPTH = 24; +const MAX_JSON_OBJECT_KEYS = 64; +const MAX_JSON_ARRAY_ITEMS = 64; +const MAX_RPC_ID_LENGTH = 256; +const MAX_SAFE_PUBLIC_ERROR_LENGTH = 512; +const MAX_SEARCH_PRICE_FILTER_CANDIDATES = 40; + +const FORBIDDEN_OBJECT_KEYS = new Set([ + '__proto__', + 'constructor', + 'prototype', +]); +const DISALLOWED_IDENTIFIER_TOKENS = new Set([ + 'null', + 'undefined', + 'nan', + 'none', + 'infinity', + '-infinity', + 'true', + 'false', + '__proto__', + 'constructor', + 'prototype', +]); +const DB_INTERNAL_ERROR_REGEX = + /PGRST\d+|relation\s+"[^"]+"|column\s+"[^"]+"|permission denied|syntax error at|duplicate key value|violates foreign key|violates check constraint|schema\s+"rate"|rate-api:\s*failed to|supabase/i; + +export const MCP_SERVER_INFO = { + name: 'rate-vn-shopping-mcp', + title: 'Rate.vn Verified Shopping & Price Truth MCP Server', + version: '1.0.0', +} as const; + +export const MCP_SERVER_INSTRUCTIONS = + 'Read-only Vietnamese tech shopping intelligence across 22 retail platforms and 5 device categories (smartphones, tablets, laptops, smartwatches, earbuds). Always cite canonical_citation_url (https://rate.vn/...) and freshness timestamps (observed_at / price_observed_at) when presenting prices, specifications, or 6-axis review trust verdicts to users. Sold-out and implausibly low bait-price listings are excluded from market floor calculations.'; + +export const MCP_CORS_HEADERS: Record = { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'POST, OPTIONS', + 'Access-Control-Allow-Headers': + 'Content-Type, Accept, MCP-Protocol-Version, Mcp-Session-Id', + 'Access-Control-Expose-Headers': 'Retry-After, MCP-Protocol-Version', +}; + +export const MCP_DISCOVERY_CORS_HEADERS: Record = { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'GET, OPTIONS', + 'Access-Control-Allow-Headers': + 'Content-Type, Accept, MCP-Protocol-Version, Authorization, X-Rate-Extension-Version', +}; + +export const mcpRateLimiter = new BoundedSlidingWindowRateLimiter({ + windowMs: MCP_RATE_LIMIT_WINDOW_MS, + maxRequests: MCP_RATE_LIMIT_MAX_REQUESTS, + maxBuckets: 5_000, +}); + +const SUPPORTED_PLATFORM_LIST = Array.from(SUPPORTED_PLATFORM_SLUGS) as [ + string, + ...string[], +]; + +const SUPPORTED_CATEGORY_ENUM = z.enum([ + 'all', + 'smartphones', + 'tablets', + 'laptops', + 'smartwatches', + 'earbuds', +]); + +const SUPPORTED_PLATFORM_OR_ALL_ENUM = z.enum([ + 'all', + ...SUPPORTED_PLATFORM_LIST, +]); + +function isValidSlugToken(raw: string, maxLength = 120): boolean { + if (typeof raw !== 'string') return false; + const lower = raw.toLowerCase(); + return ( + raw.length >= 1 && + raw.length <= maxLength && + /^[a-zA-Z0-9._-]+$/.test(raw) && + /[a-zA-Z0-9]/.test(raw) && + !/^0+$/.test(raw) && + !DISALLOWED_IDENTIFIER_TOKENS.has(lower) && + !raw.startsWith('.') && + !raw.endsWith('.') && + !raw.includes('..') + ); +} + +function isValidCompareSlugOrPin(token: string): boolean { + const atIdx = token.indexOf('@'); + if (atIdx === -1) { + return isValidSlugToken(token, 120); + } + if (token.indexOf('@', atIdx + 1) !== -1) return false; + const slugPart = token.slice(0, atIdx); + const variantPart = token.slice(atIdx + 1); + return ( + isValidSlugToken(slugPart, 120) && + variantPart.length >= 1 && + variantPart.length <= 64 && + /^[a-zA-Z0-9_-]+$/.test(variantPart) && + /[a-zA-Z0-9]/.test(variantPart) && + !DISALLOWED_IDENTIFIER_TOKENS.has(variantPart.toLowerCase()) + ); +} + +function isValidBrandFilter(raw: string): boolean { + const trimmed = raw.trim(); + const lower = trimmed.toLowerCase(); + return ( + trimmed.length >= 1 && + trimmed.length <= 40 && + /^[\p{L}\p{N}\s.+-]+$/u.test(trimmed) && + /[\p{L}\p{N}]/u.test(trimmed) && + !/^0+$/.test(trimmed) && + !DISALLOWED_IDENTIFIER_TOKENS.has(lower) && + !trimmed.includes('..') + ); +} + +function isSupportedRetailOrRateInspectionUrl(rawUrl: string): boolean { + if (!isSafeCrowdIngestHttpUrl(rawUrl)) return false; + const detected = detectPlatformFromInput(null, rawUrl); + if (detected && SUPPORTED_PLATFORM_SLUGS.has(detected)) return true; + const parsed = parseEcommerceUrlOrQuery(rawUrl); + if ( + typeof parsed.platform === 'string' && + SUPPORTED_PLATFORM_SLUGS.has(parsed.platform) + ) { + return true; + } + try { + const urlObj = new URL(rawUrl.trim()); + const host = urlObj.hostname.toLowerCase(); + if (host === 'rate.vn' || host === 'www.rate.vn') { + const cleanPath = urlObj.pathname.replace(/\/+$/, ''); + const segments = cleanPath.split('/').filter(Boolean); + if (segments.length === 2) { + const [section, identifier] = segments; + const lowerSection = section!.toLowerCase(); + if ( + (lowerSection === 'smartphones' || + lowerSection === 'tablets' || + lowerSection === 'laptops' || + lowerSection === 'smartwatches' || + lowerSection === 'earbuds' || + lowerSection === 'merchants') && + isValidSlugToken(identifier!, 128) + ) { + return true; + } + } + } + } catch { + return false; + } + return false; +} + +export const SearchVerifiedCatalogInputSchema = z + .strictObject({ + query: z + .string() + .trim() + .min(1) + .max(160) + .optional() + .describe( + 'Model name, series, or chipset keyword (for example "iPhone 16 Pro", "Snapdragon 8 Elite", "Sony WF-1000XM5").' + ), + category: SUPPORTED_CATEGORY_ENUM.default('all').describe( + 'Canonical device category filter across the 5 supported categories, or "all".' + ), + brand: z + .string() + .trim() + .min(1) + .max(40) + .refine(isValidBrandFilter, 'Invalid brand filter') + .optional() + .describe('Manufacturer name filter (for example "Apple", "Samsung").'), + minPriceVnd: z + .number() + .int() + .min(1) + .max(MAX_VALID_VND_PRICE) + .optional() + .describe('Minimum verified VND price floor.'), + maxPriceVnd: z + .number() + .int() + .min(1) + .max(MAX_VALID_VND_PRICE) + .optional() + .describe('Maximum verified VND price ceiling.'), + sort: z + .enum([ + 'default', + 'price_asc', + 'price_desc', + 'rating_desc', + 'merchants_desc', + 'newest', + ]) + .default('rating_desc') + .describe('Sort order for matched catalog devices.'), + limit: z + .number() + .int() + .min(1) + .max(MAX_MCP_RESULT_ITEMS) + .default(5) + .describe('Maximum results to return (1 to 10, default 5).'), + }) + .refine( + (v) => + v.minPriceVnd === undefined || + v.maxPriceVnd === undefined || + v.minPriceVnd <= v.maxPriceVnd, + { message: 'minPriceVnd must not exceed maxPriceVnd' } + ); + +export const GetStoreOffersAndPriceTruthInputSchema = z.strictObject({ + slug: z + .string() + .trim() + .min(1) + .max(120) + .refine((v) => isValidSlugToken(v, 120), 'Invalid product slug') + .describe( + 'Canonical product or item slug on Rate.vn (for example "apple-iphone-16-pro-max-256gb").' + ), + officialOnly: z + .boolean() + .default(false) + .describe( + 'When true, keep only verified Official Mall / authorized chain listings.' + ), + platform: SUPPORTED_PLATFORM_OR_ALL_ENUM.default('all').describe( + 'Optional filter for one of the 22 tracked Vietnamese retail platforms, or "all".' + ), + limit: z + .number() + .int() + .min(1) + .max(MAX_MCP_RESULT_ITEMS) + .default(MAX_MCP_RESULT_ITEMS) + .describe('Maximum verified in-stock offers to return (1 to 10).'), +}); + +export const CompareDevicesByUseCaseInputSchema = z + .strictObject({ + slugs: z + .array( + z + .string() + .trim() + .min(1) + .max(185) + .refine(isValidCompareSlugOrPin, 'Invalid compare product slug') + ) + .min(2) + .max(4) + .describe( + '2 to 4 canonical product slugs in the same device category to compare side-by-side.' + ), + persona: z + .enum([ + 'balanced', + 'photography', + 'gaming', + 'endurance', + 'business', + 'value_hunter', + ]) + .default('balanced') + .describe('Preset use-case scoring profile across 5 JReviews criteria.'), + weights: z + .strictObject({ + screen: z.number().min(0).max(100).optional(), + performance: z.number().min(0).max(100).optional(), + camera: z.number().min(0).max(100).optional(), + battery: z.number().min(0).max(100).optional(), + value: z.number().min(0).max(100).optional(), + }) + .optional() + .describe( + 'Optional custom weight overrides (0 to 100) for screen, performance, camera (or ANC on earbuds), battery, and value.' + ), + }) + .refine( + (v) => new Set(v.slugs.map((s) => s.toLowerCase())).size >= 2, + 'Provide at least 2 distinct product slugs' + ); + +export const AuditListingUrlInputSchema = z.strictObject({ + url: z + .string() + .trim() + .min(8) + .max(1024) + .refine( + (v) => isSafeCrowdIngestHttpUrl(v), + 'Provide a valid public HTTP/HTTPS listing URL' + ) + .refine( + isSupportedRetailOrRateInspectionUrl, + 'URL must belong to one of the 22 supported Vietnamese retail platforms or rate.vn' + ) + .describe( + 'Public listing URL from one of the 22 supported Vietnamese e-commerce platforms (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDD, FPT Shop, Hoang Ha, Di Dong Viet, Phong Vu, Dien May Xanh, TopZone, GearVN, Nguyen Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone, An Phat).' + ), + observedPriceVnd: z + .number() + .int() + .min(1) + .max(MAX_VALID_VND_PRICE) + .optional() + .describe('Optional live selling price in VND observed on the page.'), + observedOriginalPriceVnd: z + .number() + .int() + .min(1) + .max(MAX_VALID_VND_PRICE) + .optional() + .describe( + 'Optional strikethrough original price in VND declared by the seller.' + ), +}); + +export const GetGenuineDealsInputSchema = z.strictObject({ + category: SUPPORTED_CATEGORY_ENUM.default('all').describe( + 'Canonical device category filter across the 5 tech categories, or "all".' + ), + platform: SUPPORTED_PLATFORM_OR_ALL_ENUM.default('all').describe( + 'Optional filter for one of the 22 tracked retail platforms, or "all".' + ), + maxBudgetVnd: z + .number() + .int() + .min(1) + .max(MAX_VALID_VND_PRICE) + .optional() + .describe('Optional maximum VND budget ceiling for returned deals.'), + officialOnly: z + .boolean() + .default(false) + .describe( + 'When true, return deals from Official Mall / authorized stores only.' + ), + limit: z + .number() + .int() + .min(1) + .max(MAX_MCP_RESULT_ITEMS) + .default(MAX_MCP_RESULT_ITEMS) + .describe('Maximum genuine deals to return (1 to 10, default 10).'), +}); + +export type McpToolName = + | 'search_verified_catalog' + | 'get_22_store_offers_and_price_truth' + | 'compare_devices_by_use_case' + | 'audit_listing_url' + | 'get_genuine_deals'; + +export interface McpToolAnnotations { + title: string; + readOnlyHint: true; + destructiveHint: false; + idempotentHint: true; + openWorldHint: false; +} + +export interface McpToolDefinition { + name: McpToolName; + title: string; + description: string; + inputSchema: Record; + annotations: McpToolAnnotations; +} + +function exportToolInputJsonSchema(schema: z.ZodType): Record { + const raw = z.toJSONSchema(schema, { + io: 'input', + target: 'draft-2020-12', + unrepresentable: 'any', + }) as Record; + return { + ...raw, + type: 'object', + additionalProperties: false, + }; +} + +const READ_ONLY_ANNOTATIONS = (title: string): McpToolAnnotations => ({ + title, + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, +}); + +export const MCP_TOOL_DEFINITIONS: readonly McpToolDefinition[] = [ + { + name: 'search_verified_catalog', + title: 'Search Verified Tech Catalog', + description: + 'Search normalized tech products across 5 categories (smartphones, tablets, laptops, smartwatches, earbuds) with brand and VND price filters. Excludes sold-out and bait-price traps from floor prices and returns canonical_citation_url plus freshness timestamps (max 10 items).', + inputSchema: exportToolInputJsonSchema(SearchVerifiedCatalogInputSchema), + annotations: READ_ONLY_ANNOTATIONS('Search Verified Tech Catalog'), + }, + { + name: 'get_22_store_offers_and_price_truth', + title: 'Get 22-Store Offers & Price Truth', + description: + 'Return verified in-stock offers across 22 Vietnamese retail platforms, historical floor/median price truth, Deal Radar fake-sale flags, Bayesian rating, and 6-axis Review Trust Model v2 summary for a product slug (max 10 offers).', + inputSchema: exportToolInputJsonSchema( + GetStoreOffersAndPriceTruthInputSchema + ), + annotations: READ_ONLY_ANNOTATIONS('Get 22-Store Offers & Price Truth'), + }, + { + name: 'compare_devices_by_use_case', + title: 'Compare Devices by Use Case', + description: + 'Compare 2 to 4 same-category product slugs side-by-side across standardized 10-group specs, verified multi-store floor prices, and 5-criterion JReviews scores with optional persona or custom criterion weight overrides.', + inputSchema: exportToolInputJsonSchema(CompareDevicesByUseCaseInputSchema), + annotations: READ_ONLY_ANNOTATIONS('Compare Devices by Use Case'), + }, + { + name: 'audit_listing_url', + title: 'Audit Marketplace Listing URL', + description: + 'Inspect a product listing URL from any of the 22 supported Vietnamese marketplaces and retail chains, returning catalog match, 5-level fake-discount price verdict, accessory gatekeeper check, and DOSafe + AI review seller risk scores.', + inputSchema: exportToolInputJsonSchema(AuditListingUrlInputSchema), + annotations: READ_ONLY_ANNOTATIONS('Audit Marketplace Listing URL'), + }, + { + name: 'get_genuine_deals', + title: 'Get Genuine Multi-Store Floor Deals', + description: + 'List verified below-median and cross-platform floor deals across 22 Vietnamese retail platforms (limit <= 10), filtering out sold-out listings, implausibly low bait traps, high-risk sellers, and inflated strikethrough fake sales.', + inputSchema: exportToolInputJsonSchema(GetGenuineDealsInputSchema), + annotations: READ_ONLY_ANNOTATIONS('Get Genuine Multi-Store Floor Deals'), + }, +] as const; + +export interface McpResolvedCompareTarget { + variantSlug: string | null; + itemId: string | null; +} + +export interface McpDataReaders { + getCachedMasterProducts: ( + params?: MasterProductFilterParams + ) => Promise; + getCachedMasterProductBySlug: (slug: string) => Promise; + getCachedMasterProductOffers: ( + masterProductId: string + ) => Promise; + getCachedMasterProductReviews: ( + masterProductId: string + ) => Promise; + getCachedMasterProductReviewSummary: ( + masterProductId: string, + existingReviews?: ReviewItem[] + ) => Promise; + getCachedMasterProductPriceHistory: ( + masterProductId: string, + existingOffers?: MerchantOffer[] + ) => Promise; + getCachedCompareMasterProducts: ( + slugsCsv: string + ) => Promise; + getCachedFilteredReviewCountsByMaster: () => Promise; + getCachedInspectProductOrShopUrl: ( + rawQuery: string + ) => Promise; + getCrossPlatformDealRadar: (options?: { + categorySlug?: CanonicalCategorySlug | 'all'; + platform?: string; + limit?: number; + }) => Promise; + resolveCompareTokenTarget?: ( + rawToken: string + ) => Promise; + nowIso?: () => string; +} + +const ITEM_RESOLVER_SLUG_REGEX = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,159}$/; + +async function defaultResolveCompareTokenTarget( + rawToken: string +): Promise { + const typed = splitComparePinToken(rawToken, true); + const lower = splitComparePinToken(rawToken, false); + if (!isItemModelOn()) { + // Without the Item model, explicit @variant pins have no variant table to resolve against. + return typed.variantKey === null + ? { variantSlug: lower.slug, itemId: null } + : { variantSlug: null, itemId: null }; + } + if (!ITEM_RESOLVER_SLUG_REGEX.test(typed.slug)) { + return typed.variantKey === null + ? { variantSlug: lower.slug, itemId: null } + : { variantSlug: null, itemId: null }; + } + try { + const found = await lookupSlugAnyCase( + typed.slug, + getCachedCatalogSlugResolution + ); + const catalogRes = found.found; + const cmpRes = + !catalogRes || catalogRes.kind === 'unlinked' + ? { kind: 'unlinked' as const } + : catalogRes.kind === 'item' + ? { + kind: 'item' as const, + item: catalogRes.item, + variants: await getCachedItemVariants(catalogRes.item), + } + : { + kind: 'variant' as const, + item: catalogRes.item, + variant: catalogRes.variant, + variants: await getCachedItemVariants(catalogRes.item), + retired: catalogRes.retired, + }; + const target = compareTarget(cmpRes, lower); + if (!target) { + return { variantSlug: null, itemId: null }; + } + return { variantSlug: target.variantSlug, itemId: target.itemId }; + } catch { + return typed.variantKey === null + ? { variantSlug: lower.slug, itemId: null } + : { variantSlug: null, itemId: null }; + } +} + +const DEFAULT_MCP_READERS: McpDataReaders = { + getCachedMasterProducts, + getCachedMasterProductBySlug, + getCachedMasterProductOffers, + getCachedMasterProductReviews, + getCachedMasterProductReviewSummary, + getCachedMasterProductPriceHistory, + getCachedCompareMasterProducts, + getCachedFilteredReviewCountsByMaster, + getCachedInspectProductOrShopUrl, + getCrossPlatformDealRadar, + resolveCompareTokenTarget: defaultResolveCompareTokenTarget, + nowIso: () => new Date().toISOString(), +}; + +const PERSONA_WEIGHT_PRESETS: Record< + | 'balanced' + | 'photography' + | 'gaming' + | 'endurance' + | 'business' + | 'value_hunter', + LeaderboardCriteriaWeights +> = { + balanced: { + screen: 20, + performance: 20, + camera: 20, + battery: 20, + value: 20, + }, + photography: { + screen: 20, + performance: 15, + camera: 45, + battery: 10, + value: 10, + }, + gaming: { + screen: 25, + performance: 45, + camera: 5, + battery: 15, + value: 10, + }, + endurance: { + screen: 15, + performance: 15, + camera: 10, + battery: 45, + value: 15, + }, + business: { + screen: 35, + performance: 25, + camera: 10, + battery: 20, + value: 10, + }, + value_hunter: { + screen: 15, + performance: 20, + camera: 10, + battery: 15, + value: 40, + }, +}; + +function toWellFormedString(raw: string): string { + const maybeWellFormed = (raw as string & { toWellFormed?: () => string }) + .toWellFormed; + if (typeof maybeWellFormed === 'function') { + return maybeWellFormed.call(raw); + } + let out = ''; + for (let i = 0; i < raw.length; i++) { + const code = raw.charCodeAt(i); + if (code >= 0xd800 && code <= 0xdbff) { + const next = i + 1 < raw.length ? raw.charCodeAt(i + 1) : 0; + if (next >= 0xdc00 && next <= 0xdfff) { + out += raw[i]! + raw[i + 1]!; + i++; + } else { + out += '\ufffd'; + } + } else if (code >= 0xdc00 && code <= 0xdfff) { + out += '\ufffd'; + } else { + out += raw[i]!; + } + } + return out; +} + +export function deepSanitizeWellFormed(value: T): T { + if (typeof value === 'string') { + return toWellFormedString(value) as T; + } + if (Array.isArray(value)) { + return value.map((entry) => deepSanitizeWellFormed(entry)) as T; + } + if (value && typeof value === 'object') { + const out: Record = {}; + for (const key of Object.keys(value)) { + if (FORBIDDEN_OBJECT_KEYS.has(key)) continue; + if (!Object.hasOwn(value, key)) continue; + const safeKey = toWellFormedString(key); + if (FORBIDDEN_OBJECT_KEYS.has(safeKey)) continue; + out[safeKey] = deepSanitizeWellFormed( + (value as Record)[key] + ); + } + return out as T; + } + return value; +} + +function sanitizeMcpPublicText(raw: unknown, maxLength = 320): string { + if (typeof raw !== 'string') return ''; + const cleaned = toWellFormedString(raw) + .replace(/\p{Cc}+/gu, ' ') + .replace(/\s+/g, ' ') + .trim(); + return cleaned.length > maxLength + ? cleaned.slice(0, maxLength).trim() + : cleaned; +} + +function isSafeExternalHttpUrlWithMax( + rawUrl: string, + maxLength = 2048 +): boolean { + if (typeof rawUrl !== 'string') return false; + const trimmed = rawUrl.trim(); + if ( + !trimmed || + trimmed.length > maxLength || + /\s/.test(trimmed) || + /\p{Cc}/u.test(trimmed) + ) { + return false; + } + try { + const parsed = new URL(trimmed); + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { + return false; + } + if (parsed.username || parsed.password) return false; + const host = parsed.hostname.toLowerCase(); + if ( + !host || + !host.includes('.') || + host.startsWith('.') || + host.endsWith('.') || + host.includes('..') || + host.startsWith('[') || + host === 'localhost' || + host.endsWith('.localhost') || + host.endsWith('.local') || + host.endsWith('.internal') || + /^\d+(?:\.\d+){3}$/.test(host) + ) { + return false; + } + if (parsed.port !== '' && parsed.port !== '80' && parsed.port !== '443') { + return false; + } + return true; + } catch { + return false; + } +} + +function sanitizeExternalOfferUrl(raw: unknown): string | null { + if (typeof raw !== 'string') return null; + const trimmed = toWellFormedString(raw).trim(); + if (!isSafeExternalHttpUrlWithMax(trimmed, 2048)) return null; + return trimmed; +} + +export function buildCanonicalRateUrl(pathOrHref: string): string { + const cleaned = + typeof pathOrHref === 'string' ? toWellFormedString(pathOrHref).trim() : ''; + if ( + !cleaned || + !cleaned.startsWith('/') || + cleaned.startsWith('//') || + cleaned.includes('\\') || + /[\s\p{Cc}]/u.test(cleaned) + ) { + return CANONICAL_RATE_ORIGIN; + } + const pathPart = cleaned.split(/[?#]/)[0] ?? ''; + const segments = pathPart.split('/').filter(Boolean); + if (segments.some((seg) => seg === '.' || seg === '..')) { + return CANONICAL_RATE_ORIGIN; + } + return `${CANONICAL_RATE_ORIGIN}${cleaned}`; +} + +function buildSafeMerchantCitationUrl( + rawMerchantId: unknown, + fallbackUrl: string +): string { + const safeId = sanitizeCachedEntityId(rawMerchantId); + return safeId + ? buildCanonicalRateUrl(`/merchants/${encodeURIComponent(safeId)}`) + : fallbackUrl; +} + +function resolveValidIsoTimestamp(raw: unknown): string | null { + if (typeof raw !== 'string') return null; + const trimmed = raw.trim(); + if (!trimmed || trimmed.length > 64) return null; + const ms = Date.parse(trimmed); + if (!Number.isFinite(ms) || ms <= 0) return null; + return new Date(ms).toISOString(); +} + +function resolveProductObservedAt( + product: { updated_at?: unknown } | null | undefined, + fallbackIso: string +): { + observedAt: string; + freshnessSource: 'product_updated_at' | 'cache_snapshot'; +} { + const fromProduct = resolveValidIsoTimestamp(product?.updated_at); + if (fromProduct) { + return { observedAt: fromProduct, freshnessSource: 'product_updated_at' }; + } + return { observedAt: fallbackIso, freshnessSource: 'cache_snapshot' }; +} + +function computeMedianPrice(prices: readonly number[]): number | null { + const valid = prices + .filter((v) => Number.isFinite(v) && v > 0 && v <= MAX_VALID_VND_PRICE) + .sort((a, b) => a - b); + if (valid.length === 0) return null; + const mid = Math.floor(valid.length / 2); + if (valid.length % 2 === 1) return valid[mid]!; + return Math.round((valid[mid - 1]! + valid[mid]!) / 2); +} + +function getPlausibleInStockMerchantOffers(offers: readonly MerchantOffer[]): { + inStockOffers: MerchantOffer[]; + plausibleInStockOffers: MerchantOffer[]; + excludedUnavailableCount: number; + excludedBaitCount: number; +} { + const safeAll = Array.isArray(offers) + ? offers.filter((o): o is MerchantOffer => + Boolean(o && typeof o === 'object' && !Array.isArray(o)) + ) + : []; + const inStockOffers = safeAll.filter((o) => { + if (isOfferUnavailable(o)) return false; + const price = parseFiniteDecimalInput(o.price_current); + return Number.isFinite(price) && price > 0 && price <= MAX_VALID_VND_PRICE; + }); + const plausibleInStockOffers = plausibleOffers(inStockOffers); + return { + inStockOffers, + plausibleInStockOffers, + excludedUnavailableCount: Math.max( + 0, + safeAll.length - inStockOffers.length + ), + excludedBaitCount: Math.max( + 0, + inStockOffers.length - plausibleInStockOffers.length + ), + }; +} + +function resolveExpertRating10(product: MasterProduct): number | null { + const raw = parseFiniteDecimalInput(product.expert_rating); + if (!Number.isFinite(raw) || raw <= 0 || raw > 100) return null; + const normalized10 = raw > 10 ? raw / 10 : raw <= 5 ? raw * 2 : raw; + return roundScore(Math.min(10, normalized10), 1); +} + +function toBoundedPositiveVndOrNull(raw: unknown): number | null { + const parsed = parseFiniteDecimalInput(raw); + if (!Number.isFinite(parsed) || parsed <= 0 || parsed > MAX_VALID_VND_PRICE) { + return null; + } + return Math.round(parsed); +} + +export function sanitizeMcpErrorMessage( + rawMessage: unknown, + fallbackMessage: string +): string { + if (typeof rawMessage !== 'string') return fallbackMessage; + const cleaned = toWellFormedString(rawMessage) + .replace(/\p{Cc}+/gu, ' ') + .replace(/\s+/g, ' ') + .trim(); + if (!cleaned || DB_INTERNAL_ERROR_REGEX.test(cleaned)) { + return fallbackMessage; + } + return cleaned.length > MAX_SAFE_PUBLIC_ERROR_LENGTH + ? `${cleaned.slice(0, MAX_SAFE_PUBLIC_ERROR_LENGTH - 3).trim()}...` + : cleaned; +} + +function formatZodIssuesForMcp(issues: readonly z.core.$ZodIssue[]): string { + const parts: string[] = []; + for (const issue of issues.slice(0, 4)) { + const rawPath = + issue.path.length > 0 + ? issue.path.map((seg) => String(seg)).join('.') + : 'arguments'; + const pathLabel = sanitizeMcpPublicText(rawPath, 64) || 'arguments'; + const msg = sanitizeMcpErrorMessage(issue.message, 'invalid value'); + parts.push(`${pathLabel}: ${msg}`); + } + const combined = + parts.length > 0 + ? `Invalid tool arguments (${parts.join('; ')})` + : 'Invalid tool arguments'; + return sanitizeMcpErrorMessage(combined, 'Invalid tool arguments'); +} + +interface McpToolCallResult { + content: Array<{ type: 'text'; text: string }>; + structuredContent: Record; + isError?: boolean; +} + +function buildToolCallResult( + payload: Record, + isError = false +): McpToolCallResult { + const sanitized = deepSanitizeWellFormed(payload); + return { + content: [{ type: 'text', text: JSON.stringify(sanitized) }], + structuredContent: sanitized, + ...(isError ? { isError: true } : {}), + }; +} + +async function executeSearchVerifiedCatalog( + rawArgs: z.infer, + readers: McpDataReaders +): Promise { + const snapshotAt = (readers.nowIso ?? DEFAULT_MCP_READERS.nowIso!)(); + const limit = Math.min(rawArgs.limit, MAX_MCP_RESULT_ITEMS); + const needsVerifiedPriceFilteringOrSorting = + rawArgs.minPriceVnd !== undefined || + rawArgs.maxPriceVnd !== undefined || + rawArgs.sort === 'price_asc' || + rawArgs.sort === 'price_desc'; + const candidateLimit = needsVerifiedPriceFilteringOrSorting + ? Math.min(MAX_SEARCH_PRICE_FILTER_CANDIDATES, Math.max(limit * 3, 24)) + : limit; + + const products = await readers.getCachedMasterProducts({ + categorySlug: rawArgs.category, + brands: rawArgs.brand ? [rawArgs.brand] : undefined, + search: rawArgs.query, + minPrice: rawArgs.minPriceVnd, + maxPrice: rawArgs.maxPriceVnd, + sort: rawArgs.sort, + limit: candidateLimit, + }); + + const boundedCandidates = products.slice(0, candidateLimit); + const offersList = await Promise.all( + boundedCandidates.map((p) => readers.getCachedMasterProductOffers(p.id)) + ); + + const computedItems = boundedCandidates.map((stored, idx) => { + const category = getMasterProductCategorySlug(stored); + const scoped = applyCategorySpecTemplate(category, stored); + const rawOffers = offersList[idx] ?? []; + const { + inStockOffers, + plausibleInStockOffers, + excludedUnavailableCount, + excludedBaitCount, + } = getPlausibleInStockMerchantOffers(rawOffers); + const plausiblePrices = plausibleInStockOffers.map((o) => + Math.round(parseFiniteDecimalInput(o.price_current)) + ); + const verifiedMinPrice = + plausiblePrices.length > 0 ? Math.min(...plausiblePrices) : null; + const verifiedMaxPrice = + plausiblePrices.length > 0 ? Math.max(...plausiblePrices) : null; + const verifiedMedianPrice = computeMedianPrice(plausiblePrices); + const href = getMasterProductHref(scoped); + const { observedAt, freshnessSource } = resolveProductObservedAt( + scoped, + snapshotAt + ); + + return { + slug: sanitizeMcpPublicText(scoped.slug, 120), + name: sanitizeMcpPublicText(scoped.name, 240), + brand: sanitizeMcpPublicText(scoped.brand, 80), + category, + verified_min_price_vnd: verifiedMinPrice, + verified_median_price_vnd: verifiedMedianPrice, + verified_max_price_vnd: verifiedMaxPrice, + in_stock_offer_count: plausibleInStockOffers.length, + excluded_unavailable_offer_count: excludedUnavailableCount, + excluded_bait_offer_count: excludedBaitCount, + sale_state: saleStateOfMaster( + scoped, + listingCountForSaleState(rawOffers.length, inStockOffers.length) + ), + bayesian_rating_5: productRatingScore5(scoped), + expert_rating_10: resolveExpertRating10(scoped), + authentic_review_count: + typeof scoped.authentic_review_count === 'number' && + Number.isFinite(scoped.authentic_review_count) && + scoped.authentic_review_count >= 0 + ? Math.trunc(scoped.authentic_review_count) + : 0, + key_specs: scoped.key_specs ?? {}, + deal_radar: radarExportFields( + computeProductRadarSignal(scoped, plausibleInStockOffers) + ), + canonical_citation_url: buildCanonicalRateUrl(href), + observed_at: observedAt, + price_observed_at: observedAt, + freshness_source: freshnessSource, + }; + }); + + const priceFiltered = computedItems.filter((item) => { + if ( + rawArgs.minPriceVnd === undefined && + rawArgs.maxPriceVnd === undefined + ) { + return true; + } + if (item.verified_min_price_vnd === null) return false; + if ( + rawArgs.minPriceVnd !== undefined && + item.verified_min_price_vnd < rawArgs.minPriceVnd + ) { + return false; + } + if ( + rawArgs.maxPriceVnd !== undefined && + item.verified_min_price_vnd > rawArgs.maxPriceVnd + ) { + return false; + } + return true; + }); + + if (rawArgs.sort === 'price_asc' || rawArgs.sort === 'price_desc') { + priceFiltered.sort((a, b) => { + if ( + a.verified_min_price_vnd === null && + b.verified_min_price_vnd === null + ) { + return 0; + } + if (a.verified_min_price_vnd === null) return 1; + if (b.verified_min_price_vnd === null) return -1; + return rawArgs.sort === 'price_asc' + ? a.verified_min_price_vnd - b.verified_min_price_vnd + : b.verified_min_price_vnd - a.verified_min_price_vnd; + }); + } + + const items = priceFiltered.slice(0, limit); + const categoryUrl = + rawArgs.category === 'all' + ? CANONICAL_RATE_ORIGIN + : buildCanonicalRateUrl(`/${rawArgs.category}`); + + return buildToolCallResult({ + ok: true, + tool: 'search_verified_catalog', + category_filter: rawArgs.category, + returned_count: items.length, + max_limit: MAX_MCP_RESULT_ITEMS, + canonical_citation_url: categoryUrl, + observed_at: snapshotAt, + items, + }); +} + +async function executeGetStoreOffersAndPriceTruth( + rawArgs: z.infer, + readers: McpDataReaders +): Promise { + const snapshotAt = (readers.nowIso ?? DEFAULT_MCP_READERS.nowIso!)(); + const limit = Math.min(rawArgs.limit, MAX_MCP_RESULT_ITEMS); + + let resolvedSlug = rawArgs.slug; + if (readers.resolveCompareTokenTarget) { + const resolved = await readers.resolveCompareTokenTarget(rawArgs.slug); + if (resolved.variantSlug) resolvedSlug = resolved.variantSlug; + } + + const storedProduct = + await readers.getCachedMasterProductBySlug(resolvedSlug); + if (!storedProduct) { + return buildToolCallResult( + { + ok: false, + error: 'Product not found in Rate.vn verified catalog', + requested_slug: rawArgs.slug, + canonical_citation_url: CANONICAL_RATE_ORIGIN, + observed_at: snapshotAt, + }, + true + ); + } + + const category = getMasterProductCategorySlug(storedProduct); + const product = applyCategorySpecTemplate(category, storedProduct); + const [rawOffers, rawReviews] = await Promise.all([ + readers.getCachedMasterProductOffers(product.id), + readers.getCachedMasterProductReviews(product.id), + ]); + const [reviewSummary, priceHistory] = await Promise.all([ + readers.getCachedMasterProductReviewSummary(product.id, rawReviews), + readers.getCachedMasterProductPriceHistory(product.id, rawOffers), + ]); + + const { + inStockOffers, + plausibleInStockOffers, + excludedUnavailableCount, + excludedBaitCount, + } = getPlausibleInStockMerchantOffers(rawOffers); + + const plausibleOfferIdSet = new Set(); + for (const offer of plausibleInStockOffers) { + if (offer.id) { + plausibleOfferIdSet.add(offer.id); + const normalized = normalizeOfferId(offer.id); + if (normalized) plausibleOfferIdSet.add(normalized); + } + } + + const latestPointIsoByOfferId = new Map(); + let latestGlobalPriceIso: string | null = null; + for (const pt of priceHistory?.points ?? []) { + // Ignore synthetic live_listing fallback points (`id < 0`) so unrecorded offers + // never overwrite real crawl timestamps with `new Date()`. + if ( + pt.source === 'live_listing' || + (typeof pt.id === 'number' && pt.id < 0) + ) { + continue; + } + const iso = resolveValidIsoTimestamp(pt.recorded_at); + if (!iso) continue; + const rawPtOfferId = typeof pt.product_id === 'string' ? pt.product_id : ''; + const normPtOfferId = normalizeOfferId(rawPtOfferId); + if (rawPtOfferId) { + const existing = latestPointIsoByOfferId.get(rawPtOfferId); + if (!existing || iso > existing) { + latestPointIsoByOfferId.set(rawPtOfferId, iso); + } + } + if (normPtOfferId && normPtOfferId !== rawPtOfferId) { + const existingNorm = latestPointIsoByOfferId.get(normPtOfferId); + if (!existingNorm || iso > existingNorm) { + latestPointIsoByOfferId.set(normPtOfferId, iso); + } + } + if ( + (rawPtOfferId && plausibleOfferIdSet.has(rawPtOfferId)) || + (normPtOfferId && plausibleOfferIdSet.has(normPtOfferId)) + ) { + if (!latestGlobalPriceIso || iso > latestGlobalPriceIso) { + latestGlobalPriceIso = iso; + } + } + } + + const { observedAt: productObservedAt, freshnessSource } = + resolveProductObservedAt(product, snapshotAt); + const productPriceObservedAt = latestGlobalPriceIso ?? productObservedAt; + + const allPlausiblePrices = plausibleInStockOffers.map((o) => + Math.round(parseFiniteDecimalInput(o.price_current)) + ); + const verifiedMinPrice = + allPlausiblePrices.length > 0 ? Math.min(...allPlausiblePrices) : null; + const verifiedMaxPrice = + allPlausiblePrices.length > 0 ? Math.max(...allPlausiblePrices) : null; + const verifiedMedianPrice = computeMedianPrice(allPlausiblePrices); + + const filteredOffers = plausibleInStockOffers + .filter((o) => { + if (rawArgs.officialOnly && !o.merchant?.is_official) return false; + if ( + rawArgs.platform !== 'all' && + String(o.merchant?.platform || o.platform || '').toLowerCase() !== + rawArgs.platform + ) { + return false; + } + return true; + }) + .sort((a, b) => { + const priceDiff = + parseFiniteDecimalInput(a.price_current) - + parseFiniteDecimalInput(b.price_current); + if (priceDiff !== 0) return priceDiff; + return ( + (b.merchant?.is_official ? 1 : 0) - (a.merchant?.is_official ? 1 : 0) + ); + }) + .slice(0, limit); + + const productHref = getMasterProductHref(product); + const productCitationUrl = buildCanonicalRateUrl(productHref); + + const offers = filteredOffers.map((rawOffer) => { + const publicOffer = withPublicOfferReviewRisk(rawOffer); + const currentPrice = Math.round( + parseFiniteDecimalInput(publicOffer.price_current) + ); + const rawOrig = parseFiniteDecimalInput(publicOffer.price_original); + const normalizedOrig = normalizeOfferOriginalPrice( + currentPrice, + Number.isFinite(rawOrig) ? rawOrig : 0 + ); + const normOfferId = normalizeOfferId(publicOffer.id); + const offerAnalysis = + priceHistory?.byOffer && + Object.hasOwn(priceHistory.byOffer, publicOffer.id) + ? priceHistory.byOffer[publicOffer.id] + : normOfferId && + priceHistory?.byOffer && + Object.hasOwn(priceHistory.byOffer, normOfferId) + ? priceHistory.byOffer[normOfferId] + : null; + const offerObservedAt = + latestPointIsoByOfferId.get(publicOffer.id) ?? + (normOfferId ? latestPointIsoByOfferId.get(normOfferId) : undefined) ?? + productPriceObservedAt; + const platformSlug = sanitizeMcpPublicText( + publicOffer.merchant?.platform || publicOffer.platform || 'shopee', + 32 + ).toLowerCase(); + + return { + id: sanitizeMcpPublicText(publicOffer.id, 128), + platform: platformSlug, + title: sanitizeMcpPublicText(publicOffer.title, 280), + price_current_vnd: currentPrice, + price_original_vnd: normalizedOrig, + discount_verdict: offerAnalysis?.verdict ?? null, + historical_median_price_vnd: + offerAnalysis?.historical_median_price ?? verifiedMedianPrice, + merchant: { + id: sanitizeMcpPublicText(publicOffer.merchant?.id, 128), + name: sanitizeMcpPublicText(publicOffer.merchant?.name, 160), + is_official_mall: Boolean(publicOffer.merchant?.is_official), + risk_score: publicOffer.merchant?.risk_score ?? null, + dosafe_risk_score: publicOffer.merchant?.dosafe_risk_score ?? null, + review_risk_score: publicOffer.merchant?.review_risk_score ?? null, + }, + offer_url: sanitizeExternalOfferUrl(publicOffer.url), + canonical_citation_url: `${productCitationUrl}#offers-table`, + price_observed_at: offerObservedAt, + observed_at: offerObservedAt, + }; + }); + + return buildToolCallResult({ + ok: true, + tool: 'get_22_store_offers_and_price_truth', + canonical_citation_url: productCitationUrl, + observed_at: productObservedAt, + price_observed_at: productPriceObservedAt, + freshness_source: latestGlobalPriceIso ? 'price_history' : freshnessSource, + product: { + slug: sanitizeMcpPublicText(product.slug, 120), + name: sanitizeMcpPublicText(product.name, 240), + brand: sanitizeMcpPublicText(product.brand, 80), + category, + sale_state: saleStateOfMaster( + product, + listingCountForSaleState(rawOffers.length, inStockOffers.length) + ), + bayesian_rating_5: productRatingScore5(product), + expert_rating_10: resolveExpertRating10(product), + authentic_review_count: + typeof product.authentic_review_count === 'number' && + Number.isFinite(product.authentic_review_count) && + product.authentic_review_count >= 0 + ? Math.trunc(product.authentic_review_count) + : 0, + key_specs: product.key_specs ?? {}, + canonical_citation_url: productCitationUrl, + observed_at: productObservedAt, + }, + price_truth: { + verified_min_price_vnd: verifiedMinPrice, + verified_median_price_vnd: verifiedMedianPrice, + verified_max_price_vnd: verifiedMaxPrice, + lowest_ever_price_vnd: priceHistory?.lowestEverPrice ?? null, + lowest_ever_date: priceHistory?.lowestEverDate ?? null, + highest_ever_price_vnd: priceHistory?.highestEverPrice ?? null, + fake_discount_offer_count: priceHistory?.fakeDiscountCount ?? 0, + genuine_deal_offer_count: priceHistory?.genuineDealCount ?? 0, + total_plausible_in_stock_offers: plausibleInStockOffers.length, + excluded_unavailable_offer_count: excludedUnavailableCount, + excluded_bait_offer_count: excludedBaitCount, + deal_radar: radarExportFields( + computeProductRadarSignal(product, plausibleInStockOffers) + ), + }, + review_trust_summary: { + trust_model: 'review_trust_v2_6_axis', + total_analyzed: reviewSummary?.total_analyzed ?? 0, + authentic_pct: reviewSummary?.authentic_pct ?? 0, + suspicious_pct: reviewSummary?.suspicious_pct ?? 0, + fake_pct: reviewSummary?.fake_pct ?? 0, + pros: (reviewSummary?.pros ?? []) + .slice(0, 6) + .map((s) => sanitizeMcpPublicText(s, 200)), + cons: (reviewSummary?.cons ?? []) + .slice(0, 6) + .map((s) => sanitizeMcpPublicText(s, 200)), + ai_summary: reviewSummary?.ai_summary + ? sanitizeMcpPublicText(reviewSummary.ai_summary, 500) + : null, + }, + returned_offer_count: offers.length, + offers, + }); +} + +async function executeCompareDevicesByUseCase( + rawArgs: z.infer, + readers: McpDataReaders +): Promise { + const snapshotAt = (readers.nowIso ?? DEFAULT_MCP_READERS.nowIso!)(); + const resolveToken = + readers.resolveCompareTokenTarget ?? defaultResolveCompareTokenTarget; + + const rawResolved = await Promise.all( + rawArgs.slugs.map(async (requested) => { + const target = await resolveToken(requested); + return { requested, target }; + }) + ); + + const seenItems = new Set(); + const seenVariantSlugs = new Set(); + const resolvedEntries = rawResolved.map(({ requested, target }) => { + if (!target.variantSlug) { + return { + requested, + variantSlug: null as string | null, + deduplicated: false, + }; + } + const lowerVariantSlug = target.variantSlug.toLowerCase(); + if ( + seenVariantSlugs.has(lowerVariantSlug) || + (target.itemId !== null && seenItems.has(target.itemId)) + ) { + return { + requested, + variantSlug: target.variantSlug, + deduplicated: true, + }; + } + seenVariantSlugs.add(lowerVariantSlug); + if (target.itemId !== null) seenItems.add(target.itemId); + return { + requested, + variantSlug: target.variantSlug, + deduplicated: false, + }; + }); + + const deduplicatedSlugs = resolvedEntries + .filter((entry) => entry.deduplicated) + .map((entry) => entry.requested); + const comparedSlugs = resolvedEntries + .filter( + ( + entry + ): entry is { + requested: string; + variantSlug: string; + deduplicated: false; + } => !entry.deduplicated && entry.variantSlug !== null + ) + .map((entry) => entry.variantSlug); + + const [comparedProducts, filteredReviewCounts] = await Promise.all([ + comparedSlugs.length >= 2 + ? readers.getCachedCompareMasterProducts(comparedSlugs.join(',')) + : comparedSlugs.length === 1 + ? readers + .getCachedMasterProductBySlug(comparedSlugs[0]!) + .then((p) => (p ? [p] : [])) + : Promise.resolve([]), + readers + .getCachedFilteredReviewCountsByMaster() + .catch(() => ({}) as FilteredReviewCountsByMaster), + ]); + + const returnedSlugSet = new Set( + comparedProducts.map((p) => p.slug.toLowerCase()) + ); + const missingEntries = resolvedEntries.filter( + (entry) => + !entry.deduplicated && + (entry.variantSlug === null || + !returnedSlugSet.has(entry.variantSlug.toLowerCase())) + ); + const missingLookup = await Promise.all( + missingEntries.map((entry) => + entry.variantSlug === null + ? Promise.resolve(false) + : readers.getCachedMasterProductBySlug(entry.variantSlug).then( + (p) => p !== null, + () => false + ) + ) + ); + const excludedCrossCategorySlugs = missingEntries + .filter((_, idx) => missingLookup[idx]) + .map((entry) => entry.requested); + const notFoundSlugs = missingEntries + .filter((_, idx) => !missingLookup[idx]) + .map((entry) => entry.requested); + + if (comparedProducts.length < 2) { + return buildToolCallResult( + { + ok: false, + error: + 'At least 2 distinct published products in the same device category are required for side-by-side comparison.', + requested_slugs: rawArgs.slugs, + deduplicated_slugs: deduplicatedSlugs, + excluded_cross_category_slugs: excludedCrossCategorySlugs, + not_found_slugs: notFoundSlugs, + canonical_citation_url: buildCanonicalRateUrl('/compare'), + observed_at: snapshotAt, + }, + true + ); + } + + const lockedCategory = getMasterProductCategorySlug(comparedProducts[0]!); + const presetWeights = PERSONA_WEIGHT_PRESETS[rawArgs.persona]; + const rawMergedWeights: LeaderboardCriteriaWeights = { + screen: rawArgs.weights?.screen ?? presetWeights.screen, + performance: rawArgs.weights?.performance ?? presetWeights.performance, + camera: rawArgs.weights?.camera ?? presetWeights.camera, + battery: rawArgs.weights?.battery ?? presetWeights.battery, + value: rawArgs.weights?.value ?? presetWeights.value, + }; + const applicableCriteria = leaderboardCriteriaForCategory(lockedCategory); + + const offersList = await Promise.all( + comparedProducts.map((p) => readers.getCachedMasterProductOffers(p.id)) + ); + + const scoredEntries = comparedProducts.map((stored, idx) => { + const scoped = applyCategorySpecTemplate(lockedCategory, stored); + const scored = scoreMasterProductForLeaderboard( + scoped, + 'combined', + filteredReviewCounts + ); + return { + scoped, + scored, + rawOffers: offersList[idx] ?? [], + }; + }); + + // Only criteria where every compared model meets CRITERION_RANK_WRITERS (>= 5) participate. + let sharedCriteria: LeaderboardScoreCriterion[] = [...applicableCriteria]; + for (let i = 1; i < scoredEntries.length; i++) { + const pairShared = new Set( + sharedScoredCriteria( + scoredEntries[0]!.scored.rankCriteria, + scoredEntries[i]!.scored.rankCriteria + ) + ); + sharedCriteria = sharedCriteria.filter((c) => pairShared.has(c)); + } + + const totalSharedWeight = sharedCriteria.reduce( + (acc, key) => acc + rawMergedWeights[key], + 0 + ); + const weightsFallbackApplied = + sharedCriteria.length === 0 || totalSharedWeight <= 0; + const appliedWeightsPct = Object.fromEntries( + LEADERBOARD_SCORE_CRITERIA.map((key) => { + if (!sharedCriteria.includes(key)) return [key, 0]; + if (totalSharedWeight <= 0) { + return [key, roundScore(100 / sharedCriteria.length, 1)]; + } + return [ + key, + roundScore((rawMergedWeights[key] / totalSharedWeight) * 100, 1), + ]; + }) + ) as LeaderboardCriteriaWeights; + + const devices = scoredEntries.map(({ scoped, scored, rawOffers }) => { + const { + inStockOffers, + plausibleInStockOffers, + excludedUnavailableCount, + excludedBaitCount, + } = getPlausibleInStockMerchantOffers(rawOffers); + const plausiblePrices = plausibleInStockOffers.map((o) => + Math.round(parseFiniteDecimalInput(o.price_current)) + ); + const verifiedMinPrice = + plausiblePrices.length > 0 ? Math.min(...plausiblePrices) : null; + const verifiedMaxPrice = + plausiblePrices.length > 0 ? Math.max(...plausiblePrices) : null; + + // Blend unrounded userScore5 (or combinedScore5 when unrated by buyers) so rounding happens once (#1531 D3). + const unroundedBaseOverall5 = + scored.userScore5 > 0 + ? scored.userScore5 + : scored.combinedScore5 > 0 + ? scored.combinedScore5 + : null; + const weightedCriteria5 = + sharedCriteria.length > 0 + ? weightedCriteriaScore5( + scored.rankCriteria, + appliedWeightsPct, + sharedCriteria + ) + : null; + const useCaseScore5 = + unroundedBaseOverall5 != null && weightedCriteria5 != null + ? roundScore(unroundedBaseOverall5 * 0.35 + weightedCriteria5 * 0.65, 2) + : unroundedBaseOverall5 != null + ? roundScore(unroundedBaseOverall5, 2) + : weightedCriteria5; + const href = getMasterProductHref(scoped); + const { observedAt, freshnessSource } = resolveProductObservedAt( + scoped, + snapshotAt + ); + + return { + slug: sanitizeMcpPublicText(scoped.slug, 120), + name: sanitizeMcpPublicText(scoped.name, 240), + brand: sanitizeMcpPublicText(scoped.brand, 80), + category: lockedCategory, + verified_min_price_vnd: verifiedMinPrice, + verified_max_price_vnd: verifiedMaxPrice, + in_stock_offer_count: plausibleInStockOffers.length, + excluded_unavailable_offer_count: excludedUnavailableCount, + excluded_bait_offer_count: excludedBaitCount, + sale_state: saleStateOfMaster( + scoped, + listingCountForSaleState(rawOffers.length, inStockOffers.length) + ), + bayesian_rating_5: productRatingScore5(scoped), + expert_rating_10: scored.expertScore10, + criteria_scores_5: scored.criteria, + use_case_score_5: useCaseScore5, + use_case_score_10: + useCaseScore5 != null + ? roundScore(displayedScore5(useCaseScore5) * 2, 1) + : null, + authentic_review_count: scored.authenticReviewCount, + filtered_noise_review_count: scored.filteredNoiseReviewCount, + key_specs: scoped.key_specs ?? {}, + specifications: scoped.specifications ?? {}, + deal_radar: radarExportFields( + computeProductRadarSignal(scoped, plausibleInStockOffers) + ), + canonical_citation_url: buildCanonicalRateUrl(href), + observed_at: observedAt, + price_observed_at: observedAt, + freshness_source: freshnessSource, + }; + }); + + const scoredDevicesOnly = devices.filter((d) => d.use_case_score_5 !== null); + const rankedByUseCase = [...scoredDevicesOnly].sort((a, b) => { + const scoreA = a.use_case_score_5 ?? -1; + const scoreB = b.use_case_score_5 ?? -1; + if (scoreB !== scoreA) return scoreB - scoreA; + const priceA = a.verified_min_price_vnd ?? Number.MAX_SAFE_INTEGER; + const priceB = b.verified_min_price_vnd ?? Number.MAX_SAFE_INTEGER; + return priceA - priceB; + }); + + const compareSlugsParam = devices + .map((d) => encodeURIComponent(d.slug)) + .join(','); + const compareCitationUrl = buildCanonicalRateUrl( + `/compare?cat=${lockedCategory}&slugs=${compareSlugsParam}` + ); + + return buildToolCallResult({ + ok: true, + tool: 'compare_devices_by_use_case', + locked_category: lockedCategory, + persona: rawArgs.persona, + applied_weights_pct: appliedWeightsPct, + weights_fallback_applied: weightsFallbackApplied, + compared_criteria: sharedCriteria, + recommended_slug_for_use_case: rankedByUseCase[0]?.slug ?? null, + deduplicated_slugs: deduplicatedSlugs, + excluded_cross_category_slugs: excludedCrossCategorySlugs, + not_found_slugs: notFoundSlugs, + canonical_citation_url: compareCitationUrl, + observed_at: snapshotAt, + devices, + }); +} + +async function executeAuditListingUrl( + rawArgs: z.infer, + readers: McpDataReaders +): Promise { + const snapshotAt = (readers.nowIso ?? DEFAULT_MCP_READERS.nowIso!)(); + // Canonicalize tracking query params / fragments BEFORE cache lookup so + // affiliate parameters (?sp_atk=, ?utm_*, ?fbclid=) never bypass withRateDataCache. + const canonicalListingUrl = canonicalizeProductUrl(rawArgs.url); + const lookupTarget = canonicalListingUrl || rawArgs.url; + const inspection = + await readers.getCachedInspectProductOrShopUrl(lookupTarget); + + const masterProduct = inspection.masterProduct + ? applyCategorySpecTemplate( + getMasterProductCategorySlug(inspection.masterProduct), + inspection.masterProduct + ) + : null; + const queryPrice = rawArgs.observedPriceVnd ?? null; + const queryOriginalPrice = rawArgs.observedOriginalPriceVnd ?? null; + + const { observedPrice, observedOriginalPrice } = resolveInspectObservedPrices( + { + queryPrice, + queryOriginalPrice, + matchedOfferPriceCurrent: inspection.matchedOffer?.price_current, + matchedOfferPriceOriginal: inspection.matchedOffer?.price_original, + masterMinPrice: masterProduct?.min_price, + maxVnd: MAX_VALID_VND_PRICE, + } + ); + + const gatekeeper = detectAccessoryOrJunk({ + title: + inspection.matchedOffer?.title || masterProduct?.name || lookupTarget, + url: lookupTarget, + price: observedPrice > 0 ? observedPrice : null, + }); + + const rawMatchedPrice = parseFiniteDecimalInput( + inspection.matchedOffer?.price_current + ); + const matchedOfferHasPositivePrice = + Number.isFinite(rawMatchedPrice) && + rawMatchedPrice > 0 && + rawMatchedPrice <= MAX_VALID_VND_PRICE; + + const priceVerdict = evaluateExtensionPriceVerdict({ + isAccessory: gatekeeper.isAccessory, + accessoryReason: gatekeeper.reason, + accessoryMessage: gatekeeper.message, + isAmbiguousVariant: false, + observedPrice: observedPrice > 0 ? observedPrice : null, + observedOriginalPrice: + observedOriginalPrice > 0 ? observedOriginalPrice : null, + offers: inspection.allOffers, + observedOfferId: + inspection.matchedType === 'product_listing' || + (queryPrice === null && matchedOfferHasPositivePrice) + ? (inspection.matchedOffer?.id ?? null) + : null, + hasLiveObservedPrice: typeof queryPrice === 'number' && queryPrice > 0, + priceHistory: inspection.priceHistory, + }); + + const { + plausibleInStockOffers, + excludedUnavailableCount, + excludedBaitCount, + } = getPlausibleInStockMerchantOffers(inspection.allOffers ?? []); + const radarSignal = masterProduct + ? radarExportFields( + computeProductRadarSignal(masterProduct, plausibleInStockOffers) + ) + : null; + + const inspectCitationUrl = buildCanonicalRateUrl( + `/inspect?q=${encodeURIComponent(lookupTarget)}` + ); + const primaryCitationUrl = masterProduct + ? buildCanonicalRateUrl(getMasterProductHref(masterProduct)) + : buildSafeMerchantCitationUrl( + inspection.merchantProfile?.id, + inspectCitationUrl + ); + + const { observedAt: productObservedAt } = resolveProductObservedAt( + masterProduct, + snapshotAt + ); + + const matchedOfferPublic = inspection.matchedOffer + ? withPublicOfferReviewRisk(inspection.matchedOffer) + : null; + const merchantProfilePublic = inspection.merchantProfile + ? withPublicReviewRisk(inspection.merchantProfile) + : null; + + const matchedOfferPriceCurrent = matchedOfferPublic + ? toBoundedPositiveVndOrNull(matchedOfferPublic.price_current) + : null; + const rawMatchedOfferOrig = matchedOfferPublic + ? parseFiniteDecimalInput(matchedOfferPublic.price_original) + : Number.NaN; + const matchedOfferPriceOriginal = + matchedOfferPriceCurrent !== null + ? normalizeOfferOriginalPrice( + matchedOfferPriceCurrent, + Number.isFinite(rawMatchedOfferOrig) ? rawMatchedOfferOrig : 0 + ) + : null; + + const topCompetingOffers = [...plausibleInStockOffers] + .sort( + (a, b) => + parseFiniteDecimalInput(a.price_current) - + parseFiniteDecimalInput(b.price_current) + ) + .slice(0, 5) + .map((offer) => { + const pub = withPublicOfferReviewRisk(offer); + return { + id: sanitizeMcpPublicText(pub.id, 128), + platform: sanitizeMcpPublicText( + pub.merchant?.platform || pub.platform || 'shopee', + 32 + ).toLowerCase(), + title: sanitizeMcpPublicText(pub.title, 240), + price_current_vnd: Math.round( + parseFiniteDecimalInput(pub.price_current) + ), + merchant_name: sanitizeMcpPublicText(pub.merchant?.name, 160), + is_official_mall: Boolean(pub.merchant?.is_official), + merchant_risk_score: pub.merchant?.risk_score ?? null, + dosafe_risk_score: pub.merchant?.dosafe_risk_score ?? null, + review_risk_score: pub.merchant?.review_risk_score ?? null, + offer_url: sanitizeExternalOfferUrl(pub.url), + canonical_citation_url: primaryCitationUrl, + observed_at: productObservedAt, + price_observed_at: productObservedAt, + }; + }); + + const suggestions = (inspection.suggestions ?? []).slice(0, 5).map((s) => { + const cat = getMasterProductCategorySlug(s); + const scoped = applyCategorySpecTemplate(cat, s); + const { observedAt } = resolveProductObservedAt(scoped, snapshotAt); + return { + slug: sanitizeMcpPublicText(scoped.slug, 120), + name: sanitizeMcpPublicText(scoped.name, 240), + brand: sanitizeMcpPublicText(scoped.brand, 80), + category: cat, + canonical_citation_url: buildCanonicalRateUrl( + getMasterProductHref(scoped) + ), + observed_at: observedAt, + }; + }); + + return buildToolCallResult({ + ok: true, + tool: 'audit_listing_url', + matched_type: inspection.matchedType, + detected_platform: inspection.parsedUrl?.platform ?? null, + canonical_listing_url: canonicalListingUrl, + canonical_citation_url: primaryCitationUrl, + inspect_citation_url: inspectCitationUrl, + observed_at: productObservedAt, + price_observed_at: productObservedAt, + gatekeeper: { + is_accessory_or_part: gatekeeper.isAccessory, + reason: gatekeeper.reason ?? null, + }, + price_verdict: priceVerdict, + deal_radar: radarSignal, + matched_product: masterProduct + ? { + slug: sanitizeMcpPublicText(masterProduct.slug, 120), + name: sanitizeMcpPublicText(masterProduct.name, 240), + brand: sanitizeMcpPublicText(masterProduct.brand, 80), + category: getMasterProductCategorySlug(masterProduct), + bayesian_rating_5: productRatingScore5(masterProduct), + expert_rating_10: resolveExpertRating10(masterProduct), + canonical_citation_url: buildCanonicalRateUrl( + getMasterProductHref(masterProduct) + ), + observed_at: productObservedAt, + } + : null, + matched_offer: matchedOfferPublic + ? { + id: sanitizeMcpPublicText(matchedOfferPublic.id, 128), + platform: sanitizeMcpPublicText( + matchedOfferPublic.platform, + 32 + ).toLowerCase(), + title: sanitizeMcpPublicText(matchedOfferPublic.title, 280), + price_current_vnd: matchedOfferPriceCurrent, + price_original_vnd: matchedOfferPriceOriginal, + availability: matchedOfferPublic.availability ?? null, + is_unavailable: isOfferUnavailable(matchedOfferPublic), + canonical_citation_url: primaryCitationUrl, + price_observed_at: productObservedAt, + observed_at: productObservedAt, + } + : null, + merchant_risk_summary: merchantProfilePublic + ? { + id: sanitizeMcpPublicText(merchantProfilePublic.id, 128), + name: sanitizeMcpPublicText(merchantProfilePublic.name, 160), + platform: sanitizeMcpPublicText( + merchantProfilePublic.platform, + 32 + ).toLowerCase(), + is_official_mall: Boolean(merchantProfilePublic.is_official), + risk_score: merchantProfilePublic.risk_score ?? null, + dosafe_risk_score: merchantProfilePublic.dosafe_risk_score ?? null, + review_risk_score: merchantProfilePublic.review_risk_score ?? null, + canonical_citation_url: buildSafeMerchantCitationUrl( + merchantProfilePublic.id, + inspectCitationUrl + ), + observed_at: snapshotAt, + } + : matchedOfferPublic?.merchant + ? { + id: sanitizeMcpPublicText(matchedOfferPublic.merchant.id, 128), + name: sanitizeMcpPublicText(matchedOfferPublic.merchant.name, 160), + platform: sanitizeMcpPublicText( + matchedOfferPublic.merchant.platform, + 32 + ).toLowerCase(), + is_official_mall: Boolean(matchedOfferPublic.merchant.is_official), + risk_score: matchedOfferPublic.merchant.risk_score ?? null, + dosafe_risk_score: + matchedOfferPublic.merchant.dosafe_risk_score ?? null, + review_risk_score: + matchedOfferPublic.merchant.review_risk_score ?? null, + canonical_citation_url: buildSafeMerchantCitationUrl( + matchedOfferPublic.merchant.id, + inspectCitationUrl + ), + observed_at: snapshotAt, + } + : null, + excluded_unavailable_offer_count: excludedUnavailableCount, + excluded_bait_offer_count: excludedBaitCount, + top_competing_offers: topCompetingOffers, + suggestions, + }); +} + +async function executeGetGenuineDeals( + rawArgs: z.infer, + readers: McpDataReaders +): Promise { + const snapshotAt = (readers.nowIso ?? DEFAULT_MCP_READERS.nowIso!)(); + const limit = Math.min(rawArgs.limit, MAX_MCP_RESULT_ITEMS); + + const radar = await readers.getCrossPlatformDealRadar({ + categorySlug: rawArgs.category, + platform: rawArgs.platform, + limit: 30, + }); + + const radarObservedAt = + resolveValidIsoTimestamp(radar.generatedAt) ?? snapshotAt; + + const filteredDeals = (radar.genuineDeals ?? []) + .filter((deal) => { + if (rawArgs.officialOnly && !deal.isOfficialMall) return false; + if ( + rawArgs.maxBudgetVnd !== undefined && + deal.priceCurrent > rawArgs.maxBudgetVnd + ) { + return false; + } + return true; + }) + .slice(0, limit) + .map((deal) => ({ + id: sanitizeMcpPublicText(deal.id, 128), + verdict: deal.verdict, + product_slug: sanitizeMcpPublicText(deal.productSlug, 120), + product_name: sanitizeMcpPublicText(deal.productName, 240), + brand: sanitizeMcpPublicText(deal.brand, 80), + category: deal.categorySlug, + platform: sanitizeMcpPublicText(deal.platform, 32).toLowerCase(), + merchant_id: sanitizeMcpPublicText(deal.merchantId, 128), + merchant_name: sanitizeMcpPublicText(deal.merchantName, 160), + is_official_mall: Boolean(deal.isOfficialMall), + merchant_risk_score: deal.merchantRiskScore, + price_current_vnd: deal.priceCurrent, + price_original_vnd: deal.priceOriginal, + market_median_price_vnd: deal.marketMedianPrice, + market_min_price_vnd: deal.marketMinPrice, + market_max_price_vnd: deal.marketMaxPrice, + savings_vs_median_vnd: deal.savingsVsMedianVnd, + savings_vs_median_pct: deal.savingsVsMedianPct, + market_offer_count: deal.marketOfferCount, + jreviews_score_10: deal.jreviewsScore10, + offer_url: sanitizeExternalOfferUrl(deal.offerUrl), + canonical_citation_url: buildCanonicalRateUrl(deal.productHref), + price_observed_at: radarObservedAt, + observed_at: radarObservedAt, + })); + + return buildToolCallResult({ + ok: true, + tool: 'get_genuine_deals', + category_filter: rawArgs.category, + platform_filter: rawArgs.platform, + total_clusters_analyzed: radar.totalClustersAnalyzed, + total_offers_analyzed: radar.totalOffersAnalyzed, + total_merchants_analyzed: radar.totalMerchantsAnalyzed, + returned_count: filteredDeals.length, + max_limit: MAX_MCP_RESULT_ITEMS, + canonical_citation_url: buildCanonicalRateUrl('/deals'), + observed_at: radarObservedAt, + price_observed_at: radarObservedAt, + deals: filteredDeals, + }); +} + +class JsonPayloadGuardError extends Error { + public readonly rpcCode: number; + constructor(rpcCode: number, message: string) { + super(message); + this.name = 'JsonPayloadGuardError'; + this.rpcCode = rpcCode; + } +} + +function hasUnsafeNumericRpcIdToken(rawJsonText: string): boolean { + // Detect unquoted top-level numeric `"id": ` tokens that are fractional, + // exponential, or outside IEEE-754 safe integer precision BEFORE JSON.parse rounds them. + const idMatch = rawJsonText.match( + /"id"\s*:\s*(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/ + ); + if (!idMatch) return false; + const literal = idMatch[1]!; + if (/[.eE]/.test(literal)) return true; + try { + const asBigInt = BigInt(literal); + return ( + asBigInt > BigInt(Number.MAX_SAFE_INTEGER) || + asBigInt < BigInt(Number.MIN_SAFE_INTEGER) + ); + } catch { + return true; + } +} + +function sanitizeJsonValueOrThrow(value: unknown, depth = 0): unknown { + if (depth > MAX_JSON_NESTING_DEPTH) { + throw new JsonPayloadGuardError( + -32600, + `Invalid Request: JSON nesting depth exceeds ${MAX_JSON_NESTING_DEPTH}` + ); + } + if (typeof value === 'string') { + return toWellFormedString(value); + } + if ( + value === null || + typeof value === 'number' || + typeof value === 'boolean' + ) { + return value; + } + if (Array.isArray(value)) { + if (value.length > MAX_JSON_ARRAY_ITEMS) { + throw new JsonPayloadGuardError( + -32600, + `Invalid Request: JSON array exceeds ${MAX_JSON_ARRAY_ITEMS} elements` + ); + } + return value.map((item) => sanitizeJsonValueOrThrow(item, depth + 1)); + } + if (typeof value === 'object') { + const ownKeys = Object.getOwnPropertyNames(value); + if (ownKeys.length > MAX_JSON_OBJECT_KEYS) { + throw new JsonPayloadGuardError( + -32600, + `Invalid Request: JSON object exceeds ${MAX_JSON_OBJECT_KEYS} keys` + ); + } + const out: Record = {}; + for (const rawKey of ownKeys) { + if (FORBIDDEN_OBJECT_KEYS.has(rawKey)) { + throw new JsonPayloadGuardError( + -32600, + `Invalid Request: forbidden prototype key "${rawKey}"` + ); + } + const cleanKey = toWellFormedString(rawKey); + if (FORBIDDEN_OBJECT_KEYS.has(cleanKey)) { + throw new JsonPayloadGuardError( + -32600, + `Invalid Request: forbidden prototype key "${cleanKey}"` + ); + } + const rawVal = (value as Record)[rawKey]; + out[cleanKey] = sanitizeJsonValueOrThrow(rawVal, depth + 1); + } + return out; + } + return null; +} + +type ReadMcpBodyOutcome = + | { kind: 'too_large' } + | { kind: 'invalid_content_length' } + | { kind: 'parse_error'; message: string } + | { kind: 'guard_error'; rpcCode: number; message: string } + | { kind: 'ok'; value: unknown; unsafeNumericId: boolean }; + +async function readBoundedMcpJsonBody( + request: Request, + maxBytes = MAX_MCP_BODY_BYTES +): Promise { + const rawContentLength = request.headers.get('content-length'); + if (rawContentLength !== null) { + const trimmed = rawContentLength.trim(); + if (!/^\d+$/.test(trimmed)) { + return { kind: 'invalid_content_length' }; + } + const declared = Number(trimmed); + if (!Number.isSafeInteger(declared)) { + return { kind: 'invalid_content_length' }; + } + if (declared > maxBytes) { + return { kind: 'too_large' }; + } + } + + if (!request.body) { + return { kind: 'parse_error', message: 'Parse error: empty request body' }; + } + + let reader: ReadableStreamDefaultReader; + try { + reader = request.body.getReader(); + } catch { + return { + kind: 'parse_error', + message: 'Parse error: unreadable request body stream', + }; + } + + const chunks: Uint8Array[] = []; + let size = 0; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > maxBytes) { + await reader.cancel().catch(() => undefined); + return { kind: 'too_large' }; + } + chunks.push(value); + } + } catch { + await reader.cancel().catch(() => undefined); + return { + kind: 'parse_error', + message: 'Parse error: unreadable or aborted request body', + }; + } + + if (size === 0) { + return { kind: 'parse_error', message: 'Parse error: empty request body' }; + } + + const bytes = new Uint8Array(size); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + + let decodedText: string; + try { + decodedText = new TextDecoder('utf-8', { + fatal: true, + ignoreBOM: true, + }).decode(bytes); + } catch { + return { + kind: 'parse_error', + message: 'Parse error: request body must be valid UTF-8 JSON', + }; + } + + let rawParsed: unknown; + try { + rawParsed = JSON.parse(decodedText); + } catch { + return { kind: 'parse_error', message: 'Parse error: malformed JSON body' }; + } + + if (Array.isArray(rawParsed)) { + return { + kind: 'guard_error', + rpcCode: -32600, + message: + 'Invalid Request: JSON-RPC batch arrays are not supported on this stateless MCP endpoint; send one JSON-RPC 2.0 object per POST.', + }; + } + + try { + const cleanValue = sanitizeJsonValueOrThrow(rawParsed, 0); + return { + kind: 'ok', + value: cleanValue, + unsafeNumericId: hasUnsafeNumericRpcIdToken(decodedText), + }; + } catch (err) { + if (err instanceof JsonPayloadGuardError) { + return { + kind: 'guard_error', + rpcCode: err.rpcCode, + message: err.message, + }; + } + return { + kind: 'parse_error', + message: 'Parse error: invalid JSON payload', + }; + } +} + +function mcpResponseHeaders( + protocolVersion: string = MCP_LATEST_PROTOCOL_VERSION, + extra?: Record +): Record { + return { + ...MCP_CORS_HEADERS, + 'Cache-Control': 'no-store', + 'MCP-Protocol-Version': protocolVersion, + ...extra, + }; +} + +function jsonRpcErrorResponse( + httpStatus: number, + id: string | number | null, + code: number, + message: string, + data?: Record, + extraHeaders?: Record, + protocolVersion: string = MCP_LATEST_PROTOCOL_VERSION +): NextResponse { + return NextResponse.json( + { + jsonrpc: '2.0', + id, + error: { + code, + message: sanitizeMcpErrorMessage(message, 'MCP request error'), + ...(data ? { data: deepSanitizeWellFormed(data) } : {}), + }, + }, + { + status: httpStatus, + headers: mcpResponseHeaders(protocolVersion, extraHeaders), + } + ); +} + +function jsonRpcResultResponse( + id: string | number, + result: Record, + protocolVersion: string = MCP_LATEST_PROTOCOL_VERSION +): NextResponse { + return NextResponse.json( + { + jsonrpc: '2.0', + id, + result: deepSanitizeWellFormed(result), + }, + { + status: 200, + headers: mcpResponseHeaders(protocolVersion), + } + ); +} + +function isValidJsonContentType(rawHeader: string | null): boolean { + if (typeof rawHeader !== 'string') return false; + const parts = rawHeader.split(';').map((s) => s.trim()); + const mediaType = (parts[0] ?? '').toLowerCase(); + if (mediaType !== 'application/json') return false; + for (const param of parts.slice(1)) { + const eqIdx = param.indexOf('='); + if (eqIdx === -1) continue; + const k = param.slice(0, eqIdx).trim().toLowerCase(); + const v = param + .slice(eqIdx + 1) + .trim() + .replace(/^"|"$/g, '') + .toLowerCase(); + if (k === 'charset' && v !== 'utf-8' && v !== 'utf8') { + return false; + } + } + return true; +} + +function acceptsJsonResponse(acceptHeader: string | null): boolean { + if (acceptHeader === null || !acceptHeader.trim()) return true; + for (const entry of acceptHeader.split(',')) { + const segments = entry.split(';').map((s) => s.trim()); + const mediaRange = (segments[0] ?? '').toLowerCase(); + if ( + mediaRange !== 'application/json' && + mediaRange !== 'application/*' && + mediaRange !== '*/*' + ) { + continue; + } + let qZero = false; + for (const param of segments.slice(1)) { + const eqIdx = param.indexOf('='); + if (eqIdx === -1) continue; + const k = param.slice(0, eqIdx).trim().toLowerCase(); + const v = param.slice(eqIdx + 1).trim(); + if (k === 'q' && /^0(?:\.0{1,3})?$/.test(v)) { + qZero = true; + break; + } + } + if (!qZero) return true; + } + return false; +} + +function isPlainRecord(value: unknown): value is Record { + return Boolean(value && typeof value === 'object' && !Array.isArray(value)); +} + +function extractValidRpcId( + rawId: unknown, + unsafeNumericId = false +): { + valid: boolean; + id: string | number | null; +} { + if (typeof rawId === 'string') { + if ( + rawId.length >= 1 && + rawId.length <= MAX_RPC_ID_LENGTH && + !/\p{Cc}/u.test(rawId) + ) { + return { valid: true, id: rawId }; + } + return { valid: false, id: null }; + } + if (typeof rawId === 'number') { + if (!unsafeNumericId && Number.isSafeInteger(rawId)) { + return { valid: true, id: Object.is(rawId, -0) ? 0 : rawId }; + } + return { valid: false, id: null }; + } + return { valid: false, id: null }; +} + +const InitializeParamsSchema = z + .object({ + protocolVersion: z.string().trim().min(1).max(64).optional(), + capabilities: z.record(z.string(), z.unknown()).optional(), + clientInfo: z + .object({ + name: z.string().max(128).optional(), + version: z.string().max(64).optional(), + }) + .optional(), + }) + .passthrough(); + +export interface HandleMcpRequestOptions { + readers?: Partial; + rateLimiter?: BoundedSlidingWindowRateLimiter; + auditUrlRateLimiter?: BoundedSlidingWindowRateLimiter; +} + +export function buildMcpMethodNotAllowedResponse(): NextResponse { + return jsonRpcErrorResponse( + 405, + null, + -32600, + 'Method Not Allowed: /api/mcp is a stateless Streamable HTTP MCP endpoint. Send JSON-RPC 2.0 requests via POST.', + undefined, + { Allow: 'POST, OPTIONS' } + ); +} + +export function buildMcpCorsPreflightResponse(): NextResponse { + return new NextResponse(null, { + status: 204, + headers: mcpResponseHeaders(MCP_LATEST_PROTOCOL_VERSION, { + Allow: 'POST, OPTIONS', + }), + }); +} + +export async function handleMcpHttpPost( + request: Request, + options?: HandleMcpRequestOptions +): Promise { + try { + const limiter = options?.rateLimiter ?? mcpRateLimiter; + const auditLimiter = options?.auditUrlRateLimiter ?? inspectRateLimiter; + const clientKey = extractClientRateLimitKey(request.headers); + + const rawHeaderVersion = request.headers + .get('mcp-protocol-version') + ?.trim(); + if ( + rawHeaderVersion && + (rawHeaderVersion.length > 64 || /[\s\p{Cc}]/u.test(rawHeaderVersion)) + ) { + return jsonRpcErrorResponse( + 400, + null, + -32600, + 'Invalid Request: malformed MCP-Protocol-Version header' + ); + } + const headerVersionSupported = Boolean( + rawHeaderVersion && + (SUPPORTED_MCP_PROTOCOL_VERSIONS as readonly string[]).includes( + rawHeaderVersion + ) + ); + const activeProtocolVersion = headerVersionSupported + ? rawHeaderVersion! + : MCP_LATEST_PROTOCOL_VERSION; + + if (!limiter.allow(clientKey)) { + return jsonRpcErrorResponse( + 429, + null, + -32029, + `Rate limit exceeded. Maximum ${MCP_RATE_LIMIT_MAX_REQUESTS} MCP requests per minute.`, + { + code: 'RATE_LIMIT_EXCEEDED', + retryAfterSeconds: MCP_RETRY_AFTER_SECONDS, + }, + { 'Retry-After': String(MCP_RETRY_AFTER_SECONDS) }, + activeProtocolVersion + ); + } + + if (!isValidJsonContentType(request.headers.get('content-type'))) { + return jsonRpcErrorResponse( + 415, + null, + -32600, + 'Unsupported Media Type: Content-Type must be application/json (UTF-8)', + undefined, + undefined, + activeProtocolVersion + ); + } + + if (!acceptsJsonResponse(request.headers.get('accept'))) { + return jsonRpcErrorResponse( + 406, + null, + -32600, + 'Not Acceptable: client must accept application/json', + undefined, + undefined, + activeProtocolVersion + ); + } + + const bodyOutcome = await readBoundedMcpJsonBody( + request, + MAX_MCP_BODY_BYTES + ); + if (bodyOutcome.kind === 'too_large') { + return jsonRpcErrorResponse( + 413, + null, + -32600, + `Request body exceeds ${MAX_MCP_BODY_BYTES} bytes limit`, + { code: 'PAYLOAD_TOO_LARGE', maxBytes: MAX_MCP_BODY_BYTES }, + undefined, + activeProtocolVersion + ); + } + if (bodyOutcome.kind === 'invalid_content_length') { + return jsonRpcErrorResponse( + 400, + null, + -32600, + 'Invalid Request: malformed Content-Length header', + undefined, + undefined, + activeProtocolVersion + ); + } + if (bodyOutcome.kind === 'parse_error') { + return jsonRpcErrorResponse( + 400, + null, + -32700, + bodyOutcome.message, + undefined, + undefined, + activeProtocolVersion + ); + } + if (bodyOutcome.kind === 'guard_error') { + return jsonRpcErrorResponse( + 400, + null, + bodyOutcome.rpcCode, + bodyOutcome.message, + undefined, + undefined, + activeProtocolVersion + ); + } + + const envelope = bodyOutcome.value; + if (!isPlainRecord(envelope)) { + return jsonRpcErrorResponse( + 400, + null, + -32600, + 'Invalid Request: JSON-RPC 2.0 message must be a JSON object', + undefined, + undefined, + activeProtocolVersion + ); + } + + const jsonrpcVersion = Object.hasOwn(envelope, 'jsonrpc') + ? envelope.jsonrpc + : undefined; + const rawMethod = Object.hasOwn(envelope, 'method') + ? envelope.method + : undefined; + const hasId = Object.hasOwn(envelope, 'id'); + const rawId = hasId ? envelope.id : undefined; + const parsedId = hasId + ? extractValidRpcId(rawId, bodyOutcome.unsafeNumericId) + : { valid: false, id: null }; + + if ( + jsonrpcVersion !== '2.0' || + typeof rawMethod !== 'string' || + !rawMethod.trim() || + rawMethod.length > 128 || + /\p{Cc}/u.test(rawMethod) + ) { + return jsonRpcErrorResponse( + 400, + parsedId.valid ? parsedId.id : null, + -32600, + 'Invalid Request: expected jsonrpc "2.0" and a valid method name', + undefined, + undefined, + activeProtocolVersion + ); + } + + const method = rawMethod.trim(); + + // Enforce supported MCP-Protocol-Version header only on post-initialize calls, + // allowing newer clients sending MCP-Protocol-Version on initialize to negotiate down. + if ( + method !== 'initialize' && + rawHeaderVersion && + !headerVersionSupported + ) { + return jsonRpcErrorResponse( + 400, + parsedId.valid ? parsedId.id : null, + -32600, + `Unsupported MCP-Protocol-Version header. Supported versions: ${SUPPORTED_MCP_PROTOCOL_VERSIONS.join(', ')}` + ); + } + + const hasParams = Object.hasOwn(envelope, 'params'); + const rawParams = hasParams ? envelope.params : undefined; + + // JSON-RPC 2.0 notifications omit `id`. + if (!hasId) { + if ( + method === 'notifications/initialized' || + method.startsWith('notifications/') + ) { + if (rawParams !== undefined && !isPlainRecord(rawParams)) { + return jsonRpcErrorResponse( + 400, + null, + -32602, + 'Invalid params: notification params must be an object when provided', + undefined, + undefined, + activeProtocolVersion + ); + } + return new NextResponse(null, { + status: 202, + headers: mcpResponseHeaders(activeProtocolVersion), + }); + } + return jsonRpcErrorResponse( + 400, + null, + -32600, + 'Invalid Request: id is required for JSON-RPC request methods', + undefined, + undefined, + activeProtocolVersion + ); + } + + if (!parsedId.valid || parsedId.id === null) { + return jsonRpcErrorResponse( + 400, + null, + -32600, + 'Invalid Request: id must be a non-empty string (<= 256 chars) or safe integer', + undefined, + undefined, + activeProtocolVersion + ); + } + + const requestId = parsedId.id; + if (rawParams !== undefined && !isPlainRecord(rawParams)) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + 'Invalid params: params must be a JSON object when provided', + undefined, + undefined, + activeProtocolVersion + ); + } + + const readers: McpDataReaders = { + ...DEFAULT_MCP_READERS, + ...(options?.readers ?? {}), + }; + + if (method === 'initialize') { + const parsedInit = InitializeParamsSchema.safeParse(rawParams ?? {}); + if (!parsedInit.success) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + 'Invalid params for initialize' + ); + } + const requestedVersion = parsedInit.data.protocolVersion; + const negotiatedVersion = + requestedVersion && + (SUPPORTED_MCP_PROTOCOL_VERSIONS as readonly string[]).includes( + requestedVersion + ) + ? requestedVersion + : MCP_LATEST_PROTOCOL_VERSION; + + return jsonRpcResultResponse( + requestId, + { + protocolVersion: negotiatedVersion, + capabilities: { + tools: { + listChanged: false, + }, + }, + serverInfo: MCP_SERVER_INFO, + instructions: MCP_SERVER_INSTRUCTIONS, + }, + negotiatedVersion + ); + } + + if (method === 'notifications/initialized') { + return jsonRpcResultResponse(requestId, {}, activeProtocolVersion); + } + + if (method === 'ping') { + return jsonRpcResultResponse(requestId, {}, activeProtocolVersion); + } + + if (method === 'tools/list') { + if ( + rawParams && + Object.hasOwn(rawParams, 'cursor') && + rawParams.cursor != null + ) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + 'Invalid params: unknown pagination cursor', + undefined, + undefined, + activeProtocolVersion + ); + } + return jsonRpcResultResponse( + requestId, + { + tools: MCP_TOOL_DEFINITIONS, + }, + activeProtocolVersion + ); + } + + if (method === 'tools/call') { + if (!rawParams) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + 'Invalid params: tools/call requires params object with tool name', + undefined, + undefined, + activeProtocolVersion + ); + } + const toolName = Object.hasOwn(rawParams, 'name') + ? rawParams.name + : undefined; + const rawToolArgs = Object.hasOwn(rawParams, 'arguments') + ? rawParams.arguments + : {}; + if (typeof toolName !== 'string' || !toolName.trim()) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + 'Invalid params: tool name must be a non-empty string', + undefined, + undefined, + activeProtocolVersion + ); + } + if (rawToolArgs !== undefined && !isPlainRecord(rawToolArgs)) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + 'Invalid params: tool arguments must be a JSON object', + undefined, + undefined, + activeProtocolVersion + ); + } + const safeToolArgs = rawToolArgs ?? {}; + + try { + switch (toolName) { + case 'search_verified_catalog': { + const parsed = + SearchVerifiedCatalogInputSchema.safeParse(safeToolArgs); + if (!parsed.success) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + formatZodIssuesForMcp(parsed.error.issues), + undefined, + undefined, + activeProtocolVersion + ); + } + const result = await executeSearchVerifiedCatalog( + parsed.data, + readers + ); + return jsonRpcResultResponse( + requestId, + result as unknown as Record, + activeProtocolVersion + ); + } + + case 'get_22_store_offers_and_price_truth': { + const parsed = + GetStoreOffersAndPriceTruthInputSchema.safeParse(safeToolArgs); + if (!parsed.success) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + formatZodIssuesForMcp(parsed.error.issues), + undefined, + undefined, + activeProtocolVersion + ); + } + const result = await executeGetStoreOffersAndPriceTruth( + parsed.data, + readers + ); + return jsonRpcResultResponse( + requestId, + result as unknown as Record, + activeProtocolVersion + ); + } + + case 'compare_devices_by_use_case': { + const parsed = + CompareDevicesByUseCaseInputSchema.safeParse(safeToolArgs); + if (!parsed.success) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + formatZodIssuesForMcp(parsed.error.issues), + undefined, + undefined, + activeProtocolVersion + ); + } + const result = await executeCompareDevicesByUseCase( + parsed.data, + readers + ); + return jsonRpcResultResponse( + requestId, + result as unknown as Record, + activeProtocolVersion + ); + } + + case 'audit_listing_url': { + const parsed = AuditListingUrlInputSchema.safeParse(safeToolArgs); + if (!parsed.success) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + formatZodIssuesForMcp(parsed.error.issues), + undefined, + undefined, + activeProtocolVersion + ); + } + if (!auditLimiter.allow(clientKey)) { + return jsonRpcErrorResponse( + 429, + requestId, + -32029, + 'Rate limit exceeded. Maximum 30 listing URL audits per minute.', + { + code: 'RATE_LIMIT_EXCEEDED', + retryAfterSeconds: MCP_RETRY_AFTER_SECONDS, + }, + { 'Retry-After': String(MCP_RETRY_AFTER_SECONDS) }, + activeProtocolVersion + ); + } + const result = await executeAuditListingUrl(parsed.data, readers); + return jsonRpcResultResponse( + requestId, + result as unknown as Record, + activeProtocolVersion + ); + } + + case 'get_genuine_deals': { + const parsed = GetGenuineDealsInputSchema.safeParse(safeToolArgs); + if (!parsed.success) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + formatZodIssuesForMcp(parsed.error.issues), + undefined, + undefined, + activeProtocolVersion + ); + } + const result = await executeGetGenuineDeals(parsed.data, readers); + return jsonRpcResultResponse( + requestId, + result as unknown as Record, + activeProtocolVersion + ); + } + + default: + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + `Unknown MCP tool: ${sanitizeMcpPublicText(toolName, 80)}`, + undefined, + undefined, + activeProtocolVersion + ); + } + } catch { + const snapshotAt = (readers.nowIso ?? DEFAULT_MCP_READERS.nowIso!)(); + const safeErrorResult = buildToolCallResult( + { + ok: false, + error: + 'Temporary service error while reading verified catalog data. Please retry shortly.', + canonical_citation_url: CANONICAL_RATE_ORIGIN, + observed_at: snapshotAt, + }, + true + ); + return jsonRpcResultResponse( + requestId, + safeErrorResult as unknown as Record, + activeProtocolVersion + ); + } + } + + return jsonRpcErrorResponse( + 200, + requestId, + -32601, + `Method not found: ${sanitizeMcpPublicText(method, 80)}`, + undefined, + undefined, + activeProtocolVersion + ); + } catch { + return jsonRpcErrorResponse(500, null, -32603, 'Internal MCP server error'); + } +} + +export function buildRateWellKnownMcpDescriptor(): Record { + return { + mcpVersion: MCP_LATEST_PROTOCOL_VERSION, + supportedProtocolVersions: [...SUPPORTED_MCP_PROTOCOL_VERSIONS], + name: 'io.github.dos/rate-vn', + serverInfo: MCP_SERVER_INFO, + description: + 'Stateless read-only Streamable HTTP Model Context Protocol (MCP) server for Rate.vn: verified tech prices across 22 Vietnamese retail platforms, 10-group standardized hardware specs, historical fake-discount audits, DOSafe scam risk, and 6-axis Review Trust Model v2 scores.', + transport: 'streamable-http', + url: `${CANONICAL_RATE_ORIGIN}/api/mcp`, + endpoints: { + mcp: `${CANONICAL_RATE_ORIGIN}/api/mcp`, + transport: 'streamable-http', + }, + remotes: [ + { + type: 'streamable-http', + transport: 'streamable-http', + url: `${CANONICAL_RATE_ORIGIN}/api/mcp`, + }, + ], + documentationUrl: `${CANONICAL_RATE_ORIGIN}/developers#mcp`, + llmsTxtUrl: `${CANONICAL_RATE_ORIGIN}/llms.txt`, + openApiUrl: `${CANONICAL_RATE_ORIGIN}/api/v1/rate/openapi.json`, + repositoryUrl: 'https://github.com/DOS/Rate', + authentication: { + type: 'none', + readOnly: true, + rateLimit: { + requestsPerMinute: MCP_RATE_LIMIT_MAX_REQUESTS, + inspectRequestsPerMinute: 30, + maxBodyBytes: MAX_MCP_BODY_BYTES, + maxItemsPerCall: MAX_MCP_RESULT_ITEMS, + }, + }, + citationPolicy: { + requireCanonicalCitationUrl: true, + requireFreshnessTimestamp: true, + canonicalOrigin: CANONICAL_RATE_ORIGIN, + }, + capabilities: { + tools: { + listChanged: false, + }, + }, + tools: MCP_TOOL_DEFINITIONS.map((tool) => ({ + name: tool.name, + title: tool.title, + description: tool.description, + readOnly: true, + })), + }; +} + +export function buildRateLlmsTxt(): string { + return [ + '# Rate.vn - Verified Tech Price Truth & 6-Axis Review Trust Platform', + '', + '> Rate.vn is an open-core Vietnamese consumer tech comparison and anti-fake-discount platform covering 22 retail platforms across 5 hardware categories (smartphones, tablets, laptops, smartwatches, earbuds), backed by standardized 10-group specifications, historical price medians, DOSafe scam risk intelligence, and the 6-axis Review Trust Model v2.', + '', + '## Model Context Protocol (MCP) Server', + '', + '- Endpoint (`POST` JSON-RPC 2.0, stateless Streamable HTTP): https://rate.vn/api/mcp', + '- Discovery Descriptor: https://rate.vn/.well-known/mcp.json', + '- Supported MCP Protocol Versions: `2025-06-18`, `2025-03-26`, `2024-11-05`', + '- Access & Limits: Public read-only, no API key required, `Content-Type: application/json`, body `<= 16384` bytes, up to `10` items per tool call, per-IP sliding-window rate limiting (`429` with `Retry-After`).', + '- Mandatory Citation Rule: Every tool item includes `canonical_citation_url` (`https://rate.vn/...`) and freshness timestamps (`observed_at` / `price_observed_at`). AI agents MUST link `canonical_citation_url` and state when the price was observed.', + '', + '### Read-Only MCP Tools (`POST /api/mcp`)', + '', + '1. `search_verified_catalog`: Search normalized devices across `smartphones`, `tablets`, `laptops`, `smartwatches`, and `earbuds` with brand, VND price floor/ceiling, and rating sort (`limit <= 10`). Excludes sold-out and implausibly low bait-price listings.', + '2. `get_22_store_offers_and_price_truth`: Fetch verified in-stock offers across all 22 Vietnamese retail platforms, historical floor/median price truth, Deal Radar fake-sale flags, Bayesian rating (`k = 3`, prior `4.2`), and 6-axis Review Trust Model v2 summary for a product slug (`limit <= 10`).', + '3. `compare_devices_by_use_case`: Compare 2 to 4 same-category product slugs side-by-side across 10-group hardware specs, verified floor prices, and 5-criterion JReviews scores (`screen`, `performance`, `camera`, `battery`, `value`) with optional persona or custom weight overrides.', + '4. `audit_listing_url`: Inspect a marketplace product URL across the 22 supported Vietnamese stores and return catalog match, 5-level fake-discount verdict, accessory gatekeeper status, and DOSafe + AI review seller risk scores.', + '5. `get_genuine_deals`: List verified below-median and cross-platform floor deals (`limit <= 10`, optional category/platform/budget filter) with fake strikethrough markups and high-risk sellers filtered out.', + '', + '## 22 Tracked Vietnamese Retail Platforms', + '', + '- Marketplaces: `shopee`, `lazada`, `tiki`, `tiktok`', + '- Authorized Tech & Electronics Chains: `cellphones`, `tgdd`, `dienmayxanh`, `topzone`, `fptshop`, `hoangha`, `didongviet`, `phongvu`, `gearvn`, `nguyenkim`, `shopdunk`, `hacom`, `clickbuy`, `viettelstore`, `pico`, `mediamart`, `memoryzone`, `anphatpc`', + '', + '## Methodology & Data Integrity', + '', + '- **5 Canonical Categories**: [Smartphones](https://rate.vn/smartphones), [Tablets](https://rate.vn/tablets), [Laptops](https://rate.vn/laptops), [Smartwatches](https://rate.vn/smartwatches), [Earbuds](https://rate.vn/earbuds)', + '- **10-Group Specification Schema (`specifications` JSON keys)**: `availability`, `design`, `display`, `hardware`, `battery`, `camera` (PhoneArena per-lens split), `connectivity`, `cellular`, `multimedia`, `regulatory`.', + '- **Price Truth & Anti-Fake-Sale Engine**: Compares live selling prices against recorded historical medians rather than seller-declared strikethrough prices; excludes sold-out/discontinued offers and implausibly low bait/accessory listings from market floors.', + '- **6-Axis Review Trust Model v2 & Bayesian Rating**: Evaluates `authenticity`, `independence`, `depth`, `reviewer`, `context`, and `community` axes to filter coin-farming spam, duplicate paid seeding, competitor sabotage, and review bombing (`weight = 0`), then computes helpfulness-weighted Bayesian ratings (`k = 3`, prior `4.2`) alongside DOSafe seller scam risk.', + '', + '## REST API v1 & Developer Documentation', + '', + '- [Developer Portal & Interactive Playground](https://rate.vn/developers): Live REST API v1 playground, 10-group schema docs, and MCP quick-connect snippets.', + '- [OpenAPI 3.1.0 Specification](https://rate.vn/api/v1/rate/openapi.json): Full machine-readable specification for `/api/v1/rate/*` endpoints (`/products`, `/products/{slug}`, `/compare`, `/versus`, `/deals`, `/inspect`, `/lookup`, `/leaderboard`, `/merchants`, `/stats`).', + '- [Deal Hub](https://rate.vn/deals): Cross-platform genuine deals and inflated list-price warnings.', + '- [URL & Fake-Discount Inspector](https://rate.vn/inspect): Verify any listing URL across the 22 supported Vietnamese stores.', + '- [Category Leaderboard](https://rate.vn/leaderboard): JReviews dual-rating rankings across all 5 tech categories.', + '- [Open-Core Source Repository](https://github.com/DOS/Rate): Public normalization, scoring, and API verification code.', + '', + ].join('\n'); +} From 60e4981f3ecd69c522eb8f913a113ab0f964d4d2 Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:47:32 +0700 Subject: [PATCH 2/2] chore(git): allow tracked .well-known/mcp.json route in .gitignore --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index 3a4873adb..f61b0edf5 100644 --- a/.gitignore +++ b/.gitignore @@ -66,6 +66,8 @@ packages/*/.env .cursor/ memory-bank/ mcp.json +!apps/web/src/app/.well-known/mcp.json/ +!apps/web/src/app/.well-known/mcp.json/** .cache .strapi-updater.json