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(mcp): add a create_improve_action tool for sending Improve suggestions to Action Center (#1014)

Cihan39fb02d7b432
diff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdx
index 57296f674..4754bf32f 100644
--- a/docs/guides/mcp-server.mdx
+++ b/docs/guides/mcp-server.mdx
@@ -220,7 +220,7 @@ instead.
## Available tools
-The MCP server exposes **28 tools**. Descriptions below match
+The MCP server exposes **29 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 user
intent, not during exploratory queries.
@@ -287,6 +287,7 @@ intent, not during exploratory queries.
| `list_signals` | Detected changes (visibility, citations, traffic) with before/after values and linked `action_id`. | |
| `list_action_history` | Closed actions with measured outcomes and before/after validation results. | |
| `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** |
New tools may ship between releases — see `server.ts` and the [project roadmap](https://github.com/ansvisor/ansvisor#whats-next).
diff --git a/server/src/routes/prompts-improve-send.test.js b/server/src/routes/prompts-improve-send.test.js
new file mode 100644
index 000000000..9bf20ab0a
--- /dev/null
+++ b/server/src/routes/prompts-improve-send.test.js
@@ -0,0 +1,175 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * sendImproveActionForKeyUser is what the internal endpoint behind the MCP
+ * `create_improve_action` tool runs. An API key has no session, so these pin
+ * that the plan check happens before anything is read or written, that the
+ * key's user goes through the same org check as the dashboard, and that the
+ * action is created from the stored set like the Improve tab's send.
+ */
+
+class PlanLimitError extends Error {
+ constructor(message, statusCode = 403) {
+ super(message);
+ this.name = 'PlanLimitError';
+ this.statusCode = statusCode;
+ }
+}
+
+const enforceFeature = vi.fn();
+const sendImproveToActionCenter = vi.fn();
+const liveImproveSends = vi.fn();
+
+let reads = [];
+let rows = {};
+
+function builder(table) {
+ let op = 'select';
+ const chain = {
+ select: () => chain,
+ update: () => {
+ op = 'update';
+ return chain;
+ },
+ eq: () => chain,
+ maybeSingle: async () => {
+ reads.push(table);
+ return { data: rows[table] ?? null, error: null };
+ },
+ single: async () => {
+ reads.push(table);
+ if (op === 'update') return { data: { ...rows[table], updated: true }, error: null };
+ return { data: rows[table] ?? null, error: null };
+ },
+ };
+ return chain;
+}
+
+vi.mock('../config/supabase.js', () => ({ default: { from: (table) => builder(table) } }));
+vi.mock('../lib/plan-guard.js', () => ({
+ PlanLimitError,
+ enforceFeature,
+ enforceImproveQuota: vi.fn(),
+ getImproveQuotaStatus: vi.fn(),
+ requireFeature: () => (req, res, next) => next(),
+}));
+vi.mock('../lib/action-center/from-prompt-improve.js', () => ({
+ sendImproveToActionCenter,
+ liveImproveSends,
+}));
+vi.mock('../lib/ai-provider.js', () => ({ resolveModel: vi.fn() }));
+vi.mock('../lib/gsc-suggestions.js', () => ({ getGscSuggestionCandidates: vi.fn() }));
+vi.mock('../lib/ga-suggestions.js', () => ({ getGaSuggestionCandidates: vi.fn() }));
+
+const { sendImproveActionForKeyUser } = await import('./prompts.js');
+
+const body = {
+ preset: '7d',
+ from: '2026-10-06T00:00:00.000Z',
+ to: '2026-10-13T00:00:00.000Z',
+ region: '',
+ idempotencyKey: 'mcp-key-0001',
+ suggestions: [
+ {
+ id: 's1',
+ platform: 'perplexity-web',
+ title: 'Publish a comparison page',
+ body: 'Cover the alternatives Perplexity cites.',
+ sources: [{ type: 'domain', ref: 'example.com' }],
+ },
+ ],
+};
+
+describe('sendImproveActionForKeyUser', () => {
+ beforeEach(() => {
+ reads = [];
+ rows = {
+ prompts: { id: 'p1', text: 'best crm', prompt_sets: { brand_id: 'b1' } },
+ brands: { id: 'b1', organization_id: 'org-1' },
+ profiles: { organization_id: 'org-1', role: 'member' },
+ prompt_improve_suggestions: {
+ id: 'set-1',
+ range_key: '7d',
+ region: '',
+ generated_at: '2026-10-13T08:00:00.000Z',
+ sent_actions: [],
+ },
+ };
+ enforceFeature.mockReset().mockResolvedValue({});
+ sendImproveToActionCenter
+ .mockReset()
+ .mockResolvedValue({ actionId: 'a1', actionNo: 7, created: true });
+ liveImproveSends.mockReset().mockResolvedValue({ latest: null, sentSuggestionIds: ['s1'] });
+ });
+
+ it('refuses a plan without prompt_improve before reading anything', async () => {
+ enforceFeature.mockRejectedValue(new PlanLimitError('Your Starter plan does not include it'));
+
+ await expect(
+ sendImproveActionForKeyUser({ promptId: 'p1', userId: 'u1', body }),
+ ).rejects.toMatchObject({ statusCode: 403 });
+ expect(enforceFeature).toHaveBeenCalledWith('u1', 'prompt_improve');
+ expect(reads).toEqual([]);
+ expect(sendImproveToActionCenter).not.toHaveBeenCalled();
+ });
+
+ it('rejects a key user from another org with 403', async () => {
+ rows.profiles = { organization_id: 'org-2', role: 'member' };
+
+ await expect(
+ sendImproveActionForKeyUser({ promptId: 'p1', userId: 'u1', body }),
+ ).rejects.toMatchObject({ status: 403 });
+ expect(sendImproveToActionCenter).not.toHaveBeenCalled();
+ });
+
+ it('rejects bad suggestions with 400 and the validation details', async () => {
+ const bad = { ...body, suggestions: [{ ...body.suggestions[0], platform: 'nope' }] };
+
+ await expect(
+ sendImproveActionForKeyUser({ promptId: 'p1', userId: 'u1', body: bad }),
+ ).rejects.toMatchObject({ status: 400, details: expect.any(Array) });
+ expect(reads).toEqual([]);
+ });
+
+ it('asks for suggestions first when the range has no stored set', async () => {
+ rows.prompt_improve_suggestions = null;
+
+ await expect(
+ sendImproveActionForKeyUser({ promptId: 'p1', userId: 'u1', body }),
+ ).rejects.toMatchObject({ status: 404, message: /Generate suggestions/ });
+ expect(sendImproveToActionCenter).not.toHaveBeenCalled();
+ });
+
+ it('creates the action as the key user and records the send', async () => {
+ const result = await sendImproveActionForKeyUser({ promptId: 'p1', userId: 'u1', body });
+
+ expect(sendImproveToActionCenter).toHaveBeenCalledWith(
+ expect.objectContaining({
+ prompt: expect.objectContaining({ id: 'p1' }),
+ brandId: 'b1',
+ idempotencyKey: 'mcp-key-0001',
+ suggestions: [expect.objectContaining({ id: 's1', platform: 'perplexity-web' })],
+ panelLink: expect.stringContaining('positions=p1'),
+ userId: 'u1',
+ }),
+ );
+ expect(liveImproveSends).toHaveBeenCalledWith(expect.objectContaining({ updated: true }));
+ expect(result).toEqual({
+ actionId: 'a1',
+ actionNo: 7,
+ created: true,
+ taskCount: 1,
+ sent: { latest: null, sentSuggestionIds: ['s1'] },
+ });
+ });
+
+ it('does not record the send again when the key was already used', async () => {
+ rows.prompt_improve_suggestions.sent_actions = [{ actionId: 'a1' }];
+ sendImproveToActionCenter.mockResolvedValue({ actionId: 'a1', actionNo: 7, created: false });
+
+ const result = await sendImproveActionForKeyUser({ promptId: 'p1', userId: 'u1', body });
+
+ expect(result.created).toBe(false);
+ expect(liveImproveSends).toHaveBeenCalledWith(expect.not.objectContaining({ updated: true }));
+ });
+});
diff --git a/server/src/routes/prompts.js b/server/src/routes/prompts.js
index ec43224c8..5fa6d8d94 100644
--- a/server/src/routes/prompts.js
+++ b/server/src/routes/prompts.js
@@ -7,6 +7,7 @@ import { classifyPromptIntent } from '../lib/intent-extraction.js';
import { getLanguageName } from '../lib/languages.js';
import {
PlanLimitError,
+ enforceFeature,
enforceImproveQuota,
getImproveQuotaStatus,
requireFeature,
@@ -1134,71 +1135,105 @@ function positionsPanelLink(promptId, range) {
return `/dashboard/prompts?${params.toString()}`;
}
-router.post('/:promptId/improve/action', requireFeature('prompt_improve'), async (req, res) => {
- try {
- const range = parseImproveRange(req.body);
- const parsed = sendImproveSchema.safeParse(req.body);
- if (!parsed.success) {
- return res.status(400).json({ error: 'Invalid suggestions', details: parsed.error.issues });
- }
- const promptId = req.params.promptId;
- const { prompt, brandId } = await loadImprovePrompt(promptId, req.user.id);
+/**
+ * Sends the selected suggestions for `userId`, who must already have passed the
+ * prompt_improve plan check. Shared by the dashboard route below and the
+ * internal endpoint the web MCP layer calls (`create_improve_action`), so both
+ * create the action, record the send and dedupe on the idempotency key alike.
+ * Errors carry a `status` (400 bad input, 403/404 access, 404 no set yet).
+ */
+export async function sendImproveAction({ promptId, userId, body }) {
+ const range = parseImproveRange(body);
+ const parsed = sendImproveSchema.safeParse(body);
+ if (!parsed.success) {
+ const err = new Error('Invalid suggestions');
+ err.status = 400;
+ err.details = parsed.error.issues;
+ throw err;
+ }
+ const { prompt, brandId } = await loadImprovePrompt(promptId, userId);
+
+ const { data: set } = await supabaseAdmin
+ .from('prompt_improve_suggestions')
+ .select('*')
+ .eq('prompt_id', promptId)
+ .eq('range_key', range.key)
+ .eq('region', range.region)
+ .maybeSingle();
+ if (!set) {
+ const err = new Error('Generate suggestions for this range first');
+ err.status = 404;
+ throw err;
+ }
- const { data: set } = await supabaseAdmin
+ const { suggestions, idempotencyKey } = parsed.data;
+ const result = await sendImproveToActionCenter({
+ prompt,
+ brandId,
+ set,
+ suggestions,
+ idempotencyKey,
+ panelLink: positionsPanelLink(promptId, range),
+ userId,
+ });
+
+ // Record the send on the set, once, so the panel can show it after a reload.
+ const sends = set.sent_actions ?? [];
+ let updated = set;
+ if (!sends.some((s) => s.actionId === result.actionId)) {
+ const { data, error } = await supabaseAdmin
.from('prompt_improve_suggestions')
+ .update({
+ sent_actions: [
+ ...sends,
+ {
+ actionId: result.actionId,
+ actionNo: result.actionNo,
+ sentAt: new Date().toISOString(),
+ setGeneratedAt: set.generated_at,
+ suggestionIds: suggestions.map((s) => s.id),
+ },
+ ],
+ })
+ .eq('id', set.id)
.select('*')
- .eq('prompt_id', promptId)
- .eq('range_key', range.key)
- .eq('region', range.region)
- .maybeSingle();
- if (!set) {
- return res.status(404).json({ error: 'Generate suggestions for this range first' });
- }
+ .single();
+ if (error) throw error;
+ updated = data;
+ }
- const { suggestions, idempotencyKey } = parsed.data;
- const result = await sendImproveToActionCenter({
- prompt,
- brandId,
- set,
- suggestions,
- idempotencyKey,
- panelLink: positionsPanelLink(promptId, range),
- userId: req.user.id,
- });
+ return {
+ actionId: result.actionId,
+ actionNo: result.actionNo,
+ created: result.created,
+ taskCount: suggestions.length,
+ sent: await liveImproveSends(updated),
+ };
+}
- // Record the send on the set, once, so the panel can show it after a reload.
- const sends = set.sent_actions ?? [];
- let updated = set;
- if (!sends.some((s) => s.actionId === result.actionId)) {
- const { data, error } = await supabaseAdmin
- .from('prompt_improve_suggestions')
- .update({
- sent_actions: [
- ...sends,
- {
- actionId: result.actionId,
- actionNo: result.actionNo,
- sentAt: new Date().toISOString(),
- setGeneratedAt: set.generated_at,
- suggestionIds: suggestions.map((s) => s.id),
- },
- ],
- })
- .eq('id', set.id)
- .select('*')
- .single();
- if (error) throw error;
- updated = data;
- }
+/**
+ * The same send for an MCP API key (`create_improve_action`): the key carries
+ * no session, so the prompt_improve plan check that `requireFeature` runs for
+ * the dashboard route happens here, against the key's user.
+ */
+export async function sendImproveActionForKeyUser({ promptId, userId, body }) {
+ await enforceFeature(userId, 'prompt_improve');
+ return sendImproveAction({ promptId, userId, body });
+}
- return res.json({
- actionId: result.actionId,
- actionNo: result.actionNo,
- created: result.created,
- taskCount: suggestions.length,
- sent: await liveImproveSends(updated),
- });
+router.post('/:promptId/improve/action', requireFeature('prompt_improve'), async (req, res) => {
+ try {
+ return res.json(
+ await sendImproveAction({
+ promptId: req.params.promptId,
+ userId: req.user.id,
+ body: req.body,
+ }),
+ );
} catch (error) {
+ if (error.details) {
+ return res.status(400).json({ error: error.message, details: error.details });
+ }
req.log.error({ err: error }, 'prompt improve send error');
return res
.status(error.status || 500)
diff --git a/server/src/server.js b/server/src/server.js
index 5814083ee..001eee828 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -27,6 +27,7 @@ import { parseScraperResponse } from './lib/cloro-scraper.js';
import { handleScraperResult } from './lib/cloro-result-handler.js';
import { verifyCloroWebhook } from './lib/cloro-webhook-verify.js';
import { generateBriefForOpportunity } from './routes/content.js';
+import { sendImproveActionForKeyUser } from './routes/prompts.js';
import { startSiteAuditForBrand } from './routes/audits.js';
import { getSiteAuditQuotaStatus } from './lib/plan-guard.js';
import { recountBrandCitations } from './lib/citation-recount.js';
@@ -389,6 +390,46 @@ app.get('/api/internal/site-audit-quota', async (req, res) => {
}
});
+// --- Internal Improve send endpoint (CRON_SECRET auth, called by web MCP layer) ---
+// The web MCP layer verifies the caller's `ans_` API key org owns the prompt
+// before reaching here and passes the key's user, so this endpoint trusts the
+// secret, checks the user's plan includes prompt_improve and creates the
+// Action Center action exactly as the Improve tab's "Send Actions" does.
+app.post('/api/internal/prompts/:promptId/improve/action', async (req, res) => {
+ const secret = req.headers.authorization?.replace('Bearer ', '');
+ if (!process.env.CRON_SECRET || secret !== process.env.CRON_SECRET) {
+ return res.status(401).json({ success: false, message: 'Unauthorized' });
+ }
+
+ try {
+ const { userId, ...body } = req.body || {};
+ if (!userId) {
+ return res.status(400).json({ success: false, message: 'userId is required' });
+ }
+ const result = await sendImproveActionForKeyUser({
+ promptId: req.params.promptId,
+ userId,
+ body,
+ });
+ return res.json({ success: true, ...result });
+ } catch (err) {
+ // PlanLimitError (plan without prompt_improve / inactive subscription)
+ // carries a statusCode — surface it so the MCP layer can relay it.
+ if (err.statusCode) {
+ return res
+ .status(err.statusCode)
+ .json({ success: false, error: 'plan_limit', message: err.message });
+ }
+ if (err.status) {
+ return res
+ .status(err.status)
+ .json({ success: false, message: err.message, details: err.details });
+ }
+ req.log.error({ err }, 'internal improve send error');
+ return res.status(500).json({ success: false, message: err.message });
+ }
+});
+
// --- Internal citation-recount endpoint (CRON_SECRET auth, called by the web
// layer whenever a brand's domain list changes) ---
// Recomputes prompt_results.citation_count for the brand against its current
diff --git a/web/src/app/api/mcp/prompts/[id]/improve-action/route.ts b/web/src/app/api/mcp/prompts/[id]/improve-action/route.ts
new file mode 100644
index 000000000..61071acc1
--- /dev/null
+++ b/web/src/app/api/mcp/prompts/[id]/improve-action/route.ts
@@ -0,0 +1,56 @@
+import { NextResponse } from 'next/server';
+import { authenticateMcpRequest } from '@/lib/mcp-auth';
+import { createImproveActionFor, type CreateImproveActionInput } from '@/lib/mcp/data';
+
+/**
+ * POST /api/mcp/prompts/[id]/improve-action
+ *
+ * REST mirror of the `create_improve_action` MCP tool — same data-layer
+ * function, same ownership check. Body:
+ * `{ "range": { "preset": "7d", "from": "…", "to": "…", "region": "US" },
+ * "idempotency_key": "…", "suggestions": [{ "id", "platform", "title", "body", "sources" }] }`.
+ * The server validates the range and suggestions and checks the plan.
+ */
+export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
+ const auth = await authenticateMcpRequest(req);
+ if (auth instanceof NextResponse) return auth;
+
+ const { id } = await params;
+ if (!id) {
+ return NextResponse.json({ error: 'id is required' }, { status: 400 });
+ }
+
+ let body: { range?: unknown; idempotency_key?: unknown; suggestions?: unknown };
+ try {
+ body = (await req.json()) as typeof body;
+ } catch {
+ return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
+ }
+
+ const range = body.range as CreateImproveActionInput['range'] | undefined;
+ if (!range || typeof range.preset !== 'string' || typeof range.from !== 'string') {
+ return NextResponse.json({ error: 'range with preset and from is required' }, { status: 400 });
+ }
+ if (typeof body.idempotency_key !== 'string') {
+ return NextResponse.json({ error: 'idempotency_key is required' }, { status: 400 });
+ }
+ if (!Array.isArray(body.suggestions) || body.suggestions.length === 0) {
+ return NextResponse.json({ error: 'suggestions must be a non-empty array' }, { status: 400 });
+ }
+
+ try {
+ const result = await createImproveActionFor(auth, {
+ promptId: id,
+ range,
+ idempotencyKey: body.idempotency_key,
+ suggestions: body.suggestions as CreateImproveActionInput['suggestions'],
+ });
+ if (!result) {
+ return NextResponse.json({ error: 'Prompt not found' }, { status: 404 });
+ }
+ return NextResponse.json(result);
+ } catch (err) {
+ const message = err instanceof Error ? err.message : 'Failed';
+ return NextResponse.json({ error: message }, { status: 500 });
+ }
+}
diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.ts
index 9847aa4b7..645a570f4 100644
--- a/web/src/lib/mcp/data.ts
+++ b/web/src/lib/mcp/data.ts
@@ -2825,3 +2825,102 @@ export async function updateTaskStatusFor(
updated_at: data.updated_at ?? updatedAt,
};
}
+
+export const IMPROVE_PRESETS = ['24h', '7d', '30d', '90d', 'custom'] as const;
+export const IMPROVE_SOURCE_TYPES = [
+ 'fanout',
+ 'domain',
+ 'answer',
+ 'competitor_url',
+ 'brand_page',
+] as const;
+
+export interface CreateImproveActionInput {
+ promptId: string;
+ range: {
+ preset: (typeof IMPROVE_PRESETS)[number];
+ from: string;
+ to?: string;
+ region?: string;
+ };
+ idempotencyKey: string;
+ suggestions: Array<{
+ id: string;
+ platform: string;
+ title: string;
+ body?: string;
+ sources?: Array<{ type: (typeof IMPROVE_SOURCE_TYPES)[number]; ref: string }>;
+ }>;
+}
+
+export interface CreatedImproveAction {
+ actionId: string;
+ actionNo: number;
+ created: boolean;
+ taskCount: number;
+}
+
+/**
+ * Create a `prompt_improve` Action Center action from Improve suggestions —
+ * the MCP counterpart of the Improve tab's "Send Actions".
+ *
+ * Org-ownership of the prompt is verified *first* via supabaseAdmin — a
+ * wrong-org or missing id returns `null` (→ 404 upstream) with no outbound
+ * call. Only then do we call the internal endpoint at
+ * `${API_BASE_URL}/api/internal/prompts/:id/improve/action` with
+ * `Authorization: Bearer ${CRON_SECRET}` and the key's user — same pattern as
+ * `generateBriefFor`. The server checks the prompt_improve plan feature for
+ * that user and dedupes on the idempotency key, so a retried call returns the
+ * action the first one created (`created: false`).
+ */
+export async function createImproveActionFor(
+ auth: McpAuthContext,
+ input: CreateImproveActionInput,
+): Promise<CreatedImproveAction | null> {
+ if (!auth.organizationId) return null;
+
+ const { data: ownership } = await supabaseAdmin
+ .from('prompts')
+ .select('id, prompt_sets!inner(brands!inner(organization_id))')
+ .eq('id', input.promptId)
+ .eq('prompt_sets.brands.organization_id', auth.organizationId)
+ .maybeSingle();
+ if (!ownership) return null;
+
+ const cronSecret = process.env.CRON_SECRET;
+ if (!cronSecret) {
+ throw new Error('CRON_SECRET must be configured for MCP Improve actions');
+ }
+
+ const res = await fetch(`${API_BASE_URL}/api/internal/prompts/${input.promptId}/improve/action`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${cronSecret}`,
+ },
+ body: JSON.stringify({
+ userId: auth.userId,
+ preset: input.range.preset,
+ from: input.range.from,
+ to: input.range.to,
+ region: input.range.region ?? '',
+ idempotencyKey: input.idempotencyKey,
+ suggestions: input.suggestions,
+ }),
+ });
+
+ if (!res.ok) {
+ // Surface the server's message (plan without Improve, no suggestions for
+ // this range yet, invalid suggestion) so the agent can relay it.
+ const body = (await res.json().catch(() => null)) as { message?: string } | null;
+ throw new Error(body?.message ?? `Internal Improve endpoint returned ${res.status}`);
+ }
+
+ const body = (await res.json()) as CreatedImproveAction;
+ return {
+ actionId: body.actionId,
+ actionNo: body.actionNo,
+ created: body.created,
+ taskCount: body.taskCount,
+ };
+}
diff --git a/web/src/lib/mcp/improve-action.test.ts b/web/src/lib/mcp/improve-action.test.ts
new file mode 100644
index 000000000..9622dc035
--- /dev/null
+++ b/web/src/lib/mcp/improve-action.test.ts
@@ -0,0 +1,136 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { McpAuthContext } from '@/lib/mcp-auth';
+
+/**
+ * create_improve_action is the MCP way to send Improve suggestions to Action
+ * Center. These pin what the web layer owns: a prompt outside the caller's org
+ * never reaches the server, the send goes out as the API key's user with the
+ * range and suggestions the server expects, and a server refusal (plan, no
+ * set for the range) reaches the agent in the server's words.
+ */
+
+let promptOwned = true;
+const filters: Array<[string, unknown]> = [];
+
+vi.mock('@/lib/supabase/admin', () => ({
+ supabaseAdmin: {
+ from: () => {
+ const chain = {
+ select: () => chain,
+ eq: (column: string, value: unknown) => {
+ filters.push([column, value]);
+ return chain;
+ },
+ maybeSingle: async () => ({ data: promptOwned ? { id: 'p1' } : null, error: null }),
+ };
+ return chain;
+ },
+ },
+}));
+
+const { createImproveActionFor } = await import('./data');
+
+const auth: McpAuthContext = {
+ userId: 'user-1',
+ email: null,
+ organizationId: 'org-1',
+ apiKeyId: 'key-1',
+};
+
+const input = {
+ promptId: 'p1',
+ range: {
+ preset: '7d' as const,
+ from: '2026-10-06T00:00:00.000Z',
+ to: '2026-10-13T00:00:00.000Z',
+ },
+ idempotencyKey: 'mcp-key-0001',
+ suggestions: [
+ {
+ id: 's1',
+ platform: 'perplexity-web',
+ title: 'Publish a comparison page',
+ sources: [{ type: 'domain' as const, ref: 'example.com' }],
+ },
+ ],
+};
+
+const fetchMock = vi.fn();
+
+describe('createImproveActionFor', () => {
+ beforeEach(() => {
+ promptOwned = true;
+ filters.length = 0;
+ vi.stubEnv('CRON_SECRET', 'secret');
+ vi.stubGlobal('fetch', fetchMock);
+ fetchMock.mockReset();
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+ });
+
+ it('returns null without calling the server for a prompt outside the caller org', async () => {
+ promptOwned = false;
+ expect(await createImproveActionFor(auth, input)).toBeNull();
+ expect(filters).toContainEqual(['prompt_sets.brands.organization_id', 'org-1']);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('returns null for a key without an organization', async () => {
+ expect(await createImproveActionFor({ ...auth, organizationId: null }, input)).toBeNull();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('sends the range and suggestions to the internal endpoint as the key user', async () => {
+ fetchMock.mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ success: true,
+ actionId: 'a1',
+ actionNo: 7,
+ created: true,
+ taskCount: 1,
+ sent: { latest: null, sentSuggestionIds: ['s1'] },
+ }),
+ { status: 200 },
+ ),
+ );
+
+ const result = await createImproveActionFor(auth, input);
+
+ expect(result).toEqual({ actionId: 'a1', actionNo: 7, created: true, taskCount: 1 });
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toMatch(/\/api\/internal\/prompts\/p1\/improve\/action$/);
+ expect(init.headers.Authorization).toBe('Bearer secret');
+ expect(JSON.parse(init.body)).toEqual({
+ userId: 'user-1',
+ preset: '7d',
+ from: '2026-10-06T00:00:00.000Z',
+ to: '2026-10-13T00:00:00.000Z',
+ region: '',
+ idempotencyKey: 'mcp-key-0001',
+ suggestions: input.suggestions,
+ });
+ });
+
+ it("relays the server's refusal message", async () => {
+ fetchMock.mockResolvedValue(
+ new Response(
+ JSON.stringify({ success: false, message: 'Generate suggestions for this range first' }),
+ { status: 404 },
+ ),
+ );
+
+ await expect(createImproveActionFor(auth, input)).rejects.toThrow(
+ 'Generate suggestions for this range first',
+ );
+ });
+
+ it('refuses to run without CRON_SECRET', async () => {
+ vi.stubEnv('CRON_SECRET', '');
+ await expect(createImproveActionFor(auth, input)).rejects.toThrow(/CRON_SECRET/);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index 810c975a0..30fbc5668 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -33,6 +33,9 @@ import {
listActionsFor,
listSignalsFor,
updateTaskStatusFor,
+ IMPROVE_PRESETS,
+ IMPROVE_SOURCE_TYPES,
+ createImproveActionFor,
} from './data';
/**
@@ -1030,5 +1033,81 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
},
);
+ server.registerTool(
+ 'create_improve_action',
+ {
+ description:
+ 'Send Improve suggestions for one prompt to Action Center as a new `prompt_improve` action, one human task per suggestion — the same as the Positions panel\'s Improve tab "Send Actions". The prompt must already have an Improve suggestion set for this exact range (generated in the dashboard); otherwise it errors with "Generate suggestions for this range first". Needs a plan that includes Improve. Reuse the same idempotency_key when retrying: a repeated call returns the action the first one created (created: false) instead of a duplicate. It is a write logged under the API key\'s user — only fire on explicit user intent, never as part of an exploratory query.',
+ inputSchema: {
+ prompt_id: relaxedUuid.describe('Prompt UUID, from list_prompts.'),
+ range: z
+ .object({
+ preset: z
+ .enum(IMPROVE_PRESETS)
+ .describe(
+ 'The range the suggestion set was generated for: 24h, 7d, 30d, 90d or custom.',
+ ),
+ from: z
+ .string()
+ .describe('ISO timestamp lower bound; for custom, its date is part of the set key.'),
+ to: z
+ .string()
+ .optional()
+ .describe('ISO timestamp upper bound; for custom, its date is part of the set key.'),
+ region: z
+ .string()
+ .optional()
+ .describe('Region code the set was generated for (e.g. "US"); omit for all regions.'),
+ })
+ .describe('The Positions panel range the suggestion set belongs to.'),
+ idempotency_key: z
+ .string()
+ .min(8)
+ .max(64)
+ .describe('Unique per send (e.g. a UUID); reuse it only to retry the same send.'),
+ suggestions: z
+ .array(
+ z.object({
+ id: z.string().min(1).max(120).describe('Suggestion id from the set, or your own.'),
+ platform: z
+ .string()
+ .describe(
+ 'Platform id: chatgpt-web, perplexity-web, google-aio, google-aimode, gemini-web, copilot-web, grok-web or claude.',
+ ),
+ title: z.string().min(1).max(200).describe('Task title.'),
+ body: z.string().max(1000).optional().describe('What to do, in a sentence or two.'),
+ sources: z
+ .array(
+ z.object({ type: z.enum(IMPROVE_SOURCE_TYPES), ref: z.string().min(1).max(300) }),
+ )
+ .max(6)
+ .optional()
+ .describe('Evidence behind the suggestion.'),
+ }),
+ )
+ .min(1)
+ .max(50)
+ .describe('The suggestions to send, in task order.'),
+ },
+ },
+ async (args) => {
+ const result = await createImproveActionFor(auth, {
+ promptId: args.prompt_id,
+ range: args.range,
+ idempotencyKey: args.idempotency_key,
+ suggestions: args.suggestions,
+ });
+ if (!result) {
+ return {
+ content: [{ type: 'text', text: 'Prompt not found' }],
+ isError: true,
+ };
+ }
+ return {
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
+ };
+ },
+ );
+
return server;
}