Skip to content

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

feat(chat): list every tool Chat may use in one registry (#1759)

Cihan7aebf55f8e91
diff --git a/web/messages/en.json b/web/messages/en.json
index c5ac72d06..4942cff9c 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -2984,6 +2984,68 @@
"planGateTitle": "Agent is a {plan} feature",
"planGateBody": "Upgrade your plan to chat with your dashboard about visibility, competitors, citations, and content gaps."
},
+ "chatTools": {
+ "profile": { "name": "Read your profile", "step": "Read your profile" },
+ "aiUsage": { "name": "Read AI usage", "step": "Read AI usage" },
+ "brands": { "name": "Read brands", "step": "Read Brands" },
+ "visibility": { "name": "Read visibility", "step": "Read Visibility" },
+ "visibilityTrend": { "name": "Read the visibility trend", "step": "Read Visibility trend" },
+ "trackedPrompts": { "name": "Read tracked prompts", "step": "Read Prompts" },
+ "promptPerformance": {
+ "name": "Read prompt performance",
+ "step": "Read Prompt performance"
+ },
+ "promptSuggestions": {
+ "name": "Read prompt suggestions",
+ "step": "Read Prompt Suggestions"
+ },
+ "promptVolumes": { "name": "Read prompt volumes", "step": "Read Prompt volumes" },
+ "topics": { "name": "Read topics", "step": "Read Topics" },
+ "mentionsSummary": { "name": "Read the mentions summary", "step": "Read Mentions" },
+ "mentions": { "name": "Read mentions", "step": "Read Mentions" },
+ "mention": { "name": "Read an answer naming the brand", "step": "Read mention" },
+ "mentionCompetitors": {
+ "name": "Read competitors named in answers",
+ "step": "Read Mentions · Competitors"
+ },
+ "mentionsPerception": {
+ "name": "Read how AI describes the brand",
+ "step": "Read Mentions · Perception"
+ },
+ "citations": { "name": "Read citations", "step": "Read Citations" },
+ "competitors": { "name": "Read competitors", "step": "Read Competitors" },
+ "competitorComparison": {
+ "name": "Compare competitors",
+ "step": "Read Competitors"
+ },
+ "productVisibility": { "name": "Read Product Visibility", "step": "Read Product Visibility" },
+ "aiReferralTraffic": {
+ "name": "Read AI Referral Traffic",
+ "step": "Read AI Referral Traffic"
+ },
+ "siteAudits": { "name": "Read Site Audits", "step": "Read Site Audit" },
+ "siteAuditIssues": { "name": "Read Site Audit issues", "step": "Read Site Audit" },
+ "actions": { "name": "Read Action Center actions", "step": "Read Action Center" },
+ "action": { "name": "Read an action", "step": "Read action" },
+ "signals": { "name": "Read signals", "step": "Read Signals" },
+ "actionHistory": { "name": "Read Action History", "step": "Read Action History" },
+ "contentOpportunities": {
+ "name": "Read content opportunities",
+ "step": "Read Content opportunities"
+ },
+ "drafts": { "name": "Read the Content Library", "step": "Read Library" },
+ "draft": { "name": "Read a draft", "step": "Read draft" },
+ "reports": { "name": "Read reports", "step": "Read Reports" },
+ "saveDraft": { "name": "Save drafts in Content", "step": "Saved draft in Content" },
+ "opportunityStatus": {
+ "name": "Review or dismiss opportunities",
+ "step": "Updated opportunity"
+ },
+ "dismissSuggestion": {
+ "name": "Dismiss prompt suggestions",
+ "step": "Dismissed prompt suggestion"
+ }
+ },
"audit": {
"title": "Site Audit",
"description": "Score any page against the 48-signal AEO/GEO",
diff --git a/web/src/lib/chat/registry/define-tool.ts b/web/src/lib/chat/registry/define-tool.ts
new file mode 100644
index 000000000..7759e9342
--- /dev/null
+++ b/web/src/lib/chat/registry/define-tool.ts
@@ -0,0 +1,178 @@
+import type { z } from 'zod';
+import type { TeamRole } from '@/components/providers/role-provider';
+import type { Feature, PlanId } from '@/config/plans';
+import type { McpAuthContext } from '@/lib/mcp-auth';
+
+/**
+ * Chat's tool registry (CHAT-20 §9): one row per tool Chat may call, saying
+ * what it does, who may call it, on which plan and how a call is approved.
+ * The same rows feed the model's tool list, the step labels (CHAT-03), the
+ * Settings pages (registryCatalog) and the MCP parity checks. A capability
+ * without a row isn't available to Chat ("silence = never"), and NEVER has
+ * no class here: it is simply no row.
+ *
+ * A row only describes; the approval precedence that reads it (plan, role,
+ * policy, mode) is checked on the server when a run calls the tool.
+ */
+
+/** What a call does (CHAT-20 §3): reads, changes data in Ansvisor, or goes live / leaves it. */
+export const TOOL_CLASSES = ['read', 'write', 'execute'] as const;
+export type ToolClass = (typeof TOOL_CLASSES)[number];
+
+/**
+ * How a call is approved (CHAT-20 §5 step 4 and §9's policy codes): `on` a
+ * read runs; `never` an Admin switched it off; `ask` a card in every mode;
+ * `ask_full_auto` a card, except in Full auto ("Ask (auto allowed in Full
+ * auto)"); `always` runs without a card; `click` an EXECUTE, which only the
+ * user's click ever runs.
+ */
+export const TOOL_POLICIES = ['on', 'never', 'ask', 'ask_full_auto', 'always', 'click'] as const;
+export type ToolPolicy = (typeof TOOL_POLICIES)[number];
+
+/** The policies a WRITE row may start at or be raised to, least automatic first. */
+export const WRITE_POLICIES = ['ask', 'ask_full_auto', 'always'] as const;
+export type WritePolicy = (typeof WRITE_POLICIES)[number];
+
+/** CHAT-20 §9 cost: C0 no model, C1 a scoped read, C2 a model writing step, C3 heavy. */
+export type CostClass = 'C0' | 'C1' | 'C2' | 'C3';
+
+/** The product area a tool belongs to, as "What Chat can do" groups them (CHAT-20 §8). */
+export type ToolArea =
+ | 'account'
+ | 'usage'
+ | 'brands'
+ | 'visibility'
+ | 'prompts'
+ | 'topics'
+ | 'mentions'
+ | 'citations'
+ | 'competitors'
+ | 'product_visibility'
+ | 'ai_traffic'
+ | 'site_audit'
+ | 'action_center'
+ | 'content'
+ | 'reports';
+
+/**
+ * What the plan decides about a call (CHAT-20 §7), null when nothing. The
+ * plan facts come from Billing at run time; self-hosted passes every gate.
+ */
+export interface PlanGate {
+ /** The lowest plan that may call it, of PLAN_ORDER. */
+ minPlan?: PlanId;
+ /** The plan feature its page checks ("As live page"). */
+ feature?: Feature;
+ /** Open on every plan, but the data covers only the plan's platforms (allowedScrapers). */
+ platforms?: true;
+}
+
+export interface ToolFlags {
+ /** A WRITE that shows a card in every mode, Full auto included; its policy tops out at Ask. */
+ alwaysCard: boolean;
+ /** The cost estimate (percent of the AI limit) is shown before the first call. */
+ costCard: boolean;
+ /** A READ an Admin may switch off for the workspace (CHAT-20 §9 ¹). */
+ adminMayTurnOff: boolean;
+}
+
+/**
+ * Who a tool acts as: the signed-in user, resolved into the shape the MCP
+ * data functions scope by (lib/agent/auth.ts resolveAgentAuth).
+ */
+export type ChatToolContext = McpAuthContext;
+
+interface ToolFields<S extends z.ZodObject> {
+ /** The internal name. Never shown to customers: steps show the label (CHAT-03). */
+ name: string;
+ area: ToolArea;
+ /** What the model reads to pick the tool. */
+ description: string;
+ /** The lowest role that may call it: `analyst` means every role (CHAT-20 §20). */
+ minRole: TeamRole;
+ planGate: PlanGate | null;
+ costClass: CostClass;
+ /**
+ * The key under `chatTools` in messages/en.json (`name` for Settings, `step`
+ * for CHAT-03), and the row's key in the browser's catalog.
+ */
+ labelKey: string;
+ /** The page in the app that shows the same thing (CHAT-19), or null. */
+ route: string | null;
+ /** The Ansvisor MCP Server tool that does the same work, or null. */
+ mcpTool: string | null;
+ /** Its row in CHAT-20 §9. */
+ specRow: string;
+ inputSchema: S;
+ run(ctx: ChatToolContext, input: z.output<S>): Promise<unknown>;
+ /** A valid input, for the registry's tests and the permission fixtures (CHAT-20 §19). */
+ fixture: { input: z.input<S> };
+}
+
+type ClassFields =
+ | { class: 'read'; flags?: Partial<Pick<ToolFlags, 'adminMayTurnOff' | 'costCard'>> }
+ | {
+ class: 'write';
+ defaultPolicy: WritePolicy;
+ maxPolicy: WritePolicy;
+ flags?: Partial<Pick<ToolFlags, 'alwaysCard' | 'costCard'>>;
+ }
+ | { class: 'execute'; flags?: Partial<Pick<ToolFlags, 'costCard'>> };
+
+export type ToolDefinition<S extends z.ZodObject> = ToolFields<S> & ClassFields;
+
+export type ChatTool<S extends z.ZodObject = z.ZodObject> = ToolFields<S> & {
+ class: ToolClass;
+ defaultPolicy: ToolPolicy;
+ maxPolicy: ToolPolicy;
+ flags: ToolFlags;
+};
+
+/** Ids for the rows' fixtures: any 8-4-4-4-12 hex id passes the inputs' uuid check. */
+export const FIXTURE_IDS = {
+ brand: '11111111-1111-4111-8111-111111111111',
+ item: '22222222-2222-4222-8222-222222222222',
+} as const;
+
+const writeRank = (policy: WritePolicy) => WRITE_POLICIES.indexOf(policy);
+
+/**
+ * A registry row, with the rules every row keeps checked as it is defined:
+ * a READ runs (`on`), an EXECUTE is always a click, and a WRITE's default
+ * never goes past its maximum, which an `always_card` WRITE keeps at Ask.
+ */
+export function defineTool<S extends z.ZodObject>(def: ToolDefinition<S>): ChatTool<S> {
+ const flags: ToolFlags = {
+ alwaysCard: false,
+ costCard: false,
+ adminMayTurnOff: false,
+ ...def.flags,
+ };
+ if (def.class === 'read') {
+ if (flags.alwaysCard) throw new Error(`${def.name}: a read has no approval card`);
+ return { ...def, defaultPolicy: 'on', maxPolicy: 'on', flags };
+ }
+ if (flags.adminMayTurnOff) throw new Error(`${def.name}: only a read is switched off`);
+ if (def.class === 'execute') {
+ if (flags.alwaysCard) throw new Error(`${def.name}: an execute is a click, not a card`);
+ // Its type has no policy fields; one passed anyway can only ask for less than a click.
+ if (
+ ('defaultPolicy' in def && def.defaultPolicy !== 'click') ||
+ ('maxPolicy' in def && def.maxPolicy !== 'click')
+ ) {
+ throw new Error(`${def.name}: an execute always needs the user's click`);
+ }
+ return { ...def, defaultPolicy: 'click', maxPolicy: 'click', flags };
+ }
+ if (def.class !== 'write') throw new Error('A tool is a read, a write or an execute');
+ if (!WRITE_POLICIES.includes(def.defaultPolicy) || !WRITE_POLICIES.includes(def.maxPolicy)) {
+ throw new Error(`${def.name}: a write is asked, asked unless Full auto, or always`);
+ }
+ if (writeRank(def.defaultPolicy) > writeRank(def.maxPolicy)) {
+ throw new Error(`${def.name}: its default policy is past its maximum`);
+ }
+ if (flags.alwaysCard && def.maxPolicy !== 'ask') {
+ throw new Error(`${def.name}: an always_card write never runs without a card`);
+ }
+ return { ...def, flags };
+}
diff --git a/web/src/lib/chat/registry/mcp-parity.test.ts b/web/src/lib/chat/registry/mcp-parity.test.ts
new file mode 100644
index 000000000..c04424632
--- /dev/null
+++ b/web/src/lib/chat/registry/mcp-parity.test.ts
@@ -0,0 +1,65 @@
+// @vitest-environment node
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import { beforeAll, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Chat and the Ansvisor MCP Server do the same work through the same rows
+ * (CHAT-20 §17): every MCP tool a row names is registered on the server, and
+ * the server agrees with the row on whether it only reads.
+ */
+
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));
+// The write rows' server actions; nothing here calls them.
+vi.mock('@/lib/actions/content', () => ({ updateOpportunityStatus: vi.fn() }));
+vi.mock('@/lib/actions/content-drafts', () => ({ createContentDraft: vi.fn() }));
+vi.mock('@/lib/actions/prompt-suggestions', () => ({ dismissSuggestion: vi.fn() }));
+
+const { CHAT_TOOLS } = await import('./tools');
+const { createMcpServer } = await import('@/lib/mcp/server');
+const { isReadTool } = await import('@/lib/mcp/subscription-gate');
+
+type McpTool = Awaited<ReturnType<Client['listTools']>>['tools'][number];
+let mcpTools: Map<string, McpTool>;
+
+beforeAll(async () => {
+ // role: the MCP context's since #1762; a const, so it compiles before it too.
+ const auth = {
+ userId: 'user-1',
+ email: null,
+ organizationId: 'org-1',
+ apiKeyId: 'key-1',
+ role: 'admin' as const,
+ };
+ const server = createMcpServer(auth);
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ await server.connect(serverTransport);
+ const client = new Client({ name: 'test', version: '1.0.0' });
+ await client.connect(clientTransport);
+ const { tools } = await client.listTools();
+ mcpTools = new Map(tools.map((tool) => [tool.name, tool]));
+});
+
+const mapped = CHAT_TOOLS.filter((tool) => tool.mcpTool);
+
+describe('the registry against the MCP Server', () => {
+ it('names only MCP tools the server registers', () => {
+ const unknown = mapped.filter((tool) => !mcpTools.has(tool.mcpTool!));
+ expect(unknown.map((tool) => `${tool.name} → ${tool.mcpTool}`)).toEqual([]);
+ });
+
+ it('maps a read to an MCP read and a write to an MCP write', () => {
+ // isReadTool is the server's own split: what stays open on a read-only workspace.
+ const crossed = mapped.filter((tool) => isReadTool(tool.mcpTool!) !== (tool.class === 'read'));
+ expect(crossed.map((tool) => `${tool.name} (${tool.class}) → ${tool.mcpTool}`)).toEqual([]);
+ });
+
+ it("agrees with the MCP tools' readOnlyHint wherever they state one", () => {
+ // On main only a few tools state it; #1732 adds it to every tool, and then this covers all.
+ const disagree = mapped.filter((tool) => {
+ const hint = mcpTools.get(tool.mcpTool!)?.annotations?.readOnlyHint;
+ return hint !== undefined && hint !== (tool.class === 'read');
+ });
+ expect(disagree.map((tool) => `${tool.name} → ${tool.mcpTool}`)).toEqual([]);
+ });
+});
diff --git a/web/src/lib/chat/registry/read-tools.ts b/web/src/lib/chat/registry/read-tools.ts
new file mode 100644
index 000000000..fffa2cfce
--- /dev/null
+++ b/web/src/lib/chat/registry/read-tools.ts
@@ -0,0 +1,764 @@
+import { z } from 'zod';
+import { MENTION_SENTIMENTS, MENTION_SORTS } from '@/lib/mentions-list';
+import { getAiUsageFor, getMeFor } from '@/lib/mcp/account';
+import { getContentDraftFor, listContentDraftsFor } from '@/lib/mcp/content';
+import { contentUuid, listDraftsShape } from '@/lib/mcp/content-schemas';
+import {
+ getActionFor,
+ getAiTrafficFor,
+ getCompetitorComparisonFor,
+ getProductVisibility,
+ getPromptPerformanceFor,
+ getPromptVolumesFor,
+ getSiteAuditFor,
+ getVisibilitySummaryFor,
+ getVisibilityTrendFor,
+ listActionHistoryFor,
+ listActionsFor,
+ listBrandsFor,
+ listCitationsFor,
+ listCompetitorsFor,
+ listContentOpportunitiesFor,
+ listPromptSuggestionsFor,
+ listPromptsFor,
+ listReportsFor,
+ listSignalsFor,
+ listSiteAuditsFor,
+ listTopicsFor,
+} from '@/lib/mcp/data';
+import {
+ getMentionCompetitorsFor,
+ getMentionFor,
+ getMentionsPerceptionFor,
+ getMentionsSummaryFor,
+ listMentionsFor,
+} from '@/lib/mcp/mentions';
+import { FIXTURE_IDS, defineTool } from './define-tool';
+
+/**
+ * Chat's READ rows (CHAT-20 §9): each one calls the data function the MCP
+ * tool of the same work calls, so Chat, the MCP Server and the in-product
+ * agent read the same numbers with the same organization scoping. Inputs
+ * are the MCP tool's, in its snake_case.
+ */
+
+const brandId = contentUuid.describe('Brand id, from list_brands.');
+const dateFrom = z.string().optional().describe('ISO timestamp (inclusive) lower bound.');
+const dateTo = z.string().optional().describe('ISO timestamp (inclusive) upper bound.');
+const model = z.string().optional().describe('A model slug, or comma-separated slugs.');
+const region = z.string().optional().describe('A region code, e.g. "US" or "TR".');
+const topicId = contentUuid.optional().describe('Topic id, from list_topics.');
+const rowCap = (max: number) => z.number().int().min(1).max(max).optional();
+
+/** The Mentions & Sentiment page's filters, the same on both mentions reads. */
+const mentionFilters = {
+ brand_id: brandId,
+ date_from: dateFrom,
+ date_to: dateTo,
+ platform: z.string().optional().describe('One platform id, e.g. "chatgpt-web".'),
+ region,
+ topic_id: topicId,
+ search: z.string().optional().describe("Matched against the prompts' text."),
+};
+
+function mentionParams(input: z.output<z.ZodObject<typeof mentionFilters>>) {
+ return {
+ brandId: input.brand_id,
+ dateFrom: input.date_from,
+ dateTo: input.date_to,
+ platform: input.platform,
+ region: input.region,
+ topicId: input.topic_id,
+ search: input.search,
+ };
+}
+
+const BRAND = FIXTURE_IDS.brand;
+const ITEM = FIXTURE_IDS.item;
+
+export const READ_TOOLS = [
+ defineTool({
+ name: 'get_profile',
+ class: 'read',
+ area: 'account',
+ description:
+ 'Who the user is: their id, email, organization, role (admin, manager, analyst or agency_partner) and work areas. Read it before suggesting something only an admin or a manager may do.',
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C0',
+ labelKey: 'profile',
+ route: '/dashboard/settings/account',
+ mcpTool: 'get_me',
+ specRow: '4',
+ inputSchema: z.object({}),
+ run: (ctx) => getMeFor(ctx),
+ fixture: { input: {} },
+ }),
+ defineTool({
+ name: 'get_usage',
+ class: 'read',
+ area: 'usage',
+ description:
+ "How much of the workspace's monthly AI limit is used this period, as a percent, with each feature's share, the plan and the renewal date. No dollar amounts.",
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C0',
+ labelKey: 'aiUsage',
+ route: '/dashboard/settings/billing',
+ mcpTool: 'get_ai_usage',
+ specRow: '6',
+ inputSchema: z.object({}),
+ run: (ctx) => getAiUsageFor(ctx),
+ fixture: { input: {} },
+ }),
+ defineTool({
+ name: 'list_brands',
+ class: 'read',
+ area: 'brands',
+ description:
+ 'The brands the user can access: id, name, slug, industry, region. Call it first when the user has not named a brand.',
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'brands',
+ route: '/dashboard/brands',
+ mcpTool: 'list_brands',
+ specRow: '7',
+ inputSchema: z.object({}),
+ run: (ctx) => listBrandsFor(ctx),
+ fixture: { input: {} },
+ }),
+ defineTool({
+ name: 'get_visibility_summary',
+ class: 'read',
+ area: 'visibility',
+ description:
+ 'A brand\'s visibility over a period: results, average visibility (0–100), mentions, citations and the top competitors. For "how is my brand doing" questions.',
+ minRole: 'analyst',
+ planGate: { platforms: true },
+ costClass: 'C1',
+ labelKey: 'visibility',
+ route: '/dashboard/insights',
+ mcpTool: 'get_visibility_summary',
+ specRow: '12',
+ inputSchema: z.object({
+ brand_id: brandId,
+ date_from: dateFrom,
+ date_to: dateTo,
+ model,
+ region,
+ }),
+ run: (ctx, input) =>
+ getVisibilitySummaryFor(ctx, {
+ brandId: input.brand_id,
+ dateFrom: input.date_from,
+ dateTo: input.date_to,
+ model: input.model,
+ region: input.region,
+ }),
+ fixture: { input: { brand_id: BRAND } },
+ }),
+ defineTool({
+ name: 'get_visibility_trend',
+ class: 'read',
+ area: 'visibility',
+ description:
+ "A brand's visibility, mentions and citations over time, by day or week. For trend questions and charts.",
+ minRole: 'analyst',
+ planGate: { platforms: true },
+ costClass: 'C1',
+ labelKey: 'visibilityTrend',
+ route: '/dashboard/insights',
+ mcpTool: 'get_visibility_trend',
+ specRow: '12',
+ inputSchema: z.object({
+ brand_id: brandId,
+ date_from: dateFrom,
+ date_to: dateTo,
+ granularity: z.enum(['day', 'week']).optional(),
+ model,
+ region,
+ topic_id: topicId,
+ }),
+ run: (ctx, input) =>
+ getVisibilityTrendFor(ctx, {
+ brandId: input.brand_id,
+ dateFrom: input.date_from,
+ dateTo: input.date_to,
+ granularity: input.granularity,
+ model: input.model,
+ region: input.region,
+ topicId: input.topic_id,
+ }),
+ fixture: { input: { brand_id: BRAND, granularity: 'week' } },
+ }),
+ defineTool({
+ name: 'list_prompts',
+ class: 'read',
+ area: 'prompts',
+ description:
+ 'The prompts tracked for a brand, with topic, platforms, regions and whether each is active; newest first. Filter by topic or active state.',
+ minRole: 'analyst',
+ planGate: { platforms: true },
+ costClass: 'C1',
+ labelKey: 'trackedPrompts',
+ route: '/dashboard/prompts/tracked',
+ mcpTool: 'list_prompts',
+ specRow: '13',
+ inputSchema: z.object({
+ brand_id: brandId,
+ topic_id: topicId,
+ is_active: z.boolean().optional(),
+ limit: rowCap(500).describe('Row cap, default 100.'),
+ }),
+ run: (ctx, input) =>
+ listPromptsFor(ctx, {
+ brandId: input.brand_id,
+ topicId: input.topic_id,
+ isActive: input.is_active,
+ limit: input.limit,
+ }),
+ fixture: { input: { brand_id: BRAND, is_active: true } },
+ }),
+ defineTool({
+ name: 'get_prompt_performance',
+ class: 'read',
+ area: 'prompts',
+ description:
+ 'Visibility, mentions, citations and appearances per prompt over a period, sorted. For "which prompts do best" or "which dropped this week".',
+ minRole: 'analyst',
+ planGate: { platforms: true },
+ costClass: 'C1',
+ labelKey: 'promptPerformance',
+ route: '/dashboard/prompts/tracked',
+ mcpTool: 'get_prompt_performance',
+ specRow: '13',
+ inputSchema: z.object({
+ brand_id: brandId,
+ date_from: dateFrom,
+ date_to: dateTo,
+ topic_id: topicId,
+ sort_by: z.enum(['visibility', 'mentions', 'citations', 'appearances']).optional(),
+ order: z.enum(['desc', 'asc']).optional(),
+ limit: rowCap(100).describe('Row cap, default 10.'),
+ model,
+ region,
+ }),
+ run: (ctx, input) =>
+ getPromptPerformanceFor(ctx, {
+ brandId: input.brand_id,
+ dateFrom: input.date_from,
+ dateTo: input.date_to,
+ topicId: input.topic_id,
+ sortBy: input.sort_by,
+ order: input.order,
+ limit: input.limit,
+ model: input.model,
+ region: input.region,
+ }),
+ fixture: { input: { brand_id: BRAND, sort_by: 'visibility' } },
+ }),
+ defineTool({
+ name: 'list_prompt_suggestions',
+ class: 'read',
+ area: 'prompts',
+ description:
+ "The brand's pending prompt suggestions with topic, reason and an estimated volume. The volume is an AI guess, low confidence: say so when quoting it.",
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'promptSuggestions',
+ route: '/dashboard/prompts/suggestions',
+ mcpTool: 'list_prompt_suggestions',
+ specRow: '15',
+ inputSchema: z.object({ brand_id: brandId }),
+ run: (ctx, input) => listPromptSuggestionsFor(ctx, input.brand_id),
+ fixture: { input: { brand_id: BRAND } },
+ }),
+ defineTool({
+ name: 'get_prompt_volumes',
+ class: 'read',
+ area: 'prompts',
+ description:
+ "Each tracked prompt's estimated AI searches a month, with its range and confidence. An estimate, not a measurement.",
+ minRole: 'analyst',
+ planGate: { feature: 'prompt_volumes' },
+ costClass: 'C1',
+ labelKey: 'promptVolumes',
+ route: '/dashboard/prompts/tracked',
+ mcpTool: 'get_prompt_volumes',
+ specRow: '17',
+ inputSchema: z.object({
+ brand_id: brandId,
+ limit: rowCap(500).describe('Row cap, default 100.'),
+ }),
+ run: (ctx, input) => getPromptVolumesFor(ctx, { brandId: input.brand_id, limit: input.limit }),
+ fixture: { input: { brand_id: BRAND } },
+ }),
+ defineTool({
+ name: 'list_topics',
+ class: 'read',
+ area: 'topics',
+ description: "The brand's topics, each with its number of prompts.",
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'topics',
+ route: '/dashboard/prompts/topics',
+ mcpTool: 'list_topics',
+ specRow: '24',
+ inputSchema: z.object({ brand_id: brandId }),
+ run: (ctx, input) => listTopicsFor(ctx, input.brand_id),
+ fixture: { input: { brand_id: BRAND } },
+ }),
+ defineTool({
+ name: 'get_mentions_summary',
+ class: 'read',
+ area: 'mentions',
+ description:
+ 'How often AI answers name the brand and how they speak of it, against the period before: mention rate, net sentiment (−100…+100) and the sentiment split. Under 20 mentions it is a low sample: say so.',
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'mentionsSummary',
+ route: '/dashboard/mentions',
+ mcpTool: 'get_mentions_summary',
+ specRow: '27',
+ inputSchema: z.object(mentionFilters),
+ run: (ctx, input) => getMentionsSummaryFor(ctx, mentionParams(input)),
+ fixture: { input: { brand_id: BRAND } },
+ }),
+ defineTool({
+ name: 'list_mentions',
+ class: 'read',
+ area: 'mentions',
+ description:
+ 'The AI answers naming the brand, 100 a page: prompt, platform, sentiment, position, competitors named alongside and an excerpt.',
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'mentions',
+ route: '/dashboard/mentions',
+ mcpTool: 'list_mentions',
+ specRow: '27',
+ inputSchema: z.object({
+ ...mentionFilters,
+ sentiment: z.enum(MENTION_SENTIMENTS).optional(),
+ competitor_id: z
+ .string()
+ .optional()
+ .describe('Only answers also naming this competitor, or "none" for none.'),
+ sort: z.enum(MENTION_SORTS).optional(),
+ page: z.number().int().min(1).optional(),
+ }),
+ run: (ctx, input) =>
+ listMentionsFor(ctx, {
+ ...mentionParams(input),
+ sentiment: input.sentiment,
+ competitorId: input.competitor_id,
+ sort: input.sort,
+ page: input.page,
+ }),
+ fixture: { input: { brand_id: BRAND, sentiment: 'negative' } },
+ }),
+ // Not in CHAT-20 §9 yet: the Mentions area's reads (§8a "snippets, themes")
+ // that today's agent (/dashboard/agent) has, so Chat answers what it does.
+ defineTool({
+ name: 'get_mention',
+ class: 'read',
+ area: 'mentions',
+ description:
+ 'One AI answer naming the brand, in full: its text, citations, the competitors it names, its sentiment and any correction to it.',
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'mention',
+ route: '/dashboard/mentions',
+ mcpTool: 'get_mention',
+ specRow: '27',
+ inputSchema: z.object({ id: contentUuid.describe('The answer id, from list_mentions.') }),
+ run: (ctx, input) => getMentionFor(ctx, input.id),
+ fixture: { input: { id: ITEM } },
+ }),
+ defineTool({
+ name: 'get_mention_competitors',
+ class: 'read',
+ area: 'mentions',
+ description:
+ "How often AI answers name each competitor in the brand's tracked answers (count, share, change against the period before) and how often alongside the brand.",
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'mentionCompetitors',
+ route: '/dashboard/mentions',
+ mcpTool: 'get_mention_competitors',
+ specRow: '27',
+ inputSchema: z.object(mentionFilters),
+ run: (ctx, input) => getMentionCompetitorsFor(ctx, mentionParams(input)),
+ fixture: { input: { brand_id: BRAND } },
+ }),
+ defineTool({
+ name: 'get_mentions_perception',
+ class: 'read',
+ area: 'mentions',
+ description:
+ 'What AI associates with the brand: the terms next to it, now and before, the attributes that set it apart from its top competitors, and the biggest gap a competitor leads. Found by rule, no model.',
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'mentionsPerception',
+ route: '/dashboard/mentions',
+ mcpTool: 'get_mentions_perception',
+ specRow: '27',
+ inputSchema: z.object(mentionFilters),
+ run: (ctx, input) => getMentionsPerceptionFor(ctx, mentionParams(input)),
+ fixture: { input: { brand_id: BRAND } },
+ }),
+ defineTool({
+ name: 'list_citations',
+ class: 'read',
+ area: 'citations',
+ description:
+ 'The domains and pages AI answers cite for the brand over a period, owned, competitor or external.',
+ minRole: 'analyst',
+ planGate: { platforms: true },
+ costClass: 'C1',
+ labelKey: 'citations',
+ route: '/dashboard/citations',
+ mcpTool: 'list_citations',
+ specRow: '28',
+ inputSchema: z.object({
+ brand_id: brandId,
+ date_from: dateFrom,
+ date_to: dateTo,
+ model,
+ region,
+ topic_id: topicId,
+ limit: rowCap(200).describe('Cap on the top domains and pages, default 50.'),
+ source_filter: z.enum(['all', 'owned', 'competitor', 'external']).optional(),
+ }),
+ run: (ctx, input) =>
+ listCitationsFor(ctx, {
+ brandId: input.brand_id,
+ dateFrom: input.date_from,
+ dateTo: input.date_to,
+ model: input.model,
+ region: input.region,
+ topicId: input.topic_id,
+ limit: input.limit,
+ sourceFilter: input.source_filter,
+ }),
+ fixture: { input: { brand_id: BRAND, source_filter: 'competitor' } },
+ }),
+ defineTool({
+ name: 'list_competitors',
+ class: 'read',
+ area: 'competitors',
+ description: 'The competitors set up for the brand: id, name and domain. Not a ranking.',
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'competitors',
+ route: '/dashboard/competitors',
+ mcpTool: 'list_competitors',
+ specRow: '29',
+ inputSchema: z.object({ brand_id: brandId }),
+ run: (ctx, input) => listCompetitorsFor(ctx, input.brand_id),
+ fixture: { input: { brand_id: BRAND } },
+ }),
+ defineTool({
+ name: 'get_competitor_comparison',
+ class: 'read',
+ area: 'competitors',
+ description:
+ 'The brand against each competitor over a period: visibility, mentions, citations and share of voice, also per platform.',
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'competitorComparison',
+ route: '/dashboard/competitors',
+ mcpTool: 'get_competitor_comparison',
+ specRow: '29',
+ inputSchema: z.object({
+ brand_id: brandId,
+ date_from: dateFrom,
+ date_to: dateTo,
+ model,
+ region,
+ topic_id: topicId,
+ }),
+ run: (ctx, input) =>
+ getCompetitorComparisonFor(ctx, {
+ brandId: input.brand_id,
+ dateFrom: input.date_from,
+ dateTo: input.date_to,
+ model: input.model,
+ region: input.region,
+ topicId: input.topic_id,
+ }),
+ fixture: { input: { brand_id: BRAND } },
+ }),
+ defineTool({
+ name: 'get_shopping_visibility',
+ class: 'read',
+ area: 'product_visibility',
+ description:
+ "One product's appearances in AI shopping results: by platform, region and date, its rating, reviews and the merchants selling it.",
+ minRole: 'analyst',
+ planGate: { feature: 'shopping_analytics' },
+ costClass: 'C1',
+ labelKey: 'productVisibility',
+ route: '/dashboard/shopping',
+ mcpTool: 'get_product_visibility',
+ specRow: '33',
+ inputSchema: z.object({
+ brand_id: brandId,
+ product_title: z
+ .string()
+ .min(1)
+ .describe('The product title as AI shopping results show it.'),
+ }),
+ run: (ctx, input) =>
+ getProductVisibility(ctx, { brandId: input.brand_id, productTitle: input.product_title }),
+ fixture: { input: { brand_id: BRAND, product_title: 'Trail Runner 2' } },
+ }),
+ defineTool({
+ name: 'get_ai_traffic_summary',
+ class: 'read',
+ area: 'ai_traffic',
+ description:
+ "Visits AI assistants sent to the brand's site over a period: total, by platform, top pages and countries.",
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'aiReferralTraffic',
+ route: '/dashboard/traffic',
+ mcpTool: 'get_ai_traffic',
+ specRow: '35',
+ inputSchema: z.object({ brand_id: brandId, date_from: dateFrom, date_to: dateTo }),
+ run: (ctx, input) =>
+ getAiTrafficFor(ctx, {
+ brandId: input.brand_id,
+ dateFrom: input.date_from,
+ dateTo: input.date_to,
+ }),
+ fixture: { input: { brand_id: BRAND } },
+ }),
+ defineTool({
+ name: 'get_site_audit_summary',
+ class: 'read',
+ area: 'site_audit',
+ description:
+ "The brand's recent Site Audits, newest first: page, status, score and date. Read one with its issues through list_site_audit_issues.",
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'siteAudits',
+ route: '/dashboard/audit',
+ mcpTool: 'list_site_audits',
+ specRow: '36',
+ inputSchema: z.object({ brand_id: brandId }),
+ run: (ctx, input) => listSiteAuditsFor(ctx, input.brand_id),
+ fixture: { input: { brand_id: BRAND } },
+ }),
+ defineTool({
+ name: 'list_site_audit_issues',
+ class: 'read',
+ area: 'site_audit',
+ description: 'One Site Audit in full: its score and every check, passed or failed.',
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'siteAuditIssues',
+ route: '/dashboard/audit',
+ mcpTool: 'get_site_audit',
+ specRow: '36',
+ inputSchema: z.object({
+ audit_id: contentUuid.describe('Site Audit id, from get_site_audit_summary.'),
+ }),
+ run: (ctx, input) => getSiteAuditFor(ctx, input.audit_id),
+ fixture: { input: { audit_id: ITEM } },
+ }),
+ defineTool({
+ name: 'list_action_center_tasks',
+ class: 'read',
+ area: 'action_center',
+ description:
+ "The brand's Action Center actions, highest priority first: category, impact, priority, status, assignee, due date and task progress.",
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'actions',
+ route: '/dashboard/action-center/actions',
+ mcpTool: 'list_actions',
+ specRow: '38',
+ inputSchema: z.object({
+ brand_id: brandId,
+ status: z.enum(['new', 'in_progress', 'on_hold', 'completed', 'dismissed']).optional(),
+ category: z.enum(['growth', 'protect', 'recover', 'fix', 'compete']).optional(),
+ limit: rowCap(200).describe('Row cap, default 50.'),
+ sort: z.enum(['updated', 'priority']).optional(),
+ }),
+ run: (ctx, input) =>
+ listActionsFor(ctx, {
+ brandId: input.brand_id,
+ status: input.status,
+ category: input.category,
+ limit: input.limit,
+ sort: input.sort,
+ }),
+ fixture: { input: { brand_id: BRAND, status: 'new' } },
+ }),
+ defineTool({
+ name: 'get_action',
+ class: 'read',
+ area: 'action_center',
+ description:
+ 'One Action Center action in full: what it is about, why, its priority, signals, tasks (What, Where, Why, How, Done when) and outcome.',
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'action',
+ route: '/dashboard/action-center/actions',
+ mcpTool: 'get_action',
+ specRow: '39',
+ inputSchema: z.object({
+ action_id: contentUuid.describe('Action id, from list_action_center_tasks.'),
+ }),
+ run: (ctx, input) => getActionFor(ctx, input.action_id),
+ fixture: { input: { action_id: ITEM } },
+ }),
+ defineTool({
+ name: 'list_signals',
+ class: 'read',
+ area: 'action_center',
+ description:
+ 'The changes the Action Center detected for the brand, newest first: what moved, by how much, where, and the actions built on each.',
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'signals',
+ route: '/dashboard/action-center/signals',
+ mcpTool: 'list_signals',
+ specRow: '40',
+ inputSchema: z.object({
+ brand_id: brandId,
+ status: z.enum(['new', 'acknowledged', 'resolved', 'dismissed']).optional(),
+ kind: z.string().optional().describe('A signal kind, as returned in earlier rows.'),
+ limit: rowCap(200).describe('Row cap, default 50.'),
+ }),
+ run: (ctx, input) =>
+ listSignalsFor(ctx, {
+ brandId: input.brand_id,
+ status: input.status,
+ kind: input.kind,
+ limit: input.limit,
+ }),
+ fixture: { input: { brand_id: BRAND } },
+ }),
+ defineTool({
+ name: 'get_action_history',
+ class: 'read',
+ area: 'action_center',
+ description:
+ 'Closed actions with their measured outcome, latest first. An outcome before day 30 is a reading so far, and a change is never claimed as caused by the action.',
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'actionHistory',
+ route: '/dashboard/action-center/history',
+ mcpTool: 'list_action_history',
+ specRow: '42',
+ inputSchema: z.object({
+ brand_id: brandId,
+ limit: rowCap(200).describe('Row cap, default 50.'),
+ }),
+ run: (ctx, input) => listActionHistoryFor(ctx, { brandId: input.brand_id, limit: input.limit }),
+ fixture: { input: { brand_id: BRAND } },
+ }),
+ defineTool({
+ name: 'list_content_opportunities',
+ class: 'read',
+ area: 'content',
+ description:
+ "The brand's content opportunities, highest score first: the prompts where it loses visibility and the page that would win them.",
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'contentOpportunities',
+ route: '/dashboard/content',
+ mcpTool: 'list_content_opportunities',
+ specRow: '48',
+ inputSchema: z.object({
+ brand_id: brandId,
+ status: z
+ .enum(['new', 'reviewed', 'sent', 'in_progress', 'done', 'dismissed', 'archived'])
+ .optional(),
+ impact: z.enum(['high', 'medium', 'low']).optional(),
+ type: z.enum(['owned', 'earned']).optional(),
+ limit: rowCap(200).describe('Row cap, default 50.'),
+ }),
+ run: (ctx, input) =>
+ listContentOpportunitiesFor(ctx, {
+ brandId: input.brand_id,
+ status: input.status,
+ impact: input.impact,
+ type: input.type,
+ limit: input.limit,
+ }),
+ fixture: { input: { brand_id: BRAND, impact: 'high' } },
+ }),
+ defineTool({
+ name: 'list_drafts',
+ class: 'read',
+ area: 'content',
+ description:
+ "The brand's Content Library drafts, latest changed first: title, status, method, page type and author.",
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'drafts',
+ route: '/dashboard/content/library',
+ mcpTool: 'list_content_drafts',
+ specRow: '53',
+ inputSchema: z.object(listDraftsShape),
+ run: (ctx, input) => listContentDraftsFor(ctx, input.brand_id, input.status),
+ fixture: { input: { brand_id: BRAND, status: 'in_review' } },
+ }),
+ defineTool({
+ name: 'get_draft',
+ class: 'read',
+ area: 'content',
+ description:
+ 'One draft: its HTML passage by passage, where it is live, and the suggestions waiting for review. Passages AI answers quote are locked.',
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'draft',
+ route: '/dashboard/content/library',
+ mcpTool: 'get_content_draft',
+ specRow: '53',
+ inputSchema: z.object({ draft_id: contentUuid.describe('Draft id, from list_drafts.') }),
+ run: (ctx, input) => getContentDraftFor(ctx, input.draft_id),
+ fixture: { input: { draft_id: ITEM } },
+ }),
+ defineTool({
+ name: 'get_reports',
+ class: 'read',
+ area: 'reports',
+ description: "The brand's saved reports, newest first: title, template and date range.",
+ minRole: 'analyst',
+ planGate: null,
+ costClass: 'C1',
+ labelKey: 'reports',
+ route: '/dashboard/reports',
+ mcpTool: 'list_reports',
+ specRow: '63',
+ inputSchema: z.object({
+ brand_id: brandId,
+ limit: rowCap(100).describe('Row cap, default 50.'),
+ }),
+ run: (ctx, input) => listReportsFor(ctx, input.brand_id, input.limit),
+ fixture: { input: { brand_id: BRAND } },
+ }),
+];
diff --git a/web/src/lib/chat/registry/tools.test.ts b/web/src/lib/chat/registry/tools.test.ts
new file mode 100644
index 000000000..8302d2003
--- /dev/null
+++ b/web/src/lib/chat/registry/tools.test.ts
@@ -0,0 +1,368 @@
+// @vitest-environment node
+import { existsSync, readdirSync } from 'node:fs';
+import path from 'node:path';
+import { z } from 'zod';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../../messages/en.json';
+import type { ChatTool } from './define-tool';
+import { clientEventProblems, type ChatEvent } from '../events';
+
+/**
+ * The registry's rows (CHAT-20 §9, §21): each has its label and a fixture,
+ * names are unique, an EXECUTE is always a click, and each row calls the
+ * function it names — a READ the MCP data function, a WRITE the server
+ * action the app's own button calls — with nothing between.
+ */
+
+const calls = vi.hoisted(() => [] as { from: string; args: unknown[] }[]);
+const tracked = vi.hoisted(() => {
+ const track = (from: string) =>
+ vi.fn(async (...args: unknown[]) => {
+ calls.push({ from, args });
+ return { from };
+ });
+ return {
+ track,
+ /** Every function a module exports, tracked; its constants as they are. */
+ all: (prefix: string, mod: Record<string, unknown>) =>
+ Object.fromEntries(
+ Object.entries(mod).map(([key, value]) => [
+ key,
+ typeof value === 'function' ? track(`${prefix}.${key}`) : value,
+ ]),
+ ),
+ };
+});
+
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));
+vi.mock('@/lib/mcp/data', async (importOriginal) =>
+ tracked.all('mcp/data', await importOriginal<Record<string, unknown>>()),
+);
+vi.mock('@/lib/mcp/content', async (importOriginal) =>
+ tracked.all('mcp/content', await importOriginal<Record<string, unknown>>()),
+);
+vi.mock('@/lib/mcp/mentions', async (importOriginal) =>
+ tracked.all('mcp/mentions', await importOriginal<Record<string, unknown>>()),
+);
+vi.mock('@/lib/mcp/account', async (importOriginal) =>
+ tracked.all('mcp/account', await importOriginal<Record<string, unknown>>()),
+);
+vi.mock('@/lib/actions/content', () => ({
+ updateOpportunityStatus: tracked.track('actions/content.updateOpportunityStatus'),
+}));
+vi.mock('@/lib/actions/content-drafts', () => ({
+ createContentDraft: tracked.track('actions/content-drafts.createContentDraft'),
+}));
+vi.mock('@/lib/actions/prompt-suggestions', () => ({
+ dismissSuggestion: tracked.track('actions/prompt-suggestions.dismissSuggestion'),
+}));
+
+const { CHAT_TOOLS, chatTool, chatToolByKey, registryCatalog } = await import('./tools');
+const { FIXTURE_IDS, defineTool } = await import('./define-tool');
+
+const ctx = {
+ userId: 'user-1',
+ email: null,
+ organizationId: 'org-1',
+ apiKeyId: 'agent-internal',
+ role: 'admin' as const,
+};
+const labels = (messages as Record<string, unknown>).chatTools as Record<string, unknown>;
+
+/** What keeps a row out of the registry: a missing label, a fixture its schema refuses. */
+function rowProblems(tool: ChatTool, chatTools: Record<string, unknown> = labels): string[] {
+ const problems: string[] = [];
+ const label = chatTools?.[tool.labelKey] as Record<string, unknown> | undefined;
+ for (const part of ['name', 'step']) {
+ const text = label?.[part];
+ if (typeof text !== 'string' || !text.trim()) {
+ problems.push(`no chatTools.${tool.labelKey}.${part} in en.json`);
+ }
+ }
+ if (!tool.fixture || !('input' in tool.fixture)) problems.push('no fixture');
+ else if (!tool.inputSchema.safeParse(tool.fixture.input).success) {
+ problems.push("its fixture doesn't pass its input schema");
+ }
+ return problems;
+}
+
+/** The app's page for a route: a folder per segment, or a [param] folder for any. */
+const dashboardDir = path.join(__dirname, '../../../app/[locale]/(dashboard)');
+function pageExists(route: string): boolean {
+ let dirs = [dashboardDir];
+ for (const segment of route.split('/').filter(Boolean)) {
+ dirs = dirs.flatMap((dir) => {
+ if (!existsSync(dir)) return [];
+ const children = readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory());
+ return children
+ .filter((d) => d.name === segment || /^\[[^.\]]+\]$/.test(d.name))
+ .map((d) => path.join(dir, d.name));
+ });
+ }
+ return dirs.some((dir) => existsSync(path.join(dir, 'page.tsx')));
+}
+
+const readRow = {
+ name: 'read_test',
+ class: 'read' as const,
+ area: 'brands' as const,
+ description: 'test',
+ minRole: 'analyst' as const,
+ planGate: null,
+ costClass: 'C0' as const,
+ labelKey: 'brands',
+ route: null,
+ mcpTool: null,
+ specRow: '0',
+ inputSchema: z.object({}),
+ run: async () => null,
+ fixture: { input: {} },
+};
+
+beforeEach(() => {
+ calls.length = 0;
+});
+
+describe('the Chat tool registry', () => {
+ it('has a label and a valid fixture on every row', () => {
+ const problems = CHAT_TOOLS.flatMap((tool) =>
+ rowProblems(tool).map((problem) => `${tool.name}: ${problem}`),
+ );
+ expect(problems).toEqual([]);
+ });
+
+ it('fails a row whose label is missing or whose fixture is', () => {
+ const row = defineTool({ ...readRow, labelKey: 'notALabel' });
+ expect(rowProblems(row)).toEqual([
+ 'no chatTools.notALabel.name in en.json',
+ 'no chatTools.notALabel.step in en.json',
+ ]);
+ const noFixture = { ...defineTool(readRow), fixture: undefined } as unknown as ChatTool;
+ expect(rowProblems(noFixture)).toEqual(['no fixture']);
+ const badFixture = defineTool({
+ ...readRow,
+ inputSchema: z.object({ brand_id: z.string() }),
+ fixture: { input: {} as { brand_id: string } },
+ });
+ expect(rowProblems(badFixture)).toEqual(["its fixture doesn't pass its input schema"]);
+ });
+
+ it('gives every tool its own name and its own label', () => {
+ const names = CHAT_TOOLS.map((tool) => tool.name);
+ expect(new Set(names).size).toBe(names.length);
+ const keys = CHAT_TOOLS.map((tool) => tool.labelKey);
+ expect(new Set(keys).size).toBe(keys.length);
+ });
+
+ it("keeps the tools' names out of the label keys, which reach the browser", () => {
+ // Every page gets all of en.json; a function name never reaches a customer (CHAT-03).
+ const camel = (name: string) => name.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase());
+ for (const tool of CHAT_TOOLS) {
+ expect(tool.labelKey).not.toContain('_');
+ expect(tool.labelKey).not.toBe(camel(tool.name));
+ }
+ });
+
+ it('finds a row by its name, and nothing for a name without one', () => {
+ expect(chatTool('list_brands')?.class).toBe('read');
+ expect(chatTool('delete_brand')).toBeUndefined();
+ });
+
+ it('points every route at a page of the app', () => {
+ const missing = CHAT_TOOLS.filter((tool) => tool.route && !pageExists(tool.route));
+ expect(missing.map((tool) => `${tool.name} → ${tool.route}`)).toEqual([]);
+ });
+
+ it.each(CHAT_TOOLS.map((tool) => [tool.name, tool] as const))(
+ '%s calls its own function with the fixture, and returns what it returns',
+ async (_name, tool) => {
+ const result = await tool.run(ctx, tool.inputSchema.parse(tool.fixture.input));
+ expect(calls).toHaveLength(1);
+ expect(result).toEqual({ from: calls[0].from });
+ if (tool.class === 'read') {
+ // The MCP data functions, scoped to the signed-in member's organization.
+ expect(calls[0].from).toMatch(/^mcp\//);
+ expect(calls[0].args[0]).toBe(ctx);
+ } else {
+ // The app's server actions, through the member's own session.
+ expect(calls[0].from).toMatch(/^actions\//);
+ }
+ },
+ );
+
+ it('hands the app the same arguments its pages pass', async () => {
+ const run = (name: string, input: unknown) => {
+ const tool = chatTool(name)!;
+ return tool.run(ctx, tool.inputSchema.parse(input));
+ };
+ const { brand, item } = FIXTURE_IDS;
+
+ await run('dismiss_prompt_suggestion', { suggestion_id: item });
+ await run('update_opportunity', {
+ opportunity_id: item,
+ status: 'dismissed',
+ reason: 'wrong_angle',
+ });
+ // A reason goes only with a dismissal.
+ await run('update_opportunity', {
+ opportunity_id: item,
+ status: 'reviewed',
+ reason: 'wrong_angle',
+ });
+ await run('create_draft', {
+ brand_id: brand,
+ title: ' Pricing FAQ ',
+ page_type: 'docs_faq',
+ source: { kind: 'opportunity', id: item },
+ });
+
+ expect(calls.map((call) => [call.from, call.args])).toEqual([
+ ['actions/prompt-suggestions.dismissSuggestion', [item]],
+ ['actions/content.updateOpportunityStatus', [item, 'dismissed', 'wrong_angle']],
+ ['actions/content.updateOpportunityStatus', [item, 'reviewed', undefined]],
+ [
+ 'actions/content-drafts.createContentDraft',
+ [
+ brand,
+ {
+ method: 'create',
+ title: 'Pricing FAQ',
+ pageType: 'docs_faq',
+ typePicked: false,
+ source: { kind: 'opportunity', id: item },
+ bodyHtml: undefined,
+ sourceUrl: undefined,
+ },
+ ],
+ ],
+ ]);
+ });
+
+ it('refuses what the update and draft writes are not for', () => {
+ const update = chatTool('update_opportunity')!.inputSchema;
+ // Only reviewed or dismissed (CHAT-20 §9 row 49), not the rest of the workflow.
+ expect(update.safeParse({ opportunity_id: FIXTURE_IDS.item, status: 'done' }).success).toBe(
+ false,
+ );
+ const draft = chatTool('create_draft')!.inputSchema;
+ const base = {
+ brand_id: FIXTURE_IDS.brand,
+ title: 'Pricing',
+ page_type: 'pricing',
+ source: { kind: 'content' },
+ };
+ expect(draft.safeParse(base).success).toBe(true);
+ expect(draft.safeParse({ ...base, source_url: 'ftp://example.com' }).success).toBe(false);
+ expect(draft.safeParse({ ...base, page_type: 'press_release' }).success).toBe(false);
+ });
+});
+
+describe('approval policies', () => {
+ it('lets a read run, and starts every write here at Ask (auto allowed in Full auto)', () => {
+ for (const tool of CHAT_TOOLS) {
+ if (tool.class === 'read') {
+ expect([tool.defaultPolicy, tool.maxPolicy]).toEqual(['on', 'on']);
+ } else if (tool.class === 'write') {
+ expect([tool.defaultPolicy, tool.maxPolicy]).toEqual(['ask_full_auto', 'always']);
+ // Analysts and Agency partners are read-only (CHAT-20 §4).
+ expect(['admin', 'manager']).toContain(tool.minRole);
+ }
+ }
+ });
+
+ it('keeps every execute at a click', () => {
+ for (const tool of CHAT_TOOLS.filter((t) => t.class === 'execute')) {
+ expect([tool.defaultPolicy, tool.maxPolicy]).toEqual(['click', 'click']);
+ }
+ const execute = defineTool({ ...readRow, name: 'publish_test', class: 'execute' });
+ expect([execute.defaultPolicy, execute.maxPolicy]).toEqual(['click', 'click']);
+ // A row that asks for less than a click isn't defined at all.
+ expect(() =>
+ defineTool({ ...readRow, class: 'execute', defaultPolicy: 'always' } as never),
+ ).toThrow(/click/);
+ expect(() =>
+ defineTool({ ...readRow, class: 'execute', maxPolicy: 'ask_full_auto' } as never),
+ ).toThrow(/click/);
+ });
+
+ it("refuses a write's policy past what its flags allow", () => {
+ const write = { ...readRow, class: 'write' as const };
+ expect(() =>
+ defineTool({ ...write, defaultPolicy: 'always', maxPolicy: 'ask_full_auto' }),
+ ).toThrow(/past its maximum/);
+ // An always_card write shows its card in every mode, Full auto too (CHAT-20 §3a).
+ expect(() =>
+ defineTool({
+ ...write,
+ defaultPolicy: 'ask',
+ maxPolicy: 'ask_full_auto',
+ flags: { alwaysCard: true },
+ }),
+ ).toThrow(/without a card/);
+ expect(
+ defineTool({ ...write, defaultPolicy: 'ask', maxPolicy: 'ask', flags: { alwaysCard: true } })
+ .flags,
+ ).toEqual({ alwaysCard: true, costCard: false, adminMayTurnOff: false });
+ expect(() => defineTool({ ...write, defaultPolicy: 'on', maxPolicy: 'on' } as never)).toThrow(
+ /asked/,
+ );
+ });
+});
+
+describe('registryCatalog', () => {
+ it('lists every row as plain data, in registry order, with no code in it', () => {
+ const catalog = registryCatalog();
+ expect(catalog.map((entry) => entry.key)).toEqual(CHAT_TOOLS.map((tool) => tool.labelKey));
+ expect(JSON.parse(JSON.stringify(catalog))).toEqual(catalog);
+ for (const entry of catalog) {
+ expect(Object.keys(entry).sort()).toEqual(
+ [
+ 'area',
+ 'class',
+ 'costClass',
+ 'defaultPolicy',
+ 'flags',
+ 'key',
+ 'maxPolicy',
+ 'minRole',
+ 'planGate',
+ 'route',
+ ].sort(),
+ );
+ }
+ });
+
+ it('never carries a tool name to the browser, internal or MCP', () => {
+ // CHAT-03 item 22: no name in any value, and no key A1's event rule refuses.
+ const names = new Set(CHAT_TOOLS.flatMap((tool) => [tool.name, tool.mcpTool ?? '']));
+ const values: unknown[] = [];
+ const walk = (value: unknown) => {
+ if (value && typeof value === 'object') Object.values(value).forEach(walk);
+ else values.push(value);
+ };
+ const catalog = registryCatalog();
+ walk(catalog);
+ expect(values.filter((value) => typeof value === 'string' && names.has(value))).toEqual([]);
+ const asEvent = { type: 'next_moves', seq: 1, data: { catalog } } as unknown as ChatEvent;
+ expect(clientEventProblems(asEvent)).toEqual([]);
+ });
+
+ it('leads a key from the browser back to its row on the server', () => {
+ for (const tool of CHAT_TOOLS) expect(chatToolByKey(tool.labelKey)).toBe(tool);
+ expect(chatToolByKey('list_brands')).toBeUndefined();
+ });
+
+ it('describes a row as it is defined, without sharing its objects', () => {
+ const row = defineTool({ ...readRow, planGate: { feature: 'prompt_volumes' } });
+ const [entry] = registryCatalog([row]);
+ expect(entry).toMatchObject({
+ key: 'brands',
+ class: 'read',
+ defaultPolicy: 'on',
+ planGate: { feature: 'prompt_volumes' },
+ flags: { alwaysCard: false, costCard: false, adminMayTurnOff: false },
+ });
+ expect(entry.planGate).not.toBe(row.planGate);
+ expect(entry.flags).not.toBe(row.flags);
+ });
+});
diff --git a/web/src/lib/chat/registry/tools.ts b/web/src/lib/chat/registry/tools.ts
new file mode 100644
index 000000000..f06985b36
--- /dev/null
+++ b/web/src/lib/chat/registry/tools.ts
@@ -0,0 +1,63 @@
+import type { ChatTool, PlanGate, ToolFlags } from './define-tool';
+import { READ_TOOLS } from './read-tools';
+import { WRITE_TOOLS } from './write-tools';
+
+/**
+ * Every tool Chat may call (CHAT-20 §9). One without a row here isn't
+ * available to Chat. The rows, with their internal and MCP names, stay on
+ * the server: the approval checks, the run steps' `tool` column and the MCP
+ * parity read them here. What a browser gets is registryCatalog().
+ */
+export const CHAT_TOOLS: readonly ChatTool[] = [...READ_TOOLS, ...WRITE_TOOLS];
+
+/** The row of a tool, by its internal name; undefined for a name with no row. */
+export function chatTool(name: string): ChatTool | undefined {
+ return CHAT_TOOLS.find((tool) => tool.name === name);
+}
+
+/**
+ * The row a catalog entry's `key` stands for: how the server reads which
+ * tool a Settings page means (a policy change, say). Undefined for a key
+ * with no row.
+ */
+export function chatToolByKey(key: string): ChatTool | undefined {
+ return CHAT_TOOLS.find((tool) => tool.labelKey === key);
+}
+
+/**
+ * A row as a page shows it: its decisions, under its label key, without
+ * its names, schema, code or fixture.
+ */
+export type ToolCatalogEntry = Pick<
+ ChatTool,
+ 'area' | 'class' | 'defaultPolicy' | 'maxPolicy' | 'minRole' | 'costClass' | 'route'
+> & {
+ /** The label key: `chatTools.{key}.name` in messages/en.json names it. */
+ key: string;
+ flags: ToolFlags;
+ planGate: PlanGate | null;
+};
+
+/**
+ * The registry as plain data for the browser: Settings › Chat, "What Chat
+ * can do" and Roles & access (CHAT-20 §4a, §20). Every row, in registry
+ * order, built from the rows on each call so it can't drift from what the
+ * server checks. A tool's name, internal or MCP, never reaches a customer
+ * (CHAT-03 item 22), so a row goes by its label key, which a page sends
+ * back for chatToolByKey. Server code only (a server component or action
+ * passes the result on): the rows import the functions they call.
+ */
+export function registryCatalog(tools: readonly ChatTool[] = CHAT_TOOLS): ToolCatalogEntry[] {
+ return tools.map((tool) => ({
+ key: tool.labelKey,
+ area: tool.area,
+ class: tool.class,
+ defaultPolicy: tool.defaultPolicy,
+ maxPolicy: tool.maxPolicy,
+ flags: { ...tool.flags },
+ minRole: tool.minRole,
+ planGate: tool.planGate ? { ...tool.planGate } : null,
+ costClass: tool.costClass,
+ route: tool.route,
+ }));
+}
diff --git a/web/src/lib/chat/registry/write-tools.ts b/web/src/lib/chat/registry/write-tools.ts
new file mode 100644
index 000000000..4d1040b83
--- /dev/null
+++ b/web/src/lib/chat/registry/write-tools.ts
@@ -0,0 +1,131 @@
+import { z } from 'zod';
+import { updateOpportunityStatus } from '@/lib/actions/content';
+import { createContentDraft } from '@/lib/actions/content-drafts';
+import { dismissSuggestion } from '@/lib/actions/prompt-suggestions';
+import { PAGE_TYPES } from '@/lib/content/drafts';
+import { MAX_BODY_HTML_LENGTH, MAX_TITLE_LENGTH } from '@/lib/content/editor';
+import { contentUuid, isHttpUrl } from '@/lib/mcp/content-schemas';
+import { FIXTURE_IDS, defineTool } from './define-tool';
+
+/**
+ * Chat's first WRITE rows (CHAT-20 §9), enough to try the approval flow.
+ * Each one calls the server action the app's own button calls, so a change
+ * made through Chat is the change the page makes: as the signed-in member,
+ * through their session, with the read-only workspace check those actions
+ * already run. They need that session: a run with no request behind it
+ * (a schedule, CHAT-12) can't call them as they are.
+ */
+
+const BRAND = FIXTURE_IDS.brand;
+const ITEM = FIXTURE_IDS.item;
+
+export const WRITE_TOOLS = [
+ defineTool({
+ name: 'create_draft',
+ class: 'write',
+ area: 'content',
+ description:
+ "Save a page as a new draft in the brand's Content Library, as New content does: its title, page type, what it starts from (an opportunity, a tracked prompt, a topic, or content to optimize) and, when there is one, its HTML.",
+ defaultPolicy: 'ask_full_auto',
+ maxPolicy: 'always',
+ minRole: 'manager',
+ planGate: null,
+ costClass: 'C2',
+ labelKey: 'saveDraft',
+ route: '/dashboard/content/library',
+ mcpTool: 'create_content_draft',
+ specRow: '54',
+ inputSchema: z.object({
+ brand_id: contentUuid.describe('Brand id, from list_brands.'),
+ title: z.string().trim().min(1).max(MAX_TITLE_LENGTH).describe('The page title, its H1.'),
+ page_type: z.enum(PAGE_TYPES),
+ method: z
+ .enum(['create', 'optimize'])
+ .default('create')
+ .describe('create: a new page; optimize: a new version of the page at source_url.'),
+ source: z.discriminatedUnion('kind', [
+ z.object({ kind: z.enum(['opportunity', 'prompt', 'topic']), id: contentUuid }),
+ z.object({ kind: z.literal('content') }),
+ ]),
+ body_html: z.string().max(MAX_BODY_HTML_LENGTH).optional().describe('The page as HTML.'),
+ source_url: z
+ .string()
+ .trim()
+ .max(2048)
+ .refine(isHttpUrl, 'source_url must be an http(s) address')
+ .optional()
+ .describe('For optimize: the live page.'),
+ }),
+ run: (_ctx, input) =>
+ createContentDraft(input.brand_id, {
+ method: input.method,
+ title: input.title,
+ pageType: input.page_type,
+ // The model's pick is a guess, as Start's is: the type follows the page (CE-023).
+ typePicked: false,
+ source: input.source,
+ bodyHtml: input.body_html,
+ sourceUrl: input.source_url,
+ }),
+ fixture: {
+ input: {
+ brand_id: BRAND,
+ title: 'Pricing FAQ',
+ page_type: 'docs_faq',
+ source: { kind: 'opportunity', id: ITEM },
+ },
+ },
+ }),
+ defineTool({
+ name: 'update_opportunity',
+ class: 'write',
+ area: 'content',
+ description:
+ 'Mark a content opportunity reviewed, or dismiss it, optionally saying why (not relevant, or the wrong angle).',
+ defaultPolicy: 'ask_full_auto',
+ maxPolicy: 'always',
+ minRole: 'manager',
+ planGate: null,
+ costClass: 'C0',
+ labelKey: 'opportunityStatus',
+ route: '/dashboard/content',
+ mcpTool: 'update_opportunity_status',
+ specRow: '49',
+ inputSchema: z.object({
+ opportunity_id: contentUuid.describe('Opportunity id, from list_content_opportunities.'),
+ status: z.enum(['reviewed', 'dismissed']),
+ reason: z
+ .enum(['not_relevant', 'wrong_angle'])
+ .optional()
+ .describe('Why it is dismissed; only with dismissed.'),
+ }),
+ run: (_ctx, input) =>
+ updateOpportunityStatus(
+ input.opportunity_id,
+ input.status,
+ input.status === 'dismissed' ? input.reason : undefined,
+ ),
+ fixture: { input: { opportunity_id: ITEM, status: 'dismissed', reason: 'not_relevant' } },
+ }),
+ defineTool({
+ name: 'dismiss_prompt_suggestion',
+ class: 'write',
+ area: 'prompts',
+ description:
+ 'Dismiss a pending prompt suggestion so it leaves the suggestion list. Only when the user asked for that suggestion to go.',
+ defaultPolicy: 'ask_full_auto',
+ maxPolicy: 'always',
+ minRole: 'manager',
+ planGate: null,
+ costClass: 'C0',
+ labelKey: 'dismissSuggestion',
+ route: '/dashboard/prompts/suggestions',
+ mcpTool: 'dismiss_prompt_suggestion',
+ specRow: '23',
+ inputSchema: z.object({
+ suggestion_id: contentUuid.describe('Suggestion id, from list_prompt_suggestions.'),
+ }),
+ run: (_ctx, input) => dismissSuggestion(input.suggestion_id),
+ fixture: { input: { suggestion_id: ITEM } },
+ }),
+];