Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Add MCP cleanup tools for saved keywords, reports, and audits (#646)
Ben Senescu9aa1977bf0d9
diff --git a/src/server/features/sam/samChatTools.ts b/src/server/features/sam/samChatTools.tsindex 01bd8178..165fe0d6 100644--- a/src/server/features/sam/samChatTools.ts+++ b/src/server/features/sam/samChatTools.ts@@ -23,6 +23,7 @@ import {runSiteAuditTool,} from "@/server/mcp/tools/site-audit-tools";import { listSavedKeywordsTool } from "@/server/mcp/tools/list-saved-keywords";+import { removeSavedKeywordsTool } from "@/server/mcp/tools/remove-saved-keywords";import { buildUpdateProjectContextTool } from "@/server/mcp/tools/project-context";import {getGoogleAnalyticsAudienceBreakdownTool,@@ -363,6 +364,7 @@ export function buildSamMcpTools(// a read-only context block, so get_project_context would just re-fetch it.update_project_context: adaptTool(buildUpdateProjectContextTool("sam")),list_saved_keywords: adaptTool(listSavedKeywordsTool),+ remove_saved_keywords: adaptTool(removeSavedKeywordsTool),research_keywords: adaptTool(researchKeywordsTool),save_keywords: adaptTool(saveKeywordsTool),get_domain_overview: adaptTool(getDomainOverviewTool),diff --git a/src/server/mcp/server.ts b/src/server/mcp/server.tsindex 9a1f9c01..78d53143 100644--- a/src/server/mcp/server.ts+++ b/src/server/mcp/server.ts@@ -42,6 +42,7 @@ import {updateProjectContextTool,} from "@/server/mcp/tools/project-context";import { listSavedKeywordsTool } from "@/server/mcp/tools/list-saved-keywords";+import { removeSavedKeywordsTool } from "@/server/mcp/tools/remove-saved-keywords";import {findSerpCompetitorsTool,getGoogleBusinessQuestionsTool,@@ -58,11 +59,13 @@ import {listBusinessCategoriesTool,} from "@/server/mcp/tools/local-seo-tools";import {+ deleteReportTool,getReportTool,listReportsTool,saveReportTool,} from "@/server/mcp/tools/report-tools";import {+ deleteReportTemplateTool,listReportTemplatesTool,saveReportTemplateTool,} from "@/server/mcp/tools/report-template-tools";@@ -78,6 +81,10 @@ import {getAuditStatusTool,runSiteAuditTool,} from "@/server/mcp/tools/site-audit-tools";+import {+ deleteSiteAuditTool,+ listSiteAuditsTool,+} from "@/server/mcp/tools/site-audit-cleanup-tools";import { whoamiTool } from "@/server/mcp/tools/whoami";type ToolSchema = z.ZodType | z.ZodRawShape;@@ -176,6 +183,7 @@ export function createOpenSeoMcpServer(authProps: McpProps) {register(getProjectContextTool);register(updateProjectContextTool);register(listSavedKeywordsTool);+ register(removeSavedKeywordsTool);register(researchKeywordsTool);register(saveKeywordsTool);register(getDomainOverviewTool);@@ -214,14 +222,18 @@ export function createOpenSeoMcpServer(authProps: McpProps) {register(getGoogleAnalyticsSiteSearchTool);register(getGoogleAnalyticsAudienceBreakdownTool);register(runSiteAuditTool);+ register(listSiteAuditsTool);+ register(deleteSiteAuditTool);register(getAuditStatusTool);register(getAuditIssuesTool);register(getAuditPagesTool);register(saveReportTool);register(listReportsTool);register(getReportTool);+ register(deleteReportTool);register(listReportTemplatesTool);register(saveReportTemplateTool);+ register(deleteReportTemplateTool);return server;}diff --git a/src/server/mcp/tools/cleanup-tools.test.ts b/src/server/mcp/tools/cleanup-tools.test.tsnew file mode 100644index 00000000..39abc04f--- /dev/null+++ b/src/server/mcp/tools/cleanup-tools.test.ts@@ -0,0 +1,239 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { z } from "zod";+import { removeSavedKeywordsTool } from "./remove-saved-keywords";+import { deleteReportTool } from "./report-tools";+import { deleteReportTemplateTool } from "./report-template-tools";+import {+ deleteSiteAuditTool,+ listSiteAuditsTool,+} from "./site-audit-cleanup-tools";+import { makeToolContext } from "./tool-test-support";++const mocks = vi.hoisted(() => ({+ getProjectForOrganization: vi.fn(),+ deleteReport: vi.fn(),+ removeSavedKeywords: vi.fn(),+ deleteTemplate: vi.fn(),+ getAuditForProject: vi.fn(),+ getAuditsByProject: vi.fn(),+ deleteAuditForProject: vi.fn(),+ terminate: vi.fn(),+ status: vi.fn(),+ destroyScratchpad: vi.fn(),+}));++vi.mock("cloudflare:workers", () => ({+ env: {+ SITE_AUDIT_WORKFLOW: { get: async () => mocks },+ AUDIT_ENGINE: { destroyScratchpad: mocks.destroyScratchpad },+ },+}));+vi.mock("@/server/features/projects/services/ProjectService", () => ({+ ProjectService: {+ getProjectForOrganization: mocks.getProjectForOrganization,+ },+}));+vi.mock(+ "@/server/features/keywords/repositories/KeywordResearchRepository",+ () => ({+ KeywordResearchRepository: mocks,+ }),+);+vi.mock("@/server/features/reports/repositories/ReportRepository", () => ({+ ReportRepository: mocks,+}));+vi.mock(+ "@/server/features/reports/repositories/ReportTemplateRepository",+ () => ({+ ReportTemplateRepository: mocks,+ }),+);+vi.mock("@/server/features/audit/repositories/AuditRepository", () => ({+ AuditRepository: mocks,+}));+vi.mock("@/server/lib/posthog", () => ({ captureServerEvent: vi.fn() }));++beforeEach(() => {+ vi.resetAllMocks();+ mocks.getProjectForOrganization.mockResolvedValue({ id: "project_1" });+ mocks.deleteReport.mockResolvedValue(true);+ mocks.deleteTemplate.mockResolvedValue(true);+ mocks.getAuditForProject.mockResolvedValue({+ id: "audit_1",+ status: "completed",+ });+ mocks.getAuditsByProject.mockResolvedValue([]);+});++const context = makeToolContext();+const deletes = [+ {+ tool: deleteReportTool,+ call: () =>+ deleteReportTool.handler(+ { projectId: "project_1", reportId: "report_1" },+ context,+ ),+ storage: mocks.deleteReport,+ scopedArgs: ["project_1", "report_1"],+ },+ {+ tool: deleteReportTemplateTool,+ call: () =>+ deleteReportTemplateTool.handler(+ { projectId: "project_1", templateId: "template_1" },+ context,+ ),+ storage: mocks.deleteTemplate,+ scopedArgs: ["project_1", "template_1"],+ },+ {+ tool: deleteSiteAuditTool,+ call: () =>+ deleteSiteAuditTool.handler(+ { projectId: "project_1", auditId: "audit_1" },+ context,+ ),+ storage: mocks.deleteAuditForProject,+ scopedArgs: ["audit_1", "project_1"],+ },+];++describe.each(deletes)("$tool.name", ({ tool, call, storage, scopedArgs }) => {+ it("deletes only within the authorized project", async () => {+ expect((await call()).structuredContent.deleted).toBe(true);+ expect(storage).toHaveBeenCalledWith(...scopedArgs);+ });++ it("refuses an inaccessible project before deleting anything", async () => {+ mocks.getProjectForOrganization.mockResolvedValue(null);+ await expect(call()).rejects.toMatchObject({ code: "FORBIDDEN" });+ expect(storage).not.toHaveBeenCalled();+ });++ it("refuses missing IDs or IDs belonging to another project", async () => {+ mocks.deleteReport.mockResolvedValue(false);+ mocks.deleteTemplate.mockResolvedValue(false);+ mocks.getAuditForProject.mockResolvedValue(null);+ await expect(call()).rejects.toMatchObject({ code: "NOT_FOUND" });+ });++ it("requires an explicit target and advertises destructive behavior", () => {+ expect(+ z.object(tool.config.inputSchema).safeParse({ projectId: "project_1" })+ .success,+ ).toBe(false);+ expect(tool.config.annotations.destructiveHint).toBe(true);+ });+});++describe("site audit cleanup", () => {+ it("lists empty history without starting or deleting an audit", async () => {+ const result = await listSiteAuditsTool.handler(+ { projectId: "project_1" },+ context,+ );+ expect(result.structuredContent.audits).toEqual([]);+ expect(mocks.getAuditsByProject).toHaveBeenCalledWith("project_1");+ expect(mocks.deleteAuditForProject).not.toHaveBeenCalled();+ });++ it("preserves the dashboard's role restriction", async () => {+ await expect(+ deleteSiteAuditTool.handler(+ { projectId: "project_1", auditId: "audit_1" },+ makeToolContext({ role: "member" }),+ ),+ ).rejects.toMatchObject({ code: "FORBIDDEN" });+ expect(mocks.getAuditForProject).not.toHaveBeenCalled();+ expect(mocks.deleteAuditForProject).not.toHaveBeenCalled();+ });++ it("stops a running workflow before deleting its results and scratchpad", async () => {+ mocks.getAuditForProject.mockResolvedValue({+ id: "audit_1",+ status: "running",+ workflowInstanceId: "workflow_1",+ });+ await deleteSiteAuditTool.handler(+ { projectId: "project_1", auditId: "audit_1" },+ context,+ );+ expect(mocks.terminate).toHaveBeenCalledOnce();+ expect(mocks.terminate.mock.invocationCallOrder[0]).toBeLessThan(+ mocks.deleteAuditForProject.mock.invocationCallOrder[0],+ );+ expect(mocks.destroyScratchpad).toHaveBeenCalledWith("audit_1");+ });++ it("keeps data when a workflow cannot be stopped", async () => {+ vi.spyOn(console, "error").mockImplementation(() => {});+ mocks.getAuditForProject.mockResolvedValue({+ id: "audit_1",+ status: "running",+ workflowInstanceId: "workflow_1",+ });+ mocks.terminate.mockRejectedValue(new Error("Still running"));+ mocks.status.mockResolvedValue({ status: "running" });+ await expect(+ deleteSiteAuditTool.handler(+ { projectId: "project_1", auditId: "audit_1" },+ context,+ ),+ ).rejects.toMatchObject({ code: "CONFLICT" });+ expect(mocks.deleteAuditForProject).not.toHaveBeenCalled();+ });+});++describe("remove_saved_keywords", () => {+ it("passes exact row IDs to the scoped service and reports actual deletions", async () => {+ mocks.removeSavedKeywords.mockResolvedValue(1);+ const ids = ["saved_1", "saved_1", "missing_or_foreign"];+ const result = await removeSavedKeywordsTool.handler(+ { projectId: "project_1", savedKeywordIds: ids },+ context,+ );+ expect(mocks.removeSavedKeywords).toHaveBeenCalledWith(ids, "project_1");+ expect(result.structuredContent).toMatchObject({+ projectId: "project_1",+ requested: 3,+ deletedCount: 1,+ });+ expect(+ removeSavedKeywordsTool.config.outputSchema.safeParse(+ result.structuredContent,+ ).success,+ ).toBe(true);+ });++ it("refuses inaccessible projects before deletion", async () => {+ mocks.getProjectForOrganization.mockResolvedValue(null);+ await expect(+ removeSavedKeywordsTool.handler(+ { projectId: "project_1", savedKeywordIds: ["saved_1"] },+ context,+ ),+ ).rejects.toMatchObject({ code: "FORBIDDEN" });+ expect(mocks.removeSavedKeywords).not.toHaveBeenCalled();+ });++ it("reports zero when no requested row belongs to the project", async () => {+ mocks.removeSavedKeywords.mockResolvedValue(0);+ const result = await removeSavedKeywordsTool.handler(+ { projectId: "project_1", savedKeywordIds: ["missing_or_foreign"] },+ context,+ );+ expect(result.structuredContent.deletedCount).toBe(0);+ });++ it.each([undefined, [], [""], Array.from({ length: 2001 }, () => "saved_1")])(+ "rejects a missing, empty, invalid, or oversized target list (%#)",+ (savedKeywordIds) => {+ expect(+ z+ .object(removeSavedKeywordsTool.config.inputSchema)+ .safeParse({ projectId: "project_1", savedKeywordIds }).success,+ ).toBe(false);+ },+ );+});diff --git a/src/server/mcp/tools/list-saved-keywords.ts b/src/server/mcp/tools/list-saved-keywords.tsindex d69bb6cb..0489faf3 100644--- a/src/server/mcp/tools/list-saved-keywords.ts+++ b/src/server/mcp/tools/list-saved-keywords.ts@@ -8,9 +8,10 @@ import { projectIdSchema } from "@/server/mcp/schemas";import type { SavedKeywordRow, SavedKeywordTagSummary } from "@/types/keywords";// The app reads the full SavedKeywordRow through its own server functions. The-// MCP row keeps only what an agent acts on: ids, timestamps, tag colors, and the-// monthly trend array were ~60% of the bytes and never used.+// MCP row includes the saved row ID for removal, while omitting timestamps,+// tag colors, and the monthly trend array to keep the response small.const savedKeywordOutputSchema = z.looseObject({+ id: z.string(),keyword: z.string(),searchVolume: z.number().nullable(),keywordDifficulty: z.number().nullable(),@@ -24,6 +25,7 @@ function toMcpRow(row: SavedKeywordRow,): z.infer<typeof savedKeywordOutputSchema> {return {+ id: row.id,keyword: row.keyword,searchVolume: row.searchVolume,keywordDifficulty: row.keywordDifficulty,@@ -62,7 +64,7 @@ export const listSavedKeywordsTool = {config: {title: "List saved keywords",description:- "Lists keywords saved to a project (with cached metrics like search volume, difficulty, CPC, and tags if available). Uses no credits — reads from OpenSEO's database, no DataForSEO call. Use tag filters when the user asks for a saved segment; multiple tags match ANY tag.",+ "Lists keywords saved to a project (with cached metrics like search volume, difficulty, CPC, and tags if available). Uses no credits — reads from OpenSEO's database, no DataForSEO call. Each row includes its saved-keyword ID for remove_saved_keywords. Use tag filters when the user asks for a saved segment; multiple tags match ANY tag.",inputSchema,outputSchema: z.looseObject({rows: z.array(savedKeywordOutputSchema),@@ -100,7 +102,7 @@ export const listSavedKeywordsTool = {row.tags.length > 0? ` tags:${row.tags.map((tag) => tag.name).join(",")}`: "";- return `- ${row.keyword} vol:${row.searchVolume ?? "?"} kd:${row.keywordDifficulty ?? "?"} cpc:${row.cpc != null ? `$${row.cpc.toFixed(2)}` : "?"}${tagText}`;+ return `- ${row.keyword} id:${row.id} vol:${row.searchVolume ?? "?"} kd:${row.keywordDifficulty ?? "?"} cpc:${row.cpc != null ? `$${row.cpc.toFixed(2)}` : "?"}${tagText}`;}).join("\n");return mcpResponse({diff --git a/src/server/mcp/tools/project-context.test.ts b/src/server/mcp/tools/project-context.test.tsindex dec3c4ee..7bd93a82 100644--- a/src/server/mcp/tools/project-context.test.ts+++ b/src/server/mcp/tools/project-context.test.ts@@ -16,6 +16,10 @@ const mocks = vi.hoisted(() => ({listKeyPages: vi.fn(),listResearchLog: vi.fn(),listTemplates: vi.fn(),+ deleteSection: vi.fn(),+ deleteCompetitors: vi.fn(),+ deleteKeyPages: vi.fn(),+ deleteResearchLogEntries: vi.fn(),}));vi.mock("cloudflare:workers", () => ({ env: {} }));@@ -51,6 +55,47 @@ beforeEach(() => {});describe("update_project_context", () => {+ it("removes each kind of context entry within the authorized project", async () => {+ await updateProjectContextTool.handler(+ {+ projectId: "project_1",+ updates: [+ { section: "current_goal", content: "" },+ { deleteCustomSection: "old-findings" },+ { removeCompetitors: ["https://www.Example.com/"] },+ { removeKeyPages: ["https://Example.com/pricing#old"] },+ { removeResearchLog: ["research_1"] },+ ],+ },+ makeToolContext(),+ );+ expect(mocks.deleteSection).toHaveBeenCalledWith(+ expect.anything(),+ "project_1",+ "current_goal",+ );+ expect(mocks.deleteSection).toHaveBeenCalledWith(+ expect.anything(),+ "project_1",+ "custom:old-findings",+ );+ expect(mocks.deleteCompetitors).toHaveBeenCalledWith(+ expect.anything(),+ "project_1",+ ["example.com"],+ );+ expect(mocks.deleteKeyPages).toHaveBeenCalledWith(+ expect.anything(),+ "project_1",+ ["https://example.com/pricing"],+ );+ expect(mocks.deleteResearchLogEntries).toHaveBeenCalledWith(+ expect.anything(),+ "project_1",+ ["research_1"],+ );+ });+// Provenance is the contract: a write arriving over MCP must be attributable// to MCP in the UI, and silently recording it as a user edit would be// invisible everywhere else.diff --git a/src/server/mcp/tools/project-context.ts b/src/server/mcp/tools/project-context.tsindex 090f45bd..19eebfe2 100644--- a/src/server/mcp/tools/project-context.ts+++ b/src/server/mcp/tools/project-context.ts@@ -74,7 +74,7 @@ const updateInputSchema = {// The batch cap lives with the server function's schema so both entry points// accept exactly the same patch list.updates: updateProjectContextSchema.shape.updates.describe(- "Patch ops, applied in order. Empty section content clears the section; adds upsert by domain/url; research-log entries are date-stamped by the server.",+ 'Patch ops, applied in order. Clear a standard section with {section: "current_goal", content: ""}; delete a custom section with {deleteCustomSection: "slug"}; removeCompetitors takes domains, removeKeyPages takes URLs, and removeResearchLog takes entry IDs from the project context. Adds upsert by domain/url; research-log entries are date-stamped by the server.',),} as const;@@ -89,7 +89,7 @@ export function buildUpdateProjectContextTool(author: ContextAuthor) {config: {title: "Update project context",description:- "Writes to a project's shared memory so the app, SAM, and other agents see it. Uses no credits. Send a list of patch ops; sections are prose (~4,000 chars max), competitors and key pages are curated shortlists (100 max each), and appendResearchLog records what research was bought so nobody re-buys it. Confirm facts with the user before storing them.",+ "Adds, edits, or deletes a project's shared memory so the app, SAM, and other agents see it. Uses no credits. Use the current project context to find the entries to remove. Send patch ops to clear sections, deleteCustomSection, removeCompetitors, removeKeyPages, or removeResearchLog. Sections are prose (~4,000 chars max), competitors and key pages are curated shortlists (100 max each), and appendResearchLog records research already bought. Report templates are managed separately. Confirm facts with the user before storing them.",inputSchema: updateInputSchema,outputSchema: contextOutputSchema,annotations: {diff --git a/src/server/mcp/tools/remove-saved-keywords.ts b/src/server/mcp/tools/remove-saved-keywords.tsnew file mode 100644index 00000000..a7403ecf--- /dev/null+++ b/src/server/mcp/tools/remove-saved-keywords.ts@@ -0,0 +1,60 @@+import { z } from "zod";+import { KeywordResearchService } from "@/server/features/keywords/services/KeywordResearchService";+import { buildProjectMeta } from "@/server/mcp/context";+import { mcpResponse } from "@/server/mcp/formatters";+import { optionalMetaOutputSchema } from "@/server/mcp/output-schemas";+import { withMcpProjectAuth } from "@/server/mcp/project-auth";+import { projectIdSchema } from "@/server/mcp/schemas";+import { removeSavedKeywordsSchema } from "@/types/schemas/keywords";++const inputSchema = {+ projectId: projectIdSchema,+ savedKeywordIds: removeSavedKeywordsSchema.shape.savedKeywordIds.describe(+ "Saved-keyword row IDs to delete. Use the `id` values returned by list_saved_keywords.",+ ),+} as const;++type Args = z.infer<z.ZodObject<typeof inputSchema>>;++export const removeSavedKeywordsTool = {+ name: "remove_saved_keywords",+ config: {+ title: "Remove saved keywords",+ description:+ "Permanently deletes keywords from a project's saved-keywords list by their row ID. Uses no credits — does not call DataForSEO. Missing, foreign-project, and repeated IDs are ignored; deletedCount reports rows actually removed. This does not affect Rank Tracking; use remove_rank_tracking_keywords for that list separately.",+ inputSchema,+ outputSchema: z+ .object({+ projectId: z.string(),+ requested: z.number(),+ deletedCount: z.number(),+ ...optionalMetaOutputSchema,+ })+ .passthrough(),+ annotations: {+ readOnlyHint: false,+ openWorldHint: false,+ destructiveHint: true,+ },+ },+ handler: withMcpProjectAuth(async (args: Args, context) => {+ const requested = args.savedKeywordIds.length;+ const result = await KeywordResearchService.removeSavedKeywords(+ args.projectId,+ { projectId: args.projectId, savedKeywordIds: args.savedKeywordIds },+ );+ return mcpResponse({+ text: `Deleted ${result.deletedCount} of ${requested} requested saved keyword${requested === 1 ? "" : "s"}.`,+ meta: buildProjectMeta(+ context,+ args.projectId,+ `/p/${args.projectId}/saved`,+ ),+ structuredContent: {+ projectId: args.projectId,+ requested,+ deletedCount: result.deletedCount,+ },+ });+ }),+};diff --git a/src/server/mcp/tools/report-template-tools.ts b/src/server/mcp/tools/report-template-tools.tsindex d14bafc2..fc0bca9f 100644--- a/src/server/mcp/tools/report-template-tools.ts+++ b/src/server/mcp/tools/report-template-tools.ts@@ -18,8 +18,8 @@ import {REPORT_TEMPLATE_MAX_NAME_CHARS,} from "@/types/schemas/report-templates";-// The two report-template tools. Both free (they touch only the app DB), both-// wrapped in withMcpProjectAuth, and both scoped to the authorized project — a+// Report-template tools are free (they touch only the app DB), all+// wrapped in withMcpProjectAuth, and all scoped to the authorized project — a// template id from another project never resolves.const templatesPath = (projectId: string) =>@@ -177,3 +177,51 @@ export const saveReportTemplateTool = {},),};++const deleteInputSchema = {+ projectId: projectIdSchema,+ templateId: z+ .string()+ .min(1)+ .describe("Template id from list_report_templates."),+} as const;++export const deleteReportTemplateTool = {+ name: "delete_report_template",+ config: {+ title: "Delete report template",+ description:+ "Permanently deletes one reusable report template from this project. Uses no credits. Call list_report_templates to find its templateId. Existing saved reports are kept.",+ inputSchema: deleteInputSchema,+ outputSchema: z.looseObject({+ templateId: z.string(),+ deleted: z.literal(true),+ ...optionalMetaOutputSchema,+ }),+ annotations: {+ readOnlyHint: false,+ openWorldHint: false,+ destructiveHint: true,+ },+ },+ handler: withMcpProjectAuth(+ async (args: z.infer<z.ZodObject<typeof deleteInputSchema>>, context) => {+ await ReportTemplateService.deleteReportTemplate(+ args.projectId,+ args.templateId,+ );+ return mcpResponse({+ text: `Deleted report template ${args.templateId}. Existing reports are kept.`,+ meta: buildProjectMeta(+ context,+ args.projectId,+ templatesPath(args.projectId),+ ),+ structuredContent: {+ templateId: args.templateId,+ deleted: true as const,+ },+ });+ },+ ),+};diff --git a/src/server/mcp/tools/report-tools.ts b/src/server/mcp/tools/report-tools.tsindex 0b0fe083..c5817447 100644--- a/src/server/mcp/tools/report-tools.ts+++ b/src/server/mcp/tools/report-tools.ts@@ -24,9 +24,8 @@ import {type ReportMetadata,} from "@/types/schemas/reports";-// The three report tools. All free (they touch only the app DB), all wrapped in-// withMcpProjectAuth, and all answering with the in-app report URL so an agent-// can hand back a link instead of pasting a document into chat.+// Report tools use only the app DB and authorize the project before access.+// Reads/saves link to the report; deletion links back to the report list.const reportPath = (projectId: string, reportId: string) =>`/p/${projectId}/reports/${reportId}`;@@ -362,3 +361,42 @@ export const getReportTool = {},),};++const deleteInputSchema = {+ projectId: projectIdSchema,+ reportId: getInputSchema.reportId,+} as const;++export const deleteReportTool = {+ name: "delete_report",+ config: {+ title: "Delete report",+ description:+ "Permanently deletes one saved report and makes its shared link unavailable. Uses no credits. Call list_reports to find the exact reportId. Does not delete site audits, templates, or project context.",+ inputSchema: deleteInputSchema,+ outputSchema: z.looseObject({+ reportId: z.string(),+ deleted: z.literal(true),+ ...optionalMetaOutputSchema,+ }),+ annotations: {+ readOnlyHint: false,+ openWorldHint: false,+ destructiveHint: true,+ },+ },+ handler: withMcpProjectAuth(+ async (args: z.infer<z.ZodObject<typeof deleteInputSchema>>, context) => {+ await ReportService.deleteReport(args.projectId, args.reportId);+ return mcpResponse({+ text: `Deleted report ${args.reportId}.`,+ meta: buildProjectMeta(+ context,+ args.projectId,+ `/p/${args.projectId}/reports`,+ ),+ structuredContent: { reportId: args.reportId, deleted: true as const },+ });+ },+ ),+};diff --git a/src/server/mcp/tools/saved-keywords-tools.test.ts b/src/server/mcp/tools/saved-keywords-tools.test.tsindex f1652998..28459695 100644--- a/src/server/mcp/tools/saved-keywords-tools.test.ts+++ b/src/server/mcp/tools/saved-keywords-tools.test.ts@@ -199,9 +199,12 @@ describe("saved keyword MCP tools", () => {rows: [{ keyword: "technical seo", tags: ["Content"] }],tags: [{ name: "Content", keywordCount: 1 }],});- expect(result.structuredContent?.rows?.[0]).not.toHaveProperty("id");+ expect(result.structuredContent?.rows?.[0]).toHaveProperty("id", "saved_1");const [content] = result.content;expect(content).toMatchObject({ type: "text" });+ expect(content?.type === "text" ? content.text : "").toContain(+ "id:saved_1",+ );expect(content?.type === "text" ? content.text : "").toContain("tags:Content",);diff --git a/src/server/mcp/tools/site-audit-cleanup-tools.ts b/src/server/mcp/tools/site-audit-cleanup-tools.tsnew file mode 100644index 00000000..e205cb73--- /dev/null+++ b/src/server/mcp/tools/site-audit-cleanup-tools.ts@@ -0,0 +1,98 @@+import { z } from "zod";+import { requireOrgPermission } from "@/server/auth/org-gate";+import { AuditService } from "@/server/features/audit/services/AuditService";+import { buildProjectMeta } from "@/server/mcp/context";+import { mcpResponse } from "@/server/mcp/formatters";+import {+ looseObjectOutputSchema,+ optionalMetaOutputSchema,+} from "@/server/mcp/output-schemas";+import { withMcpProjectAuth } from "@/server/mcp/project-auth";+import { projectIdSchema } from "@/server/mcp/schemas";++const listInputSchema = { projectId: projectIdSchema } as const;++export const listSiteAuditsTool = {+ name: "list_site_audits",+ config: {+ title: "List site audits",+ description:+ "Lists this project's site audits with IDs, URLs, status, page counts, and dates, newest first. Uses no credits. Use this to find an older audit to read or delete; get_audit_status defaults to the newest audit only.",+ inputSchema: listInputSchema,+ outputSchema: z.looseObject({+ audits: z.array(looseObjectOutputSchema),+ ...optionalMetaOutputSchema,+ }),+ annotations: {+ readOnlyHint: true,+ openWorldHint: false,+ destructiveHint: false,+ },+ },+ handler: withMcpProjectAuth(+ async (args: z.infer<z.ZodObject<typeof listInputSchema>>, context) => {+ const audits = await AuditService.getHistory(args.projectId);+ return mcpResponse({+ text: audits.length+ ? audits+ .map(+ (audit) =>+ `${audit.id} ${audit.startUrl} ${audit.status} ${audit.pagesCrawled} pages ${audit.startedAt}`,+ )+ .join("\n")+ : "No site audits in this project.",+ meta: buildProjectMeta(+ context,+ args.projectId,+ `/p/${args.projectId}/audit`,+ ),+ structuredContent: { audits },+ });+ },+ ),+};++const deleteInputSchema = {+ projectId: projectIdSchema,+ auditId: z+ .string()+ .min(1)+ .describe(+ "Exact audit ID from list_site_audits or run_site_audit. Required; never defaults to the latest audit.",+ ),+} as const;++export const deleteSiteAuditTool = {+ name: "delete_site_audit",+ config: {+ title: "Delete site audit",+ description:+ "Permanently deletes one site audit and its crawled pages, issues, and Lighthouse results, freeing audit capacity. Uses the same workflow-stop and cleanup behavior as the dashboard. Uses no credits. Requires an owner or admin, like deletion in the dashboard. Saved reports and project context are kept.",+ inputSchema: deleteInputSchema,+ outputSchema: z.looseObject({+ auditId: z.string(),+ deleted: z.literal(true),+ ...optionalMetaOutputSchema,+ }),+ annotations: {+ readOnlyHint: false,+ openWorldHint: false,+ destructiveHint: true,+ },+ },+ handler: withMcpProjectAuth(+ async (args: z.infer<z.ZodObject<typeof deleteInputSchema>>, context) => {+ requireOrgPermission(context.auth, { project: ["delete"] });+ await AuditService.remove(args.auditId, args.projectId);+ return mcpResponse({+ text: `Deleted site audit ${args.auditId}. Saved reports and project context are kept.`,+ meta: buildProjectMeta(+ context,+ args.projectId,+ `/p/${args.projectId}/audit`,+ ),+ structuredContent: { auditId: args.auditId, deleted: true as const },+ });+ },+ ),+};diff --git a/src/types/schemas/projectContext.ts b/src/types/schemas/projectContext.tsindex eecd3f66..08adf559 100644--- a/src/types/schemas/projectContext.ts+++ b/src/types/schemas/projectContext.ts@@ -46,6 +46,9 @@ const customSectionSlugSchema = z.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Use a lowercase slug like 'launch-plan'",+ )+ .describe(+ "Lowercase letters and digits separated by hyphens, e.g. 'launch-plan'. No underscores or spaces. Use the same slug to edit or delete the section.",);export const CUSTOM_SECTION_KEY_PREFIX = "custom:";