Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(mcp): read what worked: the action scorecard, net results and dismiss reasons (#1712)
Cihan3c13cc1c4627
diff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdxindex eb254ec03..e771580db 100644--- a/docs/guides/mcp-server.mdx+++ b/docs/guides/mcp-server.mdx@@ -220,7 +220,7 @@ instead.## Available tools-The MCP server exposes **52 tools**. Descriptions below match+The MCP server exposes **53 tools**. Descriptions below match[`web/src/lib/mcp/server.ts`](https://github.com/ansvisor/ansvisor/blob/main/web/src/lib/mcp/server.ts).Tools that change data are marked **writes** — only call them on explicit userintent, not during exploratory queries.@@ -339,12 +339,15 @@ Drafts are read and written as a person would in the editor. Ansvisor never publ| Tool | What it does | Writes || --- | --- | --- || `list_actions` | Recommended actions for a brand with priority (0–100 score, level and reasons), status, impact, assignee, due date, and task progress. Highest priority first; `sort: "updated"` lists the most recently updated first. | |-| `get_action` | One action in full: priority, payload, triggering signals, tasks (`mode`, `permission`), and event trail. `format: "markdown"` or `"csv"` returns it as the dashboard's **Copy Data** and **Export CSV** write it instead. | |+| `get_action` | One action in full: priority, payload, triggering signals, tasks (`mode`, `permission`), event trail, and once closed `net_of_control` and `dismiss_reason`. `format: "markdown"` or `"csv"` returns it as the dashboard's **Copy Data** and **Export CSV** write it instead. | || `list_signals` | Detected changes (visibility, citations, traffic), each with `where` (prompt, topic, platforms, locations, domain, competitor), `change` (labelled figures with unit and period), `evidence` (detection dates, app links) and `used_by_actions`. | |-| `list_action_history` | Closed actions with measured outcomes and before/after validation results. | |+| `list_action_history` | Closed actions with measured outcomes and before/after validation results, each with `net_of_control` (its change net of the brand's prompts it didn't touch, so a market-wide swing doesn't read as its effect) and `dismiss_reason` (`not_relevant`, `already_done`, `wrong_data` or `not_now`). | |+| `get_action_scorecard` | What each kind of action did at the brand, as the History tab's scorecard shows it: completed and their results, `success_rate` (from three verdicts), `median_change_percent`, and dismissals by reason. Optional `date_from`. | || `update_task_status` | Record progress on a task (`in_progress`, `completed`, `skipped`, `failed`); does not execute the task. | **yes** || `create_improve_action` | Send a prompt's Improve suggestions to Action Center as a `prompt_improve` action (needs a generated suggestion set for the range and a plan with Improve; idempotent on `idempotency_key`). | **yes** |+The scorecard is also available over REST: `GET /api/mcp/action-scorecard?brand_id=<brand_id>&date_from=2026-09-01`.+#### Export an action`get_action` takes an optional `format`:diff --git a/web/src/app/api/mcp/action-scorecard/route.test.ts b/web/src/app/api/mcp/action-scorecard/route.test.tsnew file mode 100644index 000000000..7a28c55fb--- /dev/null+++ b/web/src/app/api/mcp/action-scorecard/route.test.ts@@ -0,0 +1,52 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++/** GET /api/mcp/action-scorecard: the REST mirror of the MCP tool get_action_scorecard. */++const { getActionScorecardFor } = vi.hoisted(() => ({ getActionScorecardFor: vi.fn() }));+vi.mock('@/lib/mcp-auth', () => ({+ authenticateMcpRequest: vi.fn(async () => ({+ userId: 'user-1',+ email: null,+ organizationId: 'org-1',+ apiKeyId: 'key-1',+ })),+}));+vi.mock('@/lib/mcp/learning', () => ({ getActionScorecardFor }));++const { GET } = await import('./route');++const get = (query: string) =>+ GET(new Request(`http://localhost/api/mcp/action-scorecard${query}`));++beforeEach(() => {+ getActionScorecardFor.mockReset();+});++describe('GET /api/mcp/action-scorecard', () => {+ it("answers the brand's scorecard since a day", async () => {+ getActionScorecardFor.mockResolvedValue([{ kind: 'citation_gap', completed: 2 }]);+ const res = await get('?brand_id=brand-1&date_from=2026-09-01');+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ scorecard: [{ kind: 'citation_gap', completed: 2 }] });+ expect(getActionScorecardFor).toHaveBeenCalledWith(expect.anything(), {+ brandId: 'brand-1',+ since: '2026-09-01',+ });+ });++ it('asks for a brand, and a date it can read', async () => {+ expect((await get('')).status).toBe(400);+ expect((await get('?brand_id=brand-1&date_from=soon')).status).toBe(400);+ expect(getActionScorecardFor).not.toHaveBeenCalled();+ });++ it("answers 404 for another organization's brand, and 500 on a failure", async () => {+ getActionScorecardFor.mockResolvedValue(null);+ expect((await get('?brand_id=brand-2')).status).toBe(404);+ getActionScorecardFor.mockRejectedValue(new Error('statement timeout'));+ const res = await get('?brand_id=brand-1');+ expect(res.status).toBe(500);+ expect(await res.json()).toEqual({ error: 'statement timeout' });+ });+});diff --git a/web/src/app/api/mcp/action-scorecard/route.ts b/web/src/app/api/mcp/action-scorecard/route.tsnew file mode 100644index 000000000..558a15c80--- /dev/null+++ b/web/src/app/api/mcp/action-scorecard/route.ts@@ -0,0 +1,30 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { getActionScorecardFor } from '@/lib/mcp/learning';++/** GET /api/mcp/action-scorecard — REST mirror of the `get_action_scorecard` MCP tool. */+export async function GET(req: Request) {+ const auth = await authenticateMcpRequest(req);+ if (auth instanceof NextResponse) return auth;++ const url = new URL(req.url);+ const brandId = url.searchParams.get('brand_id');+ if (!brandId) {+ return NextResponse.json({ error: 'brand_id is required' }, { status: 400 });+ }+ const since = url.searchParams.get('date_from') ?? undefined;+ if (since !== undefined && !Number.isFinite(Date.parse(since))) {+ return NextResponse.json({ error: 'date_from is not a date' }, { status: 400 });+ }++ try {+ const scorecard = await getActionScorecardFor(auth, { brandId, since });+ if (scorecard === null) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });+ }+ return NextResponse.json({ scorecard });+ } catch (err) {+ const message = err instanceof Error ? err.message : 'Failed';+ return NextResponse.json({ error: message }, { status: 500 });+ }+}diff --git a/web/src/lib/action-center/history.test.ts b/web/src/lib/action-center/history.test.tsindex 388504710..f02f7737d 100644--- a/web/src/lib/action-center/history.test.ts+++ b/web/src/lib/action-center/history.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { compareHistory, summarize, type ActionHistoryItem } from './history';+import { compareHistory, controlNetOf, summarize, type ActionHistoryItem } from './history';const item = (over: Partial<ActionHistoryItem> = {}): ActionHistoryItem =>({@@ -39,3 +39,48 @@ describe('summarize', () => {expect(summarize([item()]).topPriority).toBeNull();});});++describe('controlNetOf', () => {+ it('reads the net the validation sweep kept, the metrics it can name', () => {+ expect(+ controlNetOf({+ control: {+ basis: 'topics',+ prompts: 12,+ net: [+ { metric: 'visibility', net: -1.5, unit: 'points' },+ { metric: 'citations', net: Number.NaN, unit: 'percent' },+ { metric: 'sessions', net: 4, unit: 'sessions' },+ ],+ },+ }),+ ).toEqual({+ basis: 'topics',+ prompts: 12,+ net: [{ metric: 'visibility', net: -1.5, unit: 'points' }],+ });+ });++ it('reads none without a control, a metric it can name or a basket size', () => {+ expect(controlNetOf(null)).toBeNull();+ expect(controlNetOf({})).toBeNull();+ expect(+ controlNetOf({ control: { prompts: 12, net: [{ metric: 'x', net: 1, unit: 'sessions' }] } }),+ ).toBeNull();+ expect(+ controlNetOf({ control: { net: [{ metric: 'visibility', net: 1, unit: 'points' }] } }),+ ).toBeNull();+ });++ it('reads any basis but topics as the brand', () => {+ expect(+ controlNetOf({+ control: {+ basis: 'other',+ prompts: 3,+ net: [{ metric: 'mentions', net: 1, unit: 'points' }],+ },+ })?.basis,+ ).toBe('brand');+ });+});diff --git a/web/src/lib/action-center/history.ts b/web/src/lib/action-center/history.tsindex 1933d5aa1..153a431d5 100644--- a/web/src/lib/action-center/history.ts+++ b/web/src/lib/action-center/history.ts@@ -97,6 +97,37 @@ export interface ControlNet {net: { metric: string; net: number; unit: 'points' | 'percent' }[];}+/**+ * Its change net of the control basket, as the validation sweep keeps it+ * (`validation.control`), the metrics it can name; null when it has none.+ */+export function controlNetOf(+ validation: {+ control?: {+ basis?: string;+ prompts?: number;+ net?: { metric?: string; net?: number; unit?: string }[];+ };+ } | null,+): ControlNet | null {+ const control = validation?.control;+ if (!control || !Array.isArray(control.net)) return null;+ const net = control.net.flatMap((m) =>+ typeof m?.metric === 'string' &&+ typeof m.net === 'number' &&+ Number.isFinite(m.net) &&+ (m.unit === 'points' || m.unit === 'percent')+ ? [{ metric: m.metric, net: m.net, unit: m.unit as 'points' | 'percent' }]+ : [],+ );+ if (!net.length || !Number.isInteger(control.prompts)) return null;+ return {+ basis: control.basis === 'topics' ? 'topics' : 'brand',+ prompts: control.prompts as number,+ net,+ };+}+/** A signal that opened the action. Several signals consolidate into one* action, so this is a list rather than a field. */export interface TriggerSignal {diff --git a/web/src/lib/action-center/registry.ts b/web/src/lib/action-center/registry.tsindex c569967df..807ff0211 100644--- a/web/src/lib/action-center/registry.ts+++ b/web/src/lib/action-center/registry.ts@@ -175,6 +175,13 @@ export const ACTION_DISMISS_REASONS = [] as const;export type ActionDismissReason = (typeof ACTION_DISMISS_REASONS)[number];+/** A stored dismiss reason, if it is one of ACTION_DISMISS_REASONS; null otherwise. */+export function dismissReasonOf(value: unknown): ActionDismissReason | null {+ return (ACTION_DISMISS_REASONS as readonly unknown[]).includes(value)+ ? (value as ActionDismissReason)+ : null;+}+/** An action whose cycle is over: it is history, and its kind's slot is free. */export const CLOSED_ACTION_STATUSES: readonly ActionStatus[] = ['completed', 'dismissed'];diff --git a/web/src/lib/actions/action-history.ts b/web/src/lib/actions/action-history.tsindex 9b57b886c..8d7ab9b00 100644--- a/web/src/lib/actions/action-history.ts+++ b/web/src/lib/actions/action-history.ts@@ -17,9 +17,8 @@import { createClient } from '@/lib/supabase/server';import type { ActionCategory } from '@/lib/action-center/registry';import {- ACTION_DISMISS_REASONS,ACTION_OUTCOMES,- type ActionDismissReason,+ dismissReasonOf,type ActionOutcome,type ActionStatus,type TaskStatus,@@ -30,6 +29,7 @@ import { storedPriorityLevel } from '@/lib/action-center/priority';import { readEntityCounts, withEntityCounts } from '@/lib/action-center/entity-counts';import {HISTORY_STATUSES,+ controlNetOf,daysBetween,type ActionHistoryItem,type ActionHistoryTask,@@ -38,7 +38,6 @@ import {type OutcomeReading,type SignalOutcome,type TriggerSignal,- type ControlNet,} from '@/lib/action-center/history';interface HistoryRow {@@ -100,26 +99,6 @@ interface ValidationSnapshot {};}-/** Its change net of the control basket, the metrics it can name. */-function controlFrom(validation: ValidationSnapshot | null): ControlNet | null {- const control = validation?.control;- if (!control || !Array.isArray(control.net)) return null;- const net = control.net.flatMap((m) =>- typeof m?.metric === 'string' &&- typeof m.net === 'number' &&- Number.isFinite(m.net) &&- (m.unit === 'points' || m.unit === 'percent')- ? [{ metric: m.metric, net: m.net, unit: m.unit as 'points' | 'percent' }]- : [],- );- if (!net.length || !Number.isInteger(control.prompts)) return null;- return {- basis: control.basis === 'topics' ? 'topics' : 'brand',- prompts: control.prompts as number,- net,- };-}-/** Its readings, the days known and verdicts it can name, in order. */function readingsFrom(validation: ValidationSnapshot | null): OutcomeReading[] {if (!Array.isArray(validation?.readings)) return [];@@ -374,11 +353,7 @@ export async function getActionHistory(triggerSignals,affected: affectedFrom(row.kind, row.payload ?? {}, triggerSignals.length),results,- dismissReason: (ACTION_DISMISS_REASONS as readonly string[]).includes(- row.dismiss_reason ?? '',- )- ? (row.dismiss_reason as ActionDismissReason)- : null,+ dismissReason: dismissReasonOf(row.dismiss_reason),signalsAfter: signalsFrom(row.validation),measuredOn: measuredOnFrom(row.validation),auditAfter: auditFrom(row.validation),@@ -392,7 +367,7 @@ export async function getActionHistory(brandWideResults: resultsFrom(row.validation?.brandWide ? { ...row.validation, metrics: row.validation.brandWide } : null,),- controlNet: controlFrom(row.validation),+ controlNet: controlNetOf(row.validation),tasks: tasksByAction.get(row.id) ?? [],assignee: row.assignee_id ? (profiles.get(row.assignee_id) ?? null) : null,dueDate: row.due_date ?? null,diff --git a/web/src/lib/mcp/action-history.test.ts b/web/src/lib/mcp/action-history.test.tsindex f09a1e564..28f9246ff 100644--- a/web/src/lib/mcp/action-history.test.ts+++ b/web/src/lib/mcp/action-history.test.ts@@ -4,7 +4,8 @@ import type { McpAuthContext } from '@/lib/mcp-auth';/*** list_action_history says whether an action's outcome is the result or a* reading so far (learning B1): an action is read 7, 14 and 30 days after it- * closed, and only the day-30 reading is final.+ * closed, and only the day-30 reading is final. It also gives its change net+ * of the control basket (learning B2) and why it was dismissed (learning A5).*/let actionRows: Record<string, unknown>[] = [];@@ -98,3 +99,45 @@ describe('listActionHistoryFor readings', () => {expect(await row()).toMatchObject({ final: false, reading_day: null });});});++describe('listActionHistoryFor results', () => {+ beforeEach(() => {+ actionRows = [];+ });++ it('gives its change net of the control basket, the metrics it can name', async () => {+ actionRows = [+ action('improved', {+ control: {+ basis: 'topics',+ prompts: 24,+ net: [+ { metric: 'visibility', net: 4.2, unit: 'points', control: { before: 30, after: 31 } },+ { metric: 'citations', net: 18.5, unit: 'percent' },+ { metric: 'sessions', net: 3, unit: 'sessions' },+ ],+ },+ }),+ ];+ expect((await row())?.net_of_control).toEqual({+ basis: 'topics',+ control_prompts: 24,+ metrics: [+ { metric: 'visibility', net: 4.2, unit: 'points' },+ { metric: 'citations', net: 18.5, unit: 'percent' },+ ],+ });+ });++ it('gives none when it could not be netted', async () => {+ actionRows = [action('improved', { metrics: [] })];+ expect((await row())?.net_of_control).toBeNull();+ });++ it('says why a dismissed one was turned down, and nothing it does not know', async () => {+ actionRows = [{ ...action(null, null), status: 'dismissed', dismiss_reason: 'already_done' }];+ expect(await row()).toMatchObject({ status: 'dismissed', dismiss_reason: 'already_done' });+ actionRows = [{ ...action(null, null), status: 'dismissed', dismiss_reason: 'bored' }];+ expect((await row())?.dismiss_reason).toBeNull();+ });+});diff --git a/web/src/lib/mcp/action-priority.test.ts b/web/src/lib/mcp/action-priority.test.tsindex b12f8e6f0..17cfc0172 100644--- a/web/src/lib/mcp/action-priority.test.ts+++ b/web/src/lib/mcp/action-priority.test.ts@@ -46,6 +46,8 @@ const ACTIONS = [let actionRows: Record<string, unknown>[] = ACTIONS;let taskRows: Record<string, unknown>[] = [];+/** What get_action's own row adds to the first action. */+let detail: Record<string, unknown> = {};function builder(table: string) {const chain = {@@ -61,7 +63,7 @@ function builder(table: string) {maybeSingle: async () => ({data:table === 'actions'- ? { ...ACTIONS[0], brand_id: 'brand-1', payload: {} }+ ? { ...ACTIONS[0], brand_id: 'brand-1', payload: {}, ...detail }: { id: 'brand-1' },error: null,}),@@ -218,6 +220,38 @@ describe('getActionFor', () => {}});+ it('gives a closed action its change net of the control and why it was dismissed', async () => {+ detail = {+ status: 'completed',+ outcome: 'improved',+ validation: {+ control: {+ basis: 'brand',+ prompts: 40,+ net: [{ metric: 'mentions', net: 2.5, unit: 'points' }],+ },+ },+ dismiss_reason: null,+ };+ try {+ expect(await getActionFor(auth, 'a1')).toMatchObject({+ net_of_control: {+ basis: 'brand',+ control_prompts: 40,+ metrics: [{ metric: 'mentions', net: 2.5, unit: 'points' }],+ },+ dismiss_reason: null,+ });+ detail = { status: 'dismissed', validation: null, dismiss_reason: 'wrong_data' };+ expect(await getActionFor(auth, 'a1')).toMatchObject({+ net_of_control: null,+ dismiss_reason: 'wrong_data',+ });+ } finally {+ detail = {};+ }+ });+it('gives the action its priority', async () => {const action = await getActionFor(auth, 'a1');expect(action?.priority).toEqual({diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.tsindex 829c2369d..1dc5d0f09 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -37,6 +37,8 @@ import {withTemplateCheck,withTemplateDoneWhen,} from '@/lib/action-center/task-details';+import { controlNetOf } from '@/lib/action-center/history';+import { dismissReasonOf, type ActionDismissReason } from '@/lib/action-center/registry';import { locationCode, isValidLocation } from '@/lib/region';import { promptVolumeEstimate, type EstimateConfidence } from '@/lib/volume-estimate';import { readPromptDemand, type PromptDemand } from './prompt-demand';@@ -2986,6 +2988,10 @@ export interface ActionDetailForMcp {impact: string;status: string;outcome: string | null;+ /** Its change net of the brand's prompts it didn't touch (learning B2); null when not netted. */+ net_of_control: McpNetOfControl | null;+ /** Why it was dismissed, as the person said (learning A5); null otherwise. */+ dismiss_reason: ActionDismissReason | null;payload: Record<string, unknown>;kpi_keys: string[];assignee: { id: string; full_name: string | null } | null;@@ -3060,7 +3066,7 @@ export async function getActionFor(const { data: action, error } = await supabaseAdmin.from('actions').select(- 'id, action_no, brand_id, category, kind, impact, status, outcome, payload, kpi_keys, assignee_id, due_date, created_at, updated_at, completed_at, priority_score, priority_level, priority_reason, brands!inner(organization_id)',+ 'id, action_no, brand_id, category, kind, impact, status, outcome, validation, dismiss_reason, payload, kpi_keys, assignee_id, due_date, created_at, updated_at, completed_at, priority_score, priority_level, priority_reason, brands!inner(organization_id)',).eq('id', actionId).eq('brands.organization_id', auth.organizationId)@@ -3111,6 +3117,8 @@ export async function getActionFor(impact: action.impact,status: action.status,outcome: action.outcome ?? null,+ net_of_control: netOfControl(action.validation),+ dismiss_reason: dismissReasonOf(action.dismiss_reason),payload,kpi_keys: action.kpi_keys ?? [],assignee: action.assignee_id@@ -3281,6 +3289,27 @@ export interface ActionHistoryRow {final: boolean;/** The day after closing its latest reading was taken on; null before one. */reading_day: number | null;+ /** Its change net of the brand's prompts it didn't touch (learning B2); null when not netted. */+ net_of_control: McpNetOfControl | null;+ /** Why it was dismissed, as the person said (learning A5); null otherwise. */+ dismiss_reason: ActionDismissReason | null;+}++/** An action's change net of a control basket's (learning B2). */+export interface McpNetOfControl {+ /** The control: the prompts of the same topics, or the brand's others. */+ basis: 'topics' | 'brand';+ control_prompts: number;+ /** Per metric: a rate's move in points, a count's in percent, minus the control's. */+ metrics: { metric: string; net: number; unit: 'points' | 'percent' }[];+}++/** The net result the validation sweep kept, if it could net one. */+function netOfControl(validation: unknown): McpNetOfControl | null {+ const control = controlNetOf(validation as Parameters<typeof controlNetOf>[0]);+ return control+ ? { basis: control.basis, control_prompts: control.prompts, metrics: control.net }+ : null;}interface ValidationMetric {@@ -3307,7 +3336,7 @@ export async function listActionHistoryFor(const { data, error } = await supabaseAdmin.from('actions').select(- 'id, action_no, category, kind, impact, status, outcome, validation, created_at, completed_at',+ 'id, action_no, category, kind, impact, status, outcome, validation, dismiss_reason, created_at, completed_at',).eq('brand_id', params.brandId).in('status', ['completed', 'dismissed'])@@ -3348,6 +3377,8 @@ export async function listActionHistoryFor(validation?.final === true ||(days.length === 0 && outcome != null && outcome !== 'pending_measurement'),reading_day: days.length ? Math.max(...days) : null,+ net_of_control: netOfControl(validation),+ dismiss_reason: dismissReasonOf(r.dismiss_reason),};});}diff --git a/web/src/lib/mcp/learning.test.ts b/web/src/lib/mcp/learning.test.tsnew file mode 100644index 000000000..ca5823b03--- /dev/null+++ b/web/src/lib/mcp/learning.test.ts@@ -0,0 +1,156 @@+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { McpAuthContext } from '@/lib/mcp-auth';++/**+ * get_action_scorecard (learning B3): what each kind of action did at the+ * brand, as the History tab's scorecard reads it — its own actions only, a+ * success rate only from three verdicts, the median change in percent and+ * the reason it is most often dismissed for.+ */++let brandFound = true;+let rpcRows: unknown[] = [];+let rpcError: { message: string } | null = null;+const rpcCalls: [string, Record<string, unknown>][] = [];++vi.mock('@/lib/supabase/admin', () => ({+ supabaseAdmin: {+ from: () => {+ const chain = {+ select: () => chain,+ eq: () => chain,+ maybeSingle: async () => ({ data: brandFound ? { id: 'brand-1' } : null, error: null }),+ };+ return chain;+ },+ rpc: async (fn: string, args: Record<string, unknown>) => {+ rpcCalls.push([fn, args]);+ return { data: rpcError ? null : rpcRows, error: rpcError };+ },+ },+}));++const { getActionScorecardFor } = await import('./learning');+const { createMcpServer } = await import('./server');++const auth: McpAuthContext = {+ userId: 'user-1',+ email: null,+ organizationId: 'org-1',+ apiKeyId: 'key-1',+};++const rpcRow = (over: Record<string, unknown>) => ({+ kind: 'content_opportunity',+ completed: 0,+ improved: 0,+ mixed: 0,+ no_change: 0,+ declined: 0,+ not_measurable: 0,+ pending: 0,+ final: 0,+ median_change: null,+ dismissed: 0,+ dismiss_reasons: {},+ ...over,+});++beforeEach(() => {+ brandFound = true;+ rpcRows = [];+ rpcError = null;+ rpcCalls.length = 0;+});++describe('getActionScorecardFor', () => {+ it("reads the brand's scorecard by kind, busiest first", async () => {+ rpcRows = [+ rpcRow({ kind: 'citation_gap', completed: 1, improved: 1 }),+ rpcRow({+ completed: 5,+ improved: 3,+ mixed: 1,+ no_change: 1,+ final: 4,+ median_change: '0.1525',+ dismissed: 3,+ dismiss_reasons: { not_relevant: 1, already_done: 2 },+ }),+ ];+ const scorecard = await getActionScorecardFor(auth, {+ brandId: 'brand-1',+ since: '2026-09-01T00:00:00Z',+ });+ expect(rpcCalls).toEqual([+ ['action_scorecard', { p_brand_id: 'brand-1', p_since: '2026-09-01T00:00:00.000Z' }],+ ]);+ expect(scorecard).toEqual([+ {+ kind: 'content_opportunity',+ completed: 5,+ improved: 3,+ mixed: 1,+ no_change: 1,+ declined: 0,+ not_measurable: 0,+ pending: 0,+ final: 4,+ success_rate: 60,+ median_change_percent: 15.3,+ dismissed: 3,+ dismiss_reasons: { not_relevant: 1, already_done: 2 },+ top_dismiss_reason: 'already_done',+ },+ expect.objectContaining({+ kind: 'citation_gap',+ // One verdict is too few to say.+ success_rate: null,+ median_change_percent: null,+ top_dismiss_reason: null,+ }),+ ]);+ });++ it('passes the start to the database as an ISO timestamp, whatever form it came in', async () => {+ await getActionScorecardFor(auth, { brandId: 'brand-1', since: '1' });+ expect(rpcCalls[0][1]).toEqual({+ p_brand_id: 'brand-1',+ p_since: new Date('1').toISOString(),+ });+ });++ it('reads every action without a start', async () => {+ await getActionScorecardFor(auth, { brandId: 'brand-1' });+ expect(rpcCalls[0][1]).toEqual({ p_brand_id: 'brand-1', p_since: null });+ });++ it("answers null for another organization's brand, without reading it", async () => {+ brandFound = false;+ expect(await getActionScorecardFor(auth, { brandId: 'brand-2' })).toBeNull();+ expect(rpcCalls).toEqual([]);+ });++ it('fails when the scorecard cannot be read', async () => {+ rpcError = { message: 'statement timeout' };+ await expect(getActionScorecardFor(auth, { brandId: 'brand-1' })).rejects.toThrow(+ 'statement timeout',+ );+ });+});++describe('the get_action_scorecard tool', () => {+ it('lists as a read-only tool with a title', async () => {+ 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();+ const tool = tools.find((t) => t.name === 'get_action_scorecard');+ expect(tool?.title).toBe('What worked, by kind of action');+ expect(tool?.annotations).toMatchObject({ readOnlyHint: true, openWorldHint: false });+ });+});diff --git a/web/src/lib/mcp/learning.ts b/web/src/lib/mcp/learning.tsnew file mode 100644index 000000000..391eeeae7--- /dev/null+++ b/web/src/lib/mcp/learning.ts@@ -0,0 +1,82 @@+import { supabaseAdmin } from '@/lib/supabase/admin';+import type { McpAuthContext } from '@/lib/mcp-auth';+import {+ parseScorecardRow,+ sortScorecard,+ successRate,+ topDismissReason,+ type ScorecardRow,+} from '@/lib/action-center/scorecard';+import type { ActionDismissReason } from '@/lib/action-center/registry';+import { brandInOrg } from './data';++/**+ * What worked at a brand, by kind of action (learning B3), for the MCP tool+ * get_action_scorecard and its REST mirror: the History tab's scorecard.+ */++/** One kind of action at the brand, as the History tab's scorecard reads it. */+export interface McpScorecardRow {+ kind: string;+ completed: number;+ improved: number;+ mixed: number;+ no_change: number;+ declined: number;+ not_measurable: number;+ /** Completed, not read yet. */+ pending: number;+ /** Completed and read for the last time, a month after it closed. */+ final: number;+ /** improved ÷ the results with a verdict, 0–100; null below three verdicts. */+ success_rate: number | null;+ /** The median change in each one's main metric, in percent (15 is +15%). */+ median_change_percent: number | null;+ dismissed: number;+ /** Dismissals by the reason given; `none` when none was. */+ dismiss_reasons: Partial<Record<ActionDismissReason | 'none', number>>;+ /** The reason given most often for dismissing this kind. */+ top_dismiss_reason: ActionDismissReason | null;+}++function mcpScorecardRow(row: ScorecardRow): McpScorecardRow {+ return {+ kind: row.kind,+ completed: row.completed,+ improved: row.improved,+ mixed: row.mixed,+ no_change: row.noChange,+ declined: row.declined,+ not_measurable: row.notMeasurable,+ pending: row.pending,+ final: row.final,+ success_rate: successRate(row),+ median_change_percent:+ row.medianChange == null ? null : Math.round(row.medianChange * 1000) / 10,+ dismissed: row.dismissed,+ dismiss_reasons: row.dismissReasons,+ top_dismiss_reason: topDismissReason(row),+ };+}++/**+ * The brand's actions raised since `since` (every one without it), summed+ * by kind in the database (action_scorecard, 00368), busiest kinds first.+ * Null for a brand outside the key's organization.+ */+export async function getActionScorecardFor(+ auth: McpAuthContext,+ params: { brandId: string; since?: string },+): Promise<McpScorecardRow[] | null> {+ if (!(await brandInOrg(auth, params.brandId))) return null;+ const { data, error } = await supabaseAdmin.rpc('action_scorecard', {+ p_brand_id: params.brandId,+ p_since: params.since ? new Date(params.since).toISOString() : null,+ });+ if (error) throw new Error(error.message);+ return sortScorecard(+ ((data ?? []) as unknown[])+ .map(parseScorecardRow)+ .filter((row): row is ScorecardRow => row !== null),+ ).map(mcpScorecardRow);+}diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex a14c7200a..ff21f508e 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -77,6 +77,7 @@ import {import { MENTION_SENTIMENTS, MENTION_SORTS } from '@/lib/mentions-list';import { gateWriteTools } from './subscription-gate';import { getAiUsageFor, getMeFor } from './account';+import { getActionScorecardFor } from './learning';/*** Build a fresh MCP server bound to a single authenticated request.@@ -1190,7 +1191,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {'get_action',{description:- 'Get one Action Center action in full: its priority (score, level and the facts it rests on), its payload (the prompts, pages, competitors or numbers it is about), the signals that triggered it, its task list and its event trail. Each task carries `mode` (who carries it out: system, agent, human or human_or_agent) and `permission` (read, write or execute). Read both before proposing to act on a task — anything beyond read needs a human to approve it in the dashboard. A task is described by `title` when someone wrote one, otherwise by `task_key` with `title_params`. `details` says what the task carries beyond that, or null: `url` (the exact page), `where` (the page, prompt, platform, domain or competitor), `why` (the evidence), `change` (`before`, null when it adds text, and `after`), `how` (the steps), `done_when` (the check that closes it), `check` (how it is checked: auto, the page fetched again; rerun, the prompts run again; manual, a person confirms), `type` (content, on_page, technical, outreach, pr or product), `effort` and `role`; a task sent from the Improve tab also carries `body`, `platform`, `platform_label` and `sources`; `sent_to_content` (the opportunity it became) and `sent_to_webhook` say where it was sent. With `format` "markdown" or "csv" it returns the action as the dashboard\'s Copy Data and Export CSV write it instead (everything its tabs show, labelled in English, dates in UTC): Markdown to paste into a doc, ticket or another agent, CSV with a row per affected item, task and signal.',+ 'Get one Action Center action in full: its outcome, its change net of the control (`net_of_control`: per metric, its move minus that of the brand\u2019s prompts it didn\u2019t touch; null when not netted) and why it was dismissed (`dismiss_reason`), its priority (score, level and the facts it rests on), its payload (the prompts, pages, competitors or numbers it is about), the signals that triggered it, its task list and its event trail. Each task carries `mode` (who carries it out: system, agent, human or human_or_agent) and `permission` (read, write or execute). Read both before proposing to act on a task — anything beyond read needs a human to approve it in the dashboard. A task is described by `title` when someone wrote one, otherwise by `task_key` with `title_params`. `details` says what the task carries beyond that, or null: `url` (the exact page), `where` (the page, prompt, platform, domain or competitor), `why` (the evidence), `change` (`before`, null when it adds text, and `after`), `how` (the steps), `done_when` (the check that closes it), `check` (how it is checked: auto, the page fetched again; rerun, the prompts run again; manual, a person confirms), `type` (content, on_page, technical, outreach, pr or product), `effort` and `role`; a task sent from the Improve tab also carries `body`, `platform`, `platform_label` and `sources`; `sent_to_content` (the opportunity it became) and `sent_to_webhook` say where it was sent. With `format` "markdown" or "csv" it returns the action as the dashboard\'s Copy Data and Export CSV write it instead (everything its tabs show, labelled in English, dates in UTC): Markdown to paste into a doc, ticket or another agent, CSV with a row per affected item, task and signal.',inputSchema: {action_id: relaxedUuid.describe('Action UUID, from list_actions or list_action_history.'),format: z@@ -1270,7 +1271,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {'list_action_history',{description:- 'List closed Action Center actions (completed or dismissed) for a brand with their measured result, most recently closed first. `outcome` is the verdict (improved, mixed when its metrics moved both ways or only some of a fix\u2019s pages pass, no_meaningful_change, declined, not_measurable, or pending_measurement while the first week after it closed is still open; read again 14 and 30 days on, the day-30 reading final) and `results` holds the before/after values the validation sweep measured. `reading_day` is the day after closing the latest reading was taken on (7, 14 or 30; null before the first, or for one measured once before readings began). Until `final` is true, the outcome is a reading so far (day 7 or 14), not the result. Use this to answer "did what we did last month work?".',+ 'List closed Action Center actions (completed or dismissed) for a brand with their measured result, most recently closed first. `outcome` is the verdict (improved, mixed when its metrics moved both ways or only some of a fix\u2019s pages pass, no_meaningful_change, declined, not_measurable, or pending_measurement while the first week after it closed is still open; read again 14 and 30 days on, the day-30 reading final) and `results` holds the before/after values the validation sweep measured. `reading_day` is the day after closing the latest reading was taken on (7, 14 or 30; null before the first, or for one measured once before readings began). Until `final` is true, the outcome is a reading so far (day 7 or 14), not the result. `net_of_control` is its change net of the brand\u2019s prompts it didn\u2019t touch (`basis` topics or brand, `control_prompts`, and per metric `net`: a rate\u2019s move in points or a count\u2019s in percent, minus the control\u2019s), so a market-wide swing doesn\u2019t read as its effect; null when it couldn\u2019t be netted. `dismiss_reason` says why a dismissed one was turned down (not_relevant, already_done, wrong_data, not_now), or null. Use this to answer "did what we did last month work?"; for what each kind of action does at the brand overall, use get_action_scorecard.',inputSchema: {brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),limit: z@@ -1795,5 +1796,34 @@ export function createMcpServer(auth: McpAuthContext): McpServer {},);+ // ─── What worked: the brand's scorecard by kind of action (B3) ───++ server.registerTool(+ 'get_action_scorecard',+ {+ title: 'What worked, by kind of action',+ description:+ "What each kind of Action Center action did at this brand, as the History tab's scorecard shows it: one row per kind (e.g. content_opportunity, citation_gap, prompt_improve) of the brand's own actions raised since `date_from` (all of them without it), busiest first. Each row: completed, and their results (improved, mixed, no_change, declined, not_measurable, pending — not read yet — and final, read for the last time a month on); success_rate (improved ÷ results with a verdict, 0–100; null below three verdicts, too few to say); median_change_percent (the median change in each one's main metric, +15 is +15%); dismissed, dismiss_reasons by reason (not_relevant, already_done, wrong_data, not_now, none) and top_dismiss_reason. Use it for \"which kinds of work pay off here?\" and to lead with the kinds that do; never compare brands with it.",+ inputSchema: {+ brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),+ date_from: z+ .string()+ .refine((value) => Number.isFinite(Date.parse(value)), 'Not a date')+ .optional()+ .describe(+ 'Only actions raised on or after this ISO timestamp, e.g. 2026-05-01T00:00:00Z. All of them when absent.',+ ),+ },+ annotations: { readOnlyHint: true, openWorldHint: false },+ },+ async (args) => {+ const scorecard = await getActionScorecardFor(auth, {+ brandId: args.brand_id,+ since: args.date_from,+ });+ return scorecard ? json(scorecard) : notFound('Brand');+ },+ );+return server;}diff --git a/web/src/lib/mcp/subscription-gate.test.ts b/web/src/lib/mcp/subscription-gate.test.tsindex e5da5ea0f..070f5652e 100644--- a/web/src/lib/mcp/subscription-gate.test.ts+++ b/web/src/lib/mcp/subscription-gate.test.ts@@ -78,7 +78,7 @@ describe('the MCP tools on a read-only workspace', () => {const client = await connect();const { tools } = await client.listTools();const names = tools.map((tool) => tool.name);- expect(names.filter(isReadTool)).toHaveLength(38);+ expect(names.filter(isReadTool)).toHaveLength(39);expect(names.filter((name) => !isReadTool(name)).sort()).toEqual(['accept_prompt_suggestion','accept_topic_suggestion',