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.

fix(mcp): keep briefs and Improve actions to admins and managers (#1770)

Cihan7e0765f81047
diff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdx
index bdd009c4a..312cdb441 100644
--- a/docs/guides/mcp-server.mdx
+++ b/docs/guides/mcp-server.mdx
@@ -314,7 +314,7 @@ curl "https://app.ansvisor.com/api/mcp/mentions/summary?brand_id=<brand_id>&plat
| `list_content_opportunities` | Content gaps ranked by opportunity score — where the brand is losing visibility. | |
| `get_content_plan` | The Content plan, as **Content → Plan** ranks it by the Priority Score: what to create, optimize or protect next, why, the score's parts, the draft already being written and the rows marked a priority. Over 7, 30 or 90 days; optional `card`. | |
| `get_content_opportunity` | Full details for one opportunity, including metrics, intent, competitors, and any existing brief. | |
-| `generate_content_brief` | Generate or overwrite an AI content brief for an opportunity (LLM cost/latency). | **yes** |
+| `generate_content_brief` | Generate or overwrite an AI content brief for an opportunity (LLM cost/latency). | **yes** (admin, manager) |
| `update_opportunity_status` | Move an opportunity through workflow states (`new`, `reviewed`, `sent`, `in_progress`, `done`, `dismissed`). Dismissing one, or moving a dismissed one back, needs an admin or a manager. | **yes** |
The plan is also available over REST with the same `ans_` key: `GET /api/mcp/content-plan?brand_id=<brand_id>&days=30`, with `card` as an optional query parameter.
@@ -378,7 +378,7 @@ The Shelf, Readiness and What AI says need a plan with Product Visibility (Growt
| `list_task_reviews` | Tasks waiting for review, as the **Needs review** tab shows them: tasks an AI writer gave without the exact page, the change, Done when or how it is checked, each with `missing` (the fields to fill). Admins and managers only. | |
| `approve_task_review` | Approve one onto its action's task list, as the tab's **Approve** does: the fields given (`url`, `change`, `done_when`, `check`, and optionally `title`, `where`, `why`, `how`) replace what was written, and all four must be filled. | **yes** (admin, manager) |
| `dismiss_task_review` | Dismiss one, as the tab's **Dismiss** does: it never reaches its action. | **yes** (admin, manager) |
-| `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** |
+| `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** (admin, manager) |
The scorecard is also available over REST: `GET /api/mcp/action-scorecard?brand_id=<brand_id>&date_from=2026-09-01`.
The review queue is also available over REST: `GET /api/mcp/task-reviews?brand_id=<brand_id>`, and `POST /api/mcp/task-reviews/<id>/approve` (the fields as JSON) or `/dismiss`.
@@ -418,10 +418,10 @@ answers in plain English using the returned data.
A key acts as the person who created it, with their role in the
organization. `get_me` returns it. Day-to-day work is open to every role:
-reading, drafts and suggestions in the Content Editor, briefs, Site Audits,
-task progress and an opportunity's progress. Adding prompts or topics,
-reviewing tasks and dismissing are for admins and managers. Dismissing a prompt suggestion is open
-to analysts too. The tools marked with roles above refuse anyone else before
+reading, drafts and suggestions in the Content Editor, Site Audits, task
+progress and an opportunity's progress. Adding prompts or topics, reviewing
+tasks, dismissing, and work that costs AI (briefs and Improve actions) are for
+admins and managers. Dismissing a prompt suggestion is open to analysts too. The tools marked with roles above refuse anyone else before
they change anything. The call fails with text like this:
```text
diff --git a/web/src/app/api/mcp/content-opportunities/[id]/brief/route.test.ts b/web/src/app/api/mcp/content-opportunities/[id]/brief/route.test.ts
new file mode 100644
index 000000000..d23c3727e
--- /dev/null
+++ b/web/src/app/api/mcp/content-opportunities/[id]/brief/route.test.ts
@@ -0,0 +1,50 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * POST /api/mcp/content-opportunities/[id]/brief: a brief costs AI, so a key
+ * whose user isn't an admin or a manager (generateBriefFor's own check)
+ * answers 403 with the reason.
+ */
+
+const { generateBriefFor } = vi.hoisted(() => ({ generateBriefFor: vi.fn() }));
+vi.mock('@/lib/mcp-auth', () => ({
+ authenticateMcpRequest: vi.fn(async () => ({
+ userId: 'user-1',
+ email: null,
+ organizationId: 'org-1',
+ role: 'analyst',
+ apiKeyId: 'key-1',
+ })),
+}));
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));
+vi.mock('@/lib/mcp/data', () => ({ generateBriefFor }));
+
+const { POST } = await import('./route');
+const { RoleRequiredError, MANAGER_ROLES } = await import('@/lib/mcp/role-gate');
+
+const post = () =>
+ POST(
+ new Request('http://localhost/api/mcp/content-opportunities/opp-1/brief', { method: 'POST' }),
+ {
+ params: Promise.resolve({ id: 'opp-1' }),
+ },
+ );
+
+beforeEach(() => {
+ generateBriefFor.mockReset();
+});
+
+describe('POST /api/mcp/content-opportunities/[id]/brief', () => {
+ it("answers 403 with the reason for an analyst's key", async () => {
+ generateBriefFor.mockRejectedValue(new RoleRequiredError(MANAGER_ROLES, 'analyst'));
+ const res = await post();
+ expect(res.status).toBe(403);
+ expect(await res.json()).toMatchObject({ error: 'forbidden', code: 'role_required' });
+ });
+
+ it('answers the brief otherwise', async () => {
+ generateBriefFor.mockResolvedValue({ brief: { title: 'x' } });
+ expect((await post()).status).toBe(200);
+ });
+});
diff --git a/web/src/app/api/mcp/content-opportunities/[id]/brief/route.ts b/web/src/app/api/mcp/content-opportunities/[id]/brief/route.ts
index cb99674d4..b2d5d9cd9 100644
--- a/web/src/app/api/mcp/content-opportunities/[id]/brief/route.ts
+++ b/web/src/app/api/mcp/content-opportunities/[id]/brief/route.ts
@@ -8,7 +8,8 @@ import { failedCallResponse } from '@/lib/mcp/subscription-gate';
*
* Parallel REST surface for the `generate_content_brief` MCP tool — same
* data-layer function, same ownership guarantee. Always re-generates;
- * cached reads belong on GET /api/mcp/content-opportunities/[id].
+ * cached reads belong on GET /api/mcp/content-opportunities/[id]. 403
+ * unless the key's user is an admin or a manager.
*/
export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
const auth = await authenticateMcpRequest(req);
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
index ba6374e42..97f557054 100644
--- a/web/src/app/api/mcp/prompts/[id]/improve-action/route.ts
+++ b/web/src/app/api/mcp/prompts/[id]/improve-action/route.ts
@@ -10,7 +10,8 @@ import { failedCallResponse } from '@/lib/mcp/subscription-gate';
* 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.
+ * The server validates the range and suggestions and checks the plan. 403
+ * unless the key's user is an admin or a manager.
*/
export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
const auth = await authenticateMcpRequest(req);
diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.ts
index 3a713e046..c38105f59 100644
--- a/web/src/lib/mcp/data.ts
+++ b/web/src/lib/mcp/data.ts
@@ -1029,6 +1029,8 @@ export async function generateBriefFor(
opportunityId: string,
): Promise<GeneratedBrief | null> {
if (!auth.organizationId) return null;
+ // Generating costs AI: an admin's or a manager's, as in the dashboard.
+ requireManager(auth);
// Ownership check first — wrong-org or missing id returns null with no
// outbound call, so no LLM cost or data leak for an attacker probing ids.
@@ -3549,6 +3551,8 @@ export async function createImproveActionFor(
input: CreateImproveActionInput,
): Promise<CreatedImproveAction | null> {
if (!auth.organizationId) return null;
+ // Improve costs AI: an admin's or a manager's, as in the dashboard.
+ requireManager(auth);
const { data: ownership } = await supabaseAdmin
.from('prompts')
diff --git a/web/src/lib/mcp/role-gate.test.ts b/web/src/lib/mcp/role-gate.test.ts
index 2bda108b5..8456edfdd 100644
--- a/web/src/lib/mcp/role-gate.test.ts
+++ b/web/src/lib/mcp/role-gate.test.ts
@@ -138,6 +138,46 @@ describe('the tools only an admin or a manager may call', () => {
});
});
+describe('the tools that cost AI: generate_content_brief and create_improve_action', () => {
+ const improveArgs = {
+ prompt_id: ID,
+ range: { preset: '7d', from: '2026-10-21T00:00:00.000Z' },
+ idempotency_key: 'key-000001',
+ suggestions: [{ id: 's1', platform: 'perplexity-web', title: 'Publish a comparison page' }],
+ };
+ const call = (client: Client) =>
+ Promise.all([
+ client.callTool({ name: 'generate_content_brief', arguments: { opportunity_id: ID } }),
+ client.callTool({ name: 'create_improve_action', arguments: improveArgs }),
+ ]);
+
+ for (const role of ['analyst', 'agency_partner'] as const) {
+ it(`refuse an ${role} before anything is read or generated`, async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+ try {
+ const client = await connect(role);
+ for (const result of await call(client)) {
+ expect(result.isError).toBe(true);
+ expect(text(result)).toMatch(/^Only an admin or a manager can do this/);
+ }
+ expect(calls).toEqual([]);
+ expect(fetchMock).not.toHaveBeenCalled();
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+ }
+
+ it('let a manager through to the opportunity and the prompt', async () => {
+ const client = await connect('manager');
+ const [brief, improve] = await call(client);
+ expect(text(brief)).not.toMatch(/^Only an admin/);
+ expect(text(improve)).toBe('Prompt not found');
+ expect(calls.map((c) => c.table)).toEqual(['content_opportunities', 'prompts']);
+ });
+});
+
describe('dismiss_prompt_suggestion', () => {
it('refuses an agency partner', async () => {
const client = await connect('agency_partner');
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index d9e67753e..60bc41589 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -678,7 +678,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
{
title: 'Generate a content brief',
description:
- 'Generate a fresh AI-powered content brief for a specific content opportunity. WARNING: this triggers an LLM call (cost + latency) and ALWAYS re-generates, overwriting any existing brief on the opportunity. Use only after list_content_opportunities + get_content_opportunity and only when the user has explicitly asked to generate or refresh a brief for a specific opportunity — never as part of exploratory queries. To read an existing brief without an LLM call, use get_content_opportunity instead.',
+ 'Generate a fresh AI-powered content brief for a specific content opportunity. WARNING: this triggers an LLM call (cost + latency) and ALWAYS re-generates, overwriting any existing brief on the opportunity. Use only after list_content_opportunities + get_content_opportunity and only when the user has explicitly asked to generate or refresh a brief for a specific opportunity — never as part of exploratory queries. To read an existing brief without an LLM call, use get_content_opportunity instead. Needs an admin or a manager (get_me returns the role).',
inputSchema: {
opportunity_id: relaxedUuid.describe(
'Content opportunity UUID, from list_content_opportunities.',
@@ -1497,7 +1497,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
{
title: 'Send Improve suggestions to Action Center',
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.',
+ '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. Needs an admin or a manager (get_me returns the role).',
inputSchema: {
prompt_id: relaxedUuid.describe('Prompt UUID, from list_prompts.'),
range: z