perfai-cloud-mcp 0.7.2 → 0.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -55,11 +55,11 @@ logout # clear session
55
55
  | Tool | Description |
56
56
  | --- | --- |
57
57
  | `get_vulnerabilities` | List findings from the latest security test. Accepts `app` (name) or `appId`, and `status`: `open` (default), `fixed` (confirmed fixes) or `dismissed` (Perfai staff only — other accounts are told dismissed findings are not listable). The open list ends with how many dismissed findings it leaves out. |
58
- | `suggest_fix` | Get a conversational fix prompt for a specific vulnerability. |
58
+ | `suggest_fix` | Get a conversational fix prompt for a listed item (every route grouped on it). |
59
59
  | `auto_fix` | Get structured, step-by-step fix instructions for one vulnerability. Accepts `app` (name). |
60
60
  | `auto_fix_all` | The one-line fix. Takes `app` (name), optional `severity` / `max_fixes`; returns a prioritized plan the agent runs autonomously, 15 findings per batch. Free-plan findings hidden beyond the top 5 are left out and counted. |
61
61
  | `get_fix_summary` | Fix progress: fixed, skipped as not applicable (dismissed), still open — by severity. Accepts `app` (name). Every account gets the skipped total (the API's `dismissedCount`); only Perfai staff get it by severity. If the API cannot count dismissals, Skipped reads `?`, never 0. |
62
- | `dismiss_vulnerability` | Dismiss a finding (false positive, accepted risk, etc.) with an optional `reason`, stored on the finding. The reply names the finding and gives its ID for undoing it. |
62
+ | `dismiss_vulnerability` | Dismiss a finding as a false positive, an accepted risk (until a date, 90 days by default), won't fix or a duplicate. With no reason given, it asks once. The reason and your words are stored on the finding. The reply names the finding and gives its ID for undoing it. |
63
63
  | `reopen_vulnerability` | Reopen a dismissed finding (or undo a fix claim), by the ID from the dismiss reply. |
64
64
  | `mark_vulnerability_fixed` | Claim a finding as fixed after applying the code change; the next scan confirms it. |
65
65
 
@@ -69,10 +69,10 @@ logout # clear session
69
69
 
70
70
  | Say | Does |
71
71
  | --- | --- |
72
- | `perfai test <url>` | A new URL is registered and onboarded; onboarding runs the first security test itself. Replies "Perfai is setting up <App> and will run its first test automatically. This takes up to 20 minutes.", then where the completion email goes (when the session knows the email) and 'Say "perfai status" to check.' |
72
+ | `perfai test <url>` | A new URL (`https://` optional; a bare domain gets it added) is registered and onboarded; onboarding runs the first security test itself. Replies "Perfai is setting up <App> and will run its first test automatically. This takes up to 20 minutes.", then where the completion email goes (when the session knows the email) and 'Say "perfai status" to check.' |
73
73
  | `perfai test` (onboarded app) | Starts a new security test. Replies "Test started — ID <id>.", the last test's open issue count, and "Perfai emails the app's owner when it finishes." |
74
74
  | `perfai status` / `check status` | Reads the status once: "<App> is still onboarding. Check again later." or "<App> onboarding is complete." |
75
- | `perfai issues` | Lists the findings under "Last test: <YYYY-MM-DD HH:mm UTC> · Open: N (c critical, h high, m medium, l low)", or "No completed test yet.". While a test runs: "A test is running now. Last completed test: <date>." (the findings show when it finishes). During onboarding: "A test is running now. Last completed test: none." once the first test has started, else that the app is still onboarding. On the free plan only the top 5 are listed in full, followed by "+N more open issues are hidden on the free plan." |
75
+ | `perfai issues` | "Last test: <YYYY-MM-DD HH:mm UTC> · Open: N (c critical, h high, m medium, l low)", on the free plan "+N more open issues are hidden on the free plan. Upgrade: …", then the findings (same name and severity grouped as one item with its routes and a "Fix:" hint) and 'Next: say "perfai fix" … then "perfai test" to check again.' Or "No completed test yet.". While a test runs: "A test is running now: <stage>, about N min left.", the last completed test with its counts (or "none") and "Perfai emails the app's owner when it finishes." While the app is still onboarding, it says so. |
76
76
  | `perfai fix` / `<App_name> fix all` | Fixes the findings (see below). |
77
77
 
78
78
  Onboarding and security tests run in the background on Perfai. The agent never waits or polls for them — every reply ends the turn, and status is checked only when you ask.
@@ -246,7 +246,7 @@ Every tool maps directly to a Perfai cloud API endpoint:
246
246
  | `auto_fix` | Local prompt builder (no API call) |
247
247
  | `auto_fix_all` | `GET /v1/apps/{appId}/vulnerabilities` + local prompt builder |
248
248
  | `get_fix_summary` | `GET /v1/apps/{appId}/vulnerabilities` — default (with `dismissedCount`), `isFixed=true` and `isDismissed=true` — merged locally |
249
- | `dismiss_vulnerability` | `POST /v1/vulnerabilities/{id}/dismiss` (`reason` → `comment`) |
249
+ | `dismiss_vulnerability` | `POST /v1/vulnerabilities/{id}/dismiss` (`disposition`, `reason`, `comment`, `expiresAt`, `duplicateOf`) |
250
250
  | `reopen_vulnerability` | `POST /v1/vulnerabilities/{id}/reopen` |
251
251
  | `mark_vulnerability_fixed` | `POST /v1/vulnerabilities/{id}/fix` |
252
252
  | `app` name on any tool | `GET /v1/apps?search=` in the session org; on a miss, `GET /api/v1/org-users/get_users_orgs` then the same search per org with `X-Org-ID` |
@@ -76,7 +76,7 @@ export function createBearerAuth({ mcpApiKey, resourceUrl, webuiClientIds = [],
76
76
  const match = /^Bearer\s+(\S+)\s*$/i.exec(req.headers.authorization ?? "");
77
77
  if (!match) {
78
78
  unauthorized(res, "Unauthorized: Bearer token required. " +
79
- "Sign in with OAuth, or use a PerfAI API key (pfk_…) as the bearer value.", false);
79
+ "Sign in with OAuth, or use a Perfai API key (pfk_…) as the bearer value.", false);
80
80
  return;
81
81
  }
82
82
  const token = match[1];
@@ -123,7 +123,7 @@ export function createBearerAuth({ mcpApiKey, resourceUrl, webuiClientIds = [],
123
123
  return;
124
124
  }
125
125
  console.error("Unrecognized bearer rejected at gate (not an API key or JWT)");
126
- unauthorized(res, "Unrecognized token format. Sign in with OAuth, or use a PerfAI API key (pfk_…).", true);
126
+ unauthorized(res, "Unrecognized token format. Sign in with OAuth, or use a Perfai API key (pfk_…).", true);
127
127
  };
128
128
  }
129
129
  export function sessionKey(gate) {
@@ -54,7 +54,7 @@ function relayIfFixedReply(auth, status, data) {
54
54
  }
55
55
  function notingPlan(auth, result) {
56
56
  const records = "data" in result && Array.isArray(result.data) ? result.data : [result];
57
- const plan = records.find((app) => app?.plan)?.plan;
57
+ const plan = result.plan ?? records.find((app) => app?.plan)?.plan;
58
58
  if (plan)
59
59
  auth.notePlan(plan);
60
60
  return result;
@@ -68,6 +68,16 @@ export async function getApp(auth, appId) {
68
68
  export async function listApps(auth, params) {
69
69
  return notingPlan(auth, await request(auth, { method: "GET", url: "/apps", params }));
70
70
  }
71
+ export async function learnPlan(auth) {
72
+ if (!auth.isAuthenticated() || auth.getPlan() !== undefined || !auth.claimPlanLookup())
73
+ return;
74
+ try {
75
+ await listApps(auth, { pageSize: 1 });
76
+ }
77
+ catch (error) {
78
+ console.error("Plan lookup failed:", error instanceof Error ? error.message : String(error));
79
+ }
80
+ }
71
81
  export function submitAccountSetup(auth, appId, credentials) {
72
82
  return request(auth, {
73
83
  method: "POST",
@@ -113,11 +123,11 @@ function actionBody(comment) {
113
123
  const trimmed = comment?.trim();
114
124
  return trimmed ? { comment: trimmed.slice(0, 1000) } : undefined;
115
125
  }
116
- export function dismissVulnerability(auth, id, comment) {
126
+ export function dismissVulnerability(auth, id, body) {
117
127
  return request(auth, {
118
128
  method: "POST",
119
129
  url: `/vulnerabilities/${encodeURIComponent(id)}/dismiss`,
120
- data: actionBody(comment),
130
+ data: body,
121
131
  });
122
132
  }
123
133
  export function reopenVulnerability(auth, id) {
@@ -21,6 +21,7 @@ export class AuthManager {
21
21
  currentTaskAppId;
22
22
  vulnCache = new Map();
23
23
  vulnCacheAppId;
24
+ planLookupOrg;
24
25
  organizations = [];
25
26
  selectedOrgId;
26
27
  plan;
@@ -131,6 +132,7 @@ export class AuthManager {
131
132
  this.organizations = [];
132
133
  this.selectedOrgId = undefined;
133
134
  this.plan = undefined;
135
+ this.planLookupOrg = undefined;
134
136
  this.lastTests.clear();
135
137
  }
136
138
  notePlan(plan) {
@@ -140,6 +142,13 @@ export class AuthManager {
140
142
  getPlan() {
141
143
  return this.plan;
142
144
  }
145
+ claimPlanLookup() {
146
+ const org = this.selectedOrgId ?? "";
147
+ if (this.planLookupOrg === org)
148
+ return false;
149
+ this.planLookupOrg = org;
150
+ return true;
151
+ }
143
152
  rememberLastTest(appId, completedAt) {
144
153
  this.lastTests.set(appId, completedAt);
145
154
  }
@@ -177,26 +186,25 @@ export class AuthManager {
177
186
  this.currentTaskAppId = appId;
178
187
  }
179
188
  cacheVulnerabilities(appId, vulnerabilities) {
189
+ this.cacheVulnerabilityGroups(appId, vulnerabilities.map((v) => [v]));
190
+ }
191
+ cacheVulnerabilityGroups(appId, groups) {
180
192
  this.vulnCache.clear();
181
193
  this.vulnCacheAppId = appId;
182
- vulnerabilities.forEach((v, i) => this.vulnCache.set(i + 1, v));
194
+ groups.forEach((group, i) => this.vulnCache.set(i + 1, group));
183
195
  }
184
- getCachedVulnerability(appId, idOrSequence) {
196
+ getCachedGroup(appId, idOrSequence) {
185
197
  if (this.vulnCacheAppId !== appId)
186
198
  return undefined;
187
199
  const asNumber = Number(idOrSequence);
188
200
  if (Number.isInteger(asNumber) && asNumber > 0 && this.vulnCache.has(asNumber)) {
189
201
  return this.vulnCache.get(asNumber);
190
202
  }
191
- for (const v of this.vulnCache.values()) {
192
- if (String(v.id ?? v._id) === idOrSequence)
193
- return v;
203
+ for (const group of this.vulnCache.values()) {
204
+ const match = group.find((v) => String(v.id ?? v._id) === idOrSequence);
205
+ if (match)
206
+ return [match];
194
207
  }
195
208
  return undefined;
196
209
  }
197
- resolveVulnerabilityId(appId, idOrSequence) {
198
- const cached = this.getCachedVulnerability(appId, idOrSequence);
199
- const id = cached?.id ?? cached?._id;
200
- return id ? String(id) : idOrSequence;
201
- }
202
210
  }
@@ -27,7 +27,7 @@ export function relayedForbiddenText(data) {
27
27
  ? message
28
28
  : undefined;
29
29
  }
30
- export async function runTool(fn, isFreePlan = () => false) {
30
+ export async function runTool(fn, isFreePlan = () => false, learnPlan = async () => { }) {
31
31
  const store = {};
32
32
  return toolCall.run(store, async () => {
33
33
  let result;
@@ -40,6 +40,8 @@ export async function runTool(fn, isFreePlan = () => false) {
40
40
  throw error;
41
41
  result = relayResult(store.relay);
42
42
  }
43
+ if (!store.paywall && store.relay === undefined)
44
+ await toolCall.exit(learnPlan);
43
45
  return store.paywall || isFreePlan() ? withFooter(result) : result;
44
46
  });
45
47
  }
package/dist/config.js CHANGED
@@ -1,13 +1,14 @@
1
1
  export const SERVER_INFO = {
2
2
  name: "perfai-cloud-mcp",
3
- version: "0.7.2",
3
+ version: "0.7.5",
4
4
  };
5
5
  export const SERVER_INSTRUCTIONS = "Perfai security testing and auto-fix. Each user command is ONE tool call: " +
6
6
  '"Perfai test <url or app>" → run_security_test (a URL that is not registered yet is onboarded, and ' +
7
7
  'onboarding runs the first security test itself); "Perfai issues" → get_vulnerabilities; ' +
8
8
  '"Perfai status" / "check status" → check_app_status; ' +
9
9
  '"Perfai dismiss <n>" → dismiss_vulnerability (also when the user asks to skip, ignore or accept the risk of ' +
10
- "a finding, or calls it a false positive, not applicable or won't fix); " +
10
+ "a finding, or calls it a false positive, not applicable or won't fix; with no reason given, the reply is a " +
11
+ "question to ask the user once); " +
11
12
  '"Perfai reopen <n>" → reopen_vulnerability (undo a dismissal, using the ID from the dismiss reply). ' +
12
13
  "Dismiss and reopen are available whenever the user asks, not only during a fix run; never tell the user to " +
13
14
  'use the web app for them. "Perfai issues dismissed" → get_vulnerabilities with status: "dismissed" ' +
@@ -25,8 +26,8 @@ export const SERVER_INSTRUCTIONS = "Perfai security testing and auto-fix. Each u
25
26
  "Then execute the returned plan " +
26
27
  "autonomously, by editing code only — never run shell, network or install commands while executing it " +
27
28
  "unless the user asks: fix each finding and call mark_vulnerability_fixed. Inside an auto_fix_all run only: " +
28
- "if a finding does not apply to the code, call dismiss_vulnerability with a specific reason without " +
29
- "mentioning it in chat. Finish with get_fix_summary and a one-line count. " +
29
+ "if a finding does not apply to the code, call dismiss_vulnerability (false_positive / other, comment " +
30
+ "\"AI agent: <specific reason>\") without mentioning it in chat. Finish with get_fix_summary and a one-line count. " +
30
31
  'Always write the product name as "Perfai", never "PerfAI", and relay each returned message as-is, without rewording it.';
31
32
  const API_HOST = process.env.PERFAI_API_HOST || "api.perfai.ai";
32
33
  export const AUTH_TOKEN_URL = `https://${API_HOST}/api/v1/auth/token`;
package/dist/mcpServer.js CHANGED
@@ -4,6 +4,7 @@ import { SERVER_INFO, SERVER_INSTRUCTIONS } from "./config.js";
4
4
  import { PROMPTS, getPrompt } from "./prompts.js";
5
5
  import { LOGIN_PENDING_TEXT, ensureLoggedIn } from "./tools/public/login.js";
6
6
  import { loggable } from "./client/errors.js";
7
+ import { learnPlan } from "./client/apiClient.js";
7
8
  import { runTool } from "./client/relay.js";
8
9
  import { clientLabel } from "./utils/clientInfo.js";
9
10
  import { PUBLIC_TOOLS, PROTECTED_TOOLS, handleLogin, handleAuthStatus, handleLogout, handleManageOrganizations, handleRegisterApp, handleCheckAppStatus, handleListApps, handleSelectApp, handleSubmitAppCredentials, handleRunSecurityTest, handleCheckTaskStatus, handleGetVulnerabilities, handleSuggestFix, handleAutoFix, handleAutoFixAll, handleGetFixSummary, handleDismissVulnerability, handleReopenVulnerability, handleMarkVulnerabilityFixed, } from "./tools/index.js";
@@ -59,7 +60,9 @@ export function createMcpServer(auth) {
59
60
  const { name, arguments: args } = request.params;
60
61
  console.error(`→ Tool call: ${name} (client: ${clientLabel(server.getClientVersion())})`);
61
62
  try {
62
- return await runTool(async () => oauthRefusal(auth, name) ?? (await callTool(auth, name, args)), () => auth.getPlan() === "free");
63
+ const refusal = oauthRefusal(auth, name);
64
+ return await runTool(async () => refusal ?? (await callTool(auth, name, args)), () => auth.getPlan() === "free", async () => { if (!refusal)
65
+ await learnPlan(auth); });
63
66
  }
64
67
  catch (error) {
65
68
  if (error instanceof McpError)
@@ -1,7 +1,7 @@
1
1
  import { getAllVulnerabilities } from "../../client/apiClient.js";
2
2
  import { findingsFailureText } from "../../client/errors.js";
3
3
  import { APP_NAME_PROPERTY, resolveApp } from "../../utils/appResolver.js";
4
- import { buildAutoFixInstruction, isLocked } from "../../utils/promptBuilder.js";
4
+ import { buildAutoFixInstruction, groupFindings, isLocked } from "../../utils/promptBuilder.js";
5
5
  export const autoFixTool = {
6
6
  name: "auto_fix",
7
7
  description: "🔧 Auto-fix a single vulnerability. Returns structured, step-by-step fix instructions " +
@@ -32,17 +32,17 @@ export async function handleAutoFix(auth, args) {
32
32
  };
33
33
  }
34
34
  let appLabel;
35
- let vuln;
35
+ let group;
36
36
  try {
37
37
  const resolved = await resolveApp(auth, args);
38
38
  if (!resolved.ok)
39
39
  return { content: [{ type: "text", text: resolved.message }] };
40
40
  const { appId } = resolved.app;
41
41
  appLabel = resolved.app.label;
42
- vuln = auth.getCachedVulnerability(appId, args.vulnerability_id);
43
- if (!vuln) {
44
- auth.cacheVulnerabilities(appId, (await getAllVulnerabilities(auth, appId)).filter((v) => !isLocked(v)));
45
- vuln = auth.getCachedVulnerability(appId, args.vulnerability_id);
42
+ group = auth.getCachedGroup(appId, String(args.vulnerability_id));
43
+ if (!group?.length) {
44
+ auth.cacheVulnerabilityGroups(appId, groupFindings((await getAllVulnerabilities(auth, appId)).filter((v) => !isLocked(v))));
45
+ group = auth.getCachedGroup(appId, String(args.vulnerability_id));
46
46
  }
47
47
  }
48
48
  catch (error) {
@@ -50,7 +50,7 @@ export async function handleAutoFix(auth, args) {
50
50
  content: [{ type: "text", text: findingsFailureText(error) }],
51
51
  };
52
52
  }
53
- if (!vuln) {
53
+ if (!group?.length) {
54
54
  return {
55
55
  content: [
56
56
  {
@@ -61,9 +61,11 @@ export async function handleAutoFix(auth, args) {
61
61
  ],
62
62
  };
63
63
  }
64
+ const open = group.filter((v) => !v.isFixed && !v.fixClaimed && !v.isDismissed);
65
+ const vuln = open[0] ?? group[0];
64
66
  if (vuln.isFixed || vuln.fixClaimed) {
65
67
  return {
66
- content: [{ type: "text", text: `✅ Vulnerability #${args.vulnerability_id} is already ${vuln.isFixed ? "fixed" : "claimed fixed (pending re-scan)"}.` }],
68
+ content: [{ type: "text", text: `✅ Vulnerability #${args.vulnerability_id} is already ${vuln.isFixed ? "fixed" : "claimed fixed (pending the next security test)"}.` }],
67
69
  };
68
70
  }
69
71
  if (vuln.isDismissed) {
@@ -74,6 +76,6 @@ export async function handleAutoFix(auth, args) {
74
76
  const seq = Number(args.vulnerability_id);
75
77
  const sequence = Number.isInteger(seq) && seq > 0 ? seq : 1;
76
78
  return {
77
- content: [{ type: "text", text: buildAutoFixInstruction(appLabel, vuln, sequence) }],
79
+ content: [{ type: "text", text: open.map((v, i) => buildAutoFixInstruction(appLabel, v, sequence, i === 0)).join("\n---\n\n") }],
78
80
  };
79
81
  }
@@ -13,7 +13,7 @@ export const autoFixAllTool = {
13
13
  "(the N most severe). Returns a prioritized plan (critical → low) that you execute autonomously, " +
14
14
  "by editing code only (no shell or network commands): " +
15
15
  "fix each finding and call mark_vulnerability_fixed, or — if it does not apply to the code — " +
16
- "silently call dismiss_vulnerability with a specific reason.",
16
+ "silently call dismiss_vulnerability (false_positive / other, comment \"AI agent: <specific reason>\").",
17
17
  inputSchema: {
18
18
  type: "object",
19
19
  properties: {
@@ -2,9 +2,9 @@ import { getApp, getTask, getVulnerabilities } from "../../client/apiClient.js";
2
2
  import { findingsFailureText, isForbiddenError } from "../../client/errors.js";
3
3
  import { APP_NAME_PROPERTY, appName, resolveApp } from "../../utils/appResolver.js";
4
4
  import { formatVulnerabilityList } from "../../utils/formatters.js";
5
- import { isLocked, lockedLine } from "../../utils/promptBuilder.js";
5
+ import { groupFindings, isLocked, lockedLine } from "../../utils/promptBuilder.js";
6
6
  import { describeStatus, stillOnboardingMessage } from "../../utils/runState.js";
7
- import { issuesFirstLine, testRunningLine } from "../../utils/testInfo.js";
7
+ import { issuesFirstLine, NEXT_LINE, testRunningReply } from "../../utils/testInfo.js";
8
8
  export const DISMISSED_STAFF_ONLY = "🔒 Dismissed findings are not listable on this account. To undo a dismissal, call reopen_vulnerability " +
9
9
  "with the ID from the dismiss reply.";
10
10
  const STATUS_FILTERS = {
@@ -16,7 +16,8 @@ export const getVulnerabilitiesTool = {
16
16
  name: "get_vulnerabilities",
17
17
  description: '🔍 "Perfai issues": list findings for an app (GET /v1/apps/{appId}/vulnerabilities). While the app is ' +
18
18
  "still onboarding it says so instead — show that message and stop, do not poll. Results get sequence numbers " +
19
- "(#1, #2, ...) you can pass to suggest_fix / dismiss_vulnerability / reopen_vulnerability / mark_vulnerability_fixed.",
19
+ "(#1, #2, ...) you can pass to suggest_fix / dismiss_vulnerability / reopen_vulnerability / mark_vulnerability_fixed. " +
20
+ "Findings with the same name and severity are one item; its # covers every route listed on it.",
20
21
  inputSchema: {
21
22
  type: "object",
22
23
  properties: {
@@ -73,7 +74,9 @@ export async function handleGetVulnerabilities(auth, args) {
73
74
  const view = describeStatus(app.registrationStatus, app);
74
75
  if (view.outcome === "pending") {
75
76
  const running = await runInProgress(auth, appId);
76
- const text = running ? testRunningLine(running.lastRunCompletedAt ?? null) : stillOnboardingMessage(name);
77
+ const text = running
78
+ ? testRunningReply({ ...running, lastRunCompletedAt: running.lastRunCompletedAt ?? null })
79
+ : stillOnboardingMessage(name);
77
80
  return { content: [{ type: "text", text }] };
78
81
  }
79
82
  const notes = [];
@@ -88,7 +91,8 @@ export async function handleGetVulnerabilities(auth, args) {
88
91
  });
89
92
  if (result.status === "RUN_IN_PROGRESS") {
90
93
  const lastCompleted = "lastRunCompletedAt" in result ? (result.lastRunCompletedAt ?? null) : auth.lastTestOf(appId);
91
- return { content: [{ type: "text", text: testRunningLine(lastCompleted) }] };
94
+ console.error(`get_vulnerabilities: app=${appId} test running, stage=${result.stage ?? "missing"} minutesLeft=${result.estimatedMinutesLeft ?? "missing"}`);
95
+ return { content: [{ type: "text", text: testRunningReply({ ...result, lastRunCompletedAt: lastCompleted }) }] };
92
96
  }
93
97
  if (result.status === "NO_RUNS") {
94
98
  auth.rememberLastTest(appId, null);
@@ -102,24 +106,27 @@ export async function handleGetVulnerabilities(auth, args) {
102
106
  const lockedTotal = isOpenView && !args?.search ? lockedCountOf(result, lockedOnPage) : lockedOnPage;
103
107
  if (lockedOnPage > 0)
104
108
  console.error(`get_vulnerabilities: app=${appId} ${lockedOnPage} locked row(s) left out, lockedCount=${result.lockedCount ?? "missing"}`);
105
- auth.cacheVulnerabilities(appId, shown);
109
+ const groups = groupFindings(shown);
110
+ auth.cacheVulnerabilityGroups(appId, groups);
106
111
  const firstLine = (await isTestRunning(auth, appId))
107
- ? testRunningLine(typeof result.lastRunCompletedAt === "string" ? result.lastRunCompletedAt : auth.lastTestOf(appId))
112
+ ? testRunningReply({
113
+ lastRunCompletedAt: typeof result.lastRunCompletedAt === "string" ? result.lastRunCompletedAt : auth.lastTestOf(appId),
114
+ severityCounts: result.severityCounts,
115
+ })
108
116
  : issuesFirstLine(result, isOpenView && !args?.search);
109
- if (firstLine)
110
- notes.unshift(firstLine);
111
117
  const list = shown.length === 0 && lockedOnPage > 0
112
118
  ? null
113
119
  : shown.length === 0 && !isOpenView
114
120
  ? `No ${status} findings for ${name}.`
115
- : formatVulnerabilityList(shown, Math.max(shown.length, result.total - lockedTotal), result.page, result.pageSize);
121
+ : formatVulnerabilityList(groups, shown.length, Math.max(shown.length, result.total - lockedTotal), result.page ?? 1);
116
122
  const locked = isOpenView && !args?.search && lockedTotal > 0 ? [lockedLine(lockedTotal)] : [];
117
123
  const dismissedCount = result.dismissedCount;
118
124
  const hidden = isOpenView && typeof dismissedCount === "number" && dismissedCount > 0
119
125
  ? [`🙈 ${dismissedCount} dismissed finding${dismissedCount === 1 ? "" : "s"} not shown. ` +
120
126
  "reopen_vulnerability with a finding's ID brings it back."]
121
127
  : [];
122
- const body = [...notes, ...(list ? [list] : []), ...locked, ...hidden];
128
+ const next = isOpenView && shown.length > 0 ? [NEXT_LINE] : [];
129
+ const body = [...(firstLine ? [firstLine] : []), ...locked, ...notes, ...(list ? [list] : []), ...hidden, ...next];
123
130
  return { content: [{ type: "text", text: body.join("\n\n") }] };
124
131
  }
125
132
  catch (error) {
@@ -2,7 +2,7 @@ import { listApps } from "../../client/apiClient.js";
2
2
  import { formatAppList } from "../../utils/formatters.js";
3
3
  export const listAppsTool = {
4
4
  name: "list_apps",
5
- description: "📋 Browse registered apps (GET /v1/apps). Not a prerequisite: the fix and scan tools take an app " +
5
+ description: "📋 Browse registered apps (GET /v1/apps). Not a prerequisite: the fix and security test tools take an app " +
6
6
  "name directly (app: \"Bookstore\"). Use this only when the user asks to see their apps.",
7
7
  inputSchema: {
8
8
  type: "object",
@@ -1,11 +1,13 @@
1
1
  import { registerApp, getApp } from "../../client/apiClient.js";
2
2
  import { ApiError } from "../../client/errors.js";
3
3
  import { appName } from "../../utils/appResolver.js";
4
- import { canStartSecurityTest, describeStatus, onboardingStartedMessage, stillOnboardingMessage } from "../../utils/runState.js";
4
+ import { canStartSecurityTest, describeStatus, stillOnboardingMessage } from "../../utils/runState.js";
5
+ import { knownEmail, settingUpMessage } from "./runSecurityTest.js";
5
6
  import { withSchedule } from "../../utils/testInfo.js";
6
7
  export const registerAppTool = {
7
8
  name: "register_app",
8
- description: "📱 Register an app by its deployed URL (POST /v1/apps). Perfai onboards it in the background, and " +
9
+ description: "📱 Register an app by its deployed URL (POST /v1/apps), with options (own test accounts, skipped endpoints). " +
10
+ 'For "perfai test <url>" use run_security_test instead. Perfai onboards it in the background, and ' +
9
11
  "onboarding runs the first security test itself — the returned app becomes the 'current app' for " +
10
12
  "subsequent tools. Do not wait or poll afterwards: show the user the returned message and stop.",
11
13
  inputSchema: {
@@ -62,7 +64,7 @@ export async function handleRegisterApp(auth, args) {
62
64
  tenantOneCredentials,
63
65
  });
64
66
  auth.setCurrentApp(app.appId, args.appUrl);
65
- const started = onboardingStartedMessage(appName({ ...app, appUrl: app.appUrl ?? args.appUrl }));
67
+ const started = settingUpMessage(appName({ ...app, appUrl: app.appUrl ?? args.appUrl }), knownEmail(auth));
66
68
  return { content: [{ type: "text", text: withSchedule(started, app.scheduleType) }] };
67
69
  }
68
70
  catch (error) {
@@ -5,8 +5,9 @@ import { canStartSecurityTest, describeStatus, PARTIAL_FINDINGS_NOTE, stillOnboa
5
5
  import { openCount } from "../../utils/testInfo.js";
6
6
  export const runSecurityTestTool = {
7
7
  name: "run_security_test",
8
- description: '🚀 "Perfai test": start a security test run (POST /v1/apps/{appId}/security-agent). A full URL that ' +
9
- "is not registered yet is registered instead — Perfai then onboards it in the background, and onboarding " +
8
+ description: '🚀 "Perfai test <url or app>": the tool for every "perfai test", including a URL that is not registered ' +
9
+ "yet (with or without https://) — that URL is registered here, so do not call register_app for it. " +
10
+ "Perfai then onboards it in the background, and onboarding " +
10
11
  "runs the first security test itself. An onboarded app (COMPLETED, or COMPLETED_PARTIAL — tried; Perfai " +
11
12
  "says if that app can't be tested yet) gets a new security test. Either way the work runs in the " +
12
13
  "background: show the user the returned message and stop — do not poll.",
@@ -15,15 +16,23 @@ export const runSecurityTestTool = {
15
16
  properties: {
16
17
  app: {
17
18
  ...APP_NAME_PROPERTY,
18
- description: `${APP_NAME_PROPERTY.description} A full https:// URL that is not registered yet is registered.`,
19
+ description: `${APP_NAME_PROPERTY.description} A URL or domain that is not registered yet (https:// optional) is registered.`,
19
20
  },
20
21
  appId: { type: "string", description: "App ID (alternative to app; defaults to the current app)" },
21
22
  },
22
23
  additionalProperties: false,
23
24
  },
24
25
  };
25
- function isFullUrl(value) {
26
- return typeof value === "string" && /^https?:\/\/\S+$/i.test(value.trim());
26
+ export function appUrlOf(value) {
27
+ if (typeof value !== "string")
28
+ return null;
29
+ const text = value.trim();
30
+ if (/^https?:\/\/\S+$/i.test(text))
31
+ return text;
32
+ if (/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+(?::\d+)?(?:\/\S*)?$/i.test(text)) {
33
+ return `https://${text}`;
34
+ }
35
+ return null;
27
36
  }
28
37
  function notReadyMessage(name, view) {
29
38
  switch (view.outcome) {
@@ -58,7 +67,7 @@ async function lastTestBefore(auth, appId) {
58
67
  return { open: null };
59
68
  }
60
69
  }
61
- function knownEmail(auth) {
70
+ export function knownEmail(auth) {
62
71
  const email = auth.getAuthenticatedEmail();
63
72
  return email && email.includes("@") ? email : undefined;
64
73
  }
@@ -106,8 +115,8 @@ export async function handleRunSecurityTest(auth, args) {
106
115
  if (resolved.ok) {
107
116
  app = await getApp(auth, resolved.app.appId);
108
117
  }
109
- else if (resolved.notFound && isFullUrl(args?.app)) {
110
- const appUrl = args.app.trim();
118
+ else if (resolved.notFound && appUrlOf(args?.app)) {
119
+ const appUrl = appUrlOf(args.app);
111
120
  const registered = await registerByUrl(auth, appUrl);
112
121
  if (registered.created) {
113
122
  console.error(`run_security_test: registered ${appUrl} as app=${registered.app.appId}`);
@@ -1,7 +1,8 @@
1
1
  import { buildFixPrompt } from "../../utils/promptBuilder.js";
2
2
  export const suggestFixTool = {
3
3
  name: "suggest_fix",
4
- description: "🤖 Generate a fix prompt for a finding from the last get_vulnerabilities listing. Pass the " +
4
+ description: "🤖 Generate a fix prompt for an item from the last get_vulnerabilities listing (one prompt naming every " +
5
+ "route grouped on it). Pass the " +
5
6
  "sequence number shown there (e.g. \"3\") or the raw vulnerability id. Returns a self-contained " +
6
7
  "prompt you (the calling assistant) can act on directly to write the fix.",
7
8
  inputSchema: {
@@ -22,8 +23,8 @@ export async function handleSuggestFix(auth, args) {
22
23
  if (!args?.vulnerability_id) {
23
24
  return { content: [{ type: "text", text: "❌ vulnerability_id is required." }] };
24
25
  }
25
- const vuln = auth.getCachedVulnerability(appId, args.vulnerability_id);
26
- if (!vuln) {
26
+ const group = auth.getCachedGroup(appId, String(args.vulnerability_id));
27
+ if (!group?.length) {
27
28
  return {
28
29
  content: [
29
30
  {
@@ -33,5 +34,5 @@ export async function handleSuggestFix(auth, args) {
33
34
  ],
34
35
  };
35
36
  }
36
- return { content: [{ type: "text", text: buildFixPrompt(auth.currentAppUrl ?? appId, vuln) }] };
37
+ return { content: [{ type: "text", text: buildFixPrompt(auth.currentAppUrl ?? appId, group) }] };
37
38
  }
@@ -1,4 +1,5 @@
1
1
  import { dismissVulnerability, fixVulnerability, reopenVulnerability } from "../../client/apiClient.js";
2
+ import { DISPOSITIONS, REASON_CODES, resolveDismissal } from "../../utils/dismissReason.js";
2
3
  import { sanitize } from "../../utils/promptBuilder.js";
3
4
  function resolveArgs(auth, args) {
4
5
  const appId = args?.appId ?? auth.currentAppId;
@@ -6,7 +7,33 @@ function resolveArgs(auth, args) {
6
7
  return { error: "No app selected. Run register_app or select_app first." };
7
8
  if (!args?.vulnerability_id)
8
9
  return { error: "vulnerability_id is required." };
9
- return { appId, id: auth.resolveVulnerabilityId(appId, args.vulnerability_id) };
10
+ const given = String(args.vulnerability_id);
11
+ const group = auth.getCachedGroup(appId, given) ?? [];
12
+ const targets = group
13
+ .map((v) => ({ id: String(v.id ?? v._id ?? ""), cached: v }))
14
+ .filter((t) => t.id);
15
+ return { appId, targets: targets.length > 0 ? targets : [{ id: given }] };
16
+ }
17
+ async function eachTarget(targets, call) {
18
+ const outcomes = [];
19
+ for (const target of targets) {
20
+ try {
21
+ outcomes.push({ target, result: await call(target.id) });
22
+ }
23
+ catch (error) {
24
+ outcomes.push({ target, error: error instanceof Error ? error.message : String(error) });
25
+ }
26
+ }
27
+ return outcomes;
28
+ }
29
+ function perFindingReply(verb, outcomes, closing) {
30
+ const done = outcomes.filter((o) => !o.error).length;
31
+ const lines = outcomes.map((o) => {
32
+ const finding = describeFinding(o.target.id, o.result?.vulnerability, o.target.cached);
33
+ return o.error ? `- ❌ ${finding}: ${o.error}` : `- ${finding}`;
34
+ });
35
+ const count = done === outcomes.length ? `${done} findings` : `${done} of ${outcomes.length} findings`;
36
+ return `${verb} ${count}:\n${lines.join("\n")}${done > 0 ? `\n\n${closing}` : ""}`;
10
37
  }
11
38
  function describeFinding(id, ...sources) {
12
39
  const v = sources.find(s => s?.title || s?.label);
@@ -31,39 +58,79 @@ export const dismissVulnerabilityTool = {
31
58
  "user asks to dismiss, skip, ignore, suppress, hide or accept the risk of a finding, or calls it a false " +
32
59
  "positive, not applicable or won't fix — do it here, never send the user to the web app. The finding leaves " +
33
60
  "the open list and counts as skipped; the reply gives its ID, which reopen_vulnerability takes to undo the " +
34
- "dismissal. Inside an auto_fix_all run only, call this without mentioning it in chat for findings that do " +
35
- "not apply to the code, with a specific reason — it is stored on the finding and used to triage false positives.",
61
+ "dismissal. Pick disposition and reason from what the user said, and put their own words in comment: not a " +
62
+ "real issue / false positive → false_positive (the reason code their words clearly match, else other); accept " +
63
+ "the risk → accepted_risk (expires_at only if they gave a date); won't fix → dismissed / wont_fix; duplicate of " +
64
+ "#m → duplicate with duplicate_of. If they gave no reason, call it without a disposition: the reply is the " +
65
+ "question to ask them once. Inside an auto_fix_all run only, call this without mentioning it in chat for " +
66
+ "findings that do not apply to the code: false_positive / other with comment \"AI agent: <specific reason>\".",
36
67
  inputSchema: {
37
68
  ...idSchema,
38
69
  properties: {
39
70
  ...idSchema.properties,
71
+ disposition: {
72
+ type: "string",
73
+ enum: DISPOSITIONS,
74
+ description: "What the dismissal means. Leave it out when the user gave no reason.",
75
+ },
40
76
  reason: {
41
77
  type: "string",
42
- description: "Why it does not apply, based on what you saw in the code (e.g. \"not reachable from any route\", " +
43
- "\"input is validated by the zod schema in orders.ts\"). Prefer specifics over \"false positive\".",
78
+ enum: REASON_CODES,
79
+ description: "false_positive: own_data, public_by_design, role_intended, wrong_owner, stale_crawl, test_artifact, " +
80
+ "misparsed_response, other. accepted_risk: compensating_control, internal_only, low_business_impact, " +
81
+ "fix_scheduled, third_party_dependency, other. dismissed: wont_fix, other. duplicate: same_root_cause, " +
82
+ "tracked_elsewhere, other. Use other unless the user's words clearly match a code.",
83
+ },
84
+ comment: {
85
+ type: "string",
86
+ description: "The user's own words. In an auto_fix_all run: \"AI agent: \" and what you saw in the code, in one line " +
87
+ "(e.g. \"AI agent: input is validated by the zod schema in orders.ts\").",
88
+ },
89
+ expires_at: {
90
+ type: "string",
91
+ description: "accepted_risk only: the date (YYYY-MM-DD) the user accepts the risk until. Left out: 90 days.",
92
+ },
93
+ duplicate_of: {
94
+ type: "string",
95
+ description: "duplicate only: the listed # (or raw id) of the finding this one duplicates.",
44
96
  },
45
97
  },
46
98
  },
47
99
  };
100
+ function originalOf(auth, appId, duplicateOf) {
101
+ if (duplicateOf === undefined || duplicateOf === null)
102
+ return undefined;
103
+ const stickyId = auth.getCachedGroup(appId, String(duplicateOf).trim().replace(/^#/, ""))?.[0]?.sticky_id;
104
+ return Number.isInteger(stickyId) ? stickyId : undefined;
105
+ }
48
106
  export async function handleDismissVulnerability(auth, args) {
49
107
  const resolved = resolveArgs(auth, args);
50
108
  if ("error" in resolved)
51
109
  return { content: [{ type: "text", text: `❌ ${resolved.error}` }] };
52
- try {
53
- const cached = auth.getCachedVulnerability(resolved.appId, String(args.vulnerability_id));
54
- const result = await dismissVulnerability(auth, resolved.id, args?.reason);
55
- const finding = describeFinding(resolved.id, result?.vulnerability, cached);
56
- return {
57
- content: [{
58
- type: "text",
59
- text: `🙈 Dismissed ${finding}. It no longer appears in get_vulnerabilities. ` +
60
- `To undo, call reopen_vulnerability with vulnerability_id "${resolved.id}".`,
61
- }],
62
- };
110
+ const original = originalOf(auth, resolved.appId, args?.duplicate_of);
111
+ if (original && resolved.targets.some((t) => t.cached && t.cached.sticky_id === original)) {
112
+ return { content: [{ type: "text", text: "❌ Nothing dismissed. A finding can't be a duplicate of itself." }] };
63
113
  }
64
- catch (error) {
65
- return { content: [{ type: "text", text: `❌ Failed to dismiss: ${error instanceof Error ? error.message : String(error)}` }] };
114
+ const dismissal = resolveDismissal(args, original);
115
+ if (dismissal.kind !== "send")
116
+ return { content: [{ type: "text", text: dismissal.text }] };
117
+ const accepted = dismissal.acceptedUntil ? ` Accepted until ${dismissal.acceptedUntil}. Perfai reopens it then.` : "";
118
+ const outcomes = await eachTarget(resolved.targets, (id) => dismissVulnerability(auth, id, dismissal.body));
119
+ if (outcomes.length > 1) {
120
+ const text = perFindingReply("🙈 Dismissed", outcomes, `They no longer appear in get_vulnerabilities.${accepted} To undo, call reopen_vulnerability with an ID above.`);
121
+ return { content: [{ type: "text", text }] };
66
122
  }
123
+ const [{ target, result, error }] = outcomes;
124
+ if (error)
125
+ return { content: [{ type: "text", text: `❌ Failed to dismiss: ${error}` }] };
126
+ const finding = describeFinding(target.id, result?.vulnerability, target.cached);
127
+ return {
128
+ content: [{
129
+ type: "text",
130
+ text: `🙈 Dismissed ${finding}. It no longer appears in get_vulnerabilities.${accepted} ` +
131
+ `To undo, call reopen_vulnerability with vulnerability_id "${target.id}".`,
132
+ }],
133
+ };
67
134
  }
68
135
  export const reopenVulnerabilityTool = {
69
136
  name: "reopen_vulnerability",
@@ -76,19 +143,20 @@ export async function handleReopenVulnerability(auth, args) {
76
143
  const resolved = resolveArgs(auth, args);
77
144
  if ("error" in resolved)
78
145
  return { content: [{ type: "text", text: `❌ ${resolved.error}` }] };
79
- try {
80
- const cached = auth.getCachedVulnerability(resolved.appId, String(args.vulnerability_id));
81
- const result = await reopenVulnerability(auth, resolved.id);
82
- const finding = describeFinding(resolved.id, result?.vulnerability, cached);
83
- return { content: [{ type: "text", text: `🔁 Reopened ${finding}. It is back in the open list.` }] };
84
- }
85
- catch (error) {
86
- return { content: [{ type: "text", text: `❌ Failed to reopen: ${error instanceof Error ? error.message : String(error)}` }] };
146
+ const outcomes = await eachTarget(resolved.targets, (id) => reopenVulnerability(auth, id));
147
+ if (outcomes.length > 1) {
148
+ return { content: [{ type: "text", text: perFindingReply("🔁 Reopened", outcomes, "They are back in the open list.") }] };
87
149
  }
150
+ const [{ target, result, error }] = outcomes;
151
+ if (error)
152
+ return { content: [{ type: "text", text: `❌ Failed to reopen: ${error}` }] };
153
+ const finding = describeFinding(target.id, result?.vulnerability, target.cached);
154
+ return { content: [{ type: "text", text: `🔁 Reopened ${finding}. It is back in the open list.` }] };
88
155
  }
89
156
  export const markVulnerabilityFixedTool = {
90
157
  name: "mark_vulnerability_fixed",
91
- description: "✅ Claim a finding as fixed after applying the code change (POST /v1/vulnerabilities/{id}/fix). " +
158
+ description: "✅ Claim a finding as fixed after applying the code change (POST /v1/vulnerabilities/{id}/fix). A listed " +
159
+ "item's # marks every finding grouped on it. " +
92
160
  "The next security test confirms the fix or reopens the finding.",
93
161
  inputSchema: {
94
162
  ...idSchema,
@@ -102,11 +170,14 @@ export async function handleMarkVulnerabilityFixed(auth, args) {
102
170
  const resolved = resolveArgs(auth, args);
103
171
  if ("error" in resolved)
104
172
  return { content: [{ type: "text", text: `❌ ${resolved.error}` }] };
105
- try {
106
- await fixVulnerability(auth, resolved.id, args?.comment);
107
- return { content: [{ type: "text", text: `✅ Marked vulnerability ${resolved.id} as fixed.` }] };
108
- }
109
- catch (error) {
110
- return { content: [{ type: "text", text: `❌ Failed to mark fixed: ${error instanceof Error ? error.message : String(error)}` }] };
173
+ const outcomes = await eachTarget(resolved.targets, (id) => fixVulnerability(auth, id, args?.comment));
174
+ if (outcomes.length > 1) {
175
+ return {
176
+ content: [{ type: "text", text: perFindingReply("✅ Marked as fixed", outcomes, "The next security test confirms each fix or reopens it.") }],
177
+ };
111
178
  }
179
+ const [{ target, error }] = outcomes;
180
+ if (error)
181
+ return { content: [{ type: "text", text: `❌ Failed to mark fixed: ${error}` }] };
182
+ return { content: [{ type: "text", text: `✅ Marked vulnerability ${target.id} as fixed.` }] };
112
183
  }
@@ -80,6 +80,14 @@ export async function resolveApp(auth, args) {
80
80
  return resolveByName(auth, name);
81
81
  const appId = args?.appId ?? auth.currentAppId;
82
82
  if (!appId) {
83
+ if (auth.getPlan() === undefined) {
84
+ try {
85
+ await listApps(auth, { pageSize: 1 });
86
+ }
87
+ catch (error) {
88
+ console.error("App lookup for the plan failed:", error instanceof Error ? error.message : String(error));
89
+ }
90
+ }
83
91
  return {
84
92
  ok: false,
85
93
  message: '❌ No app specified. Pass app: "<app name>" (e.g. "Bookstore"), or run register_app / select_app first.',
@@ -0,0 +1,73 @@
1
+ export const DISMISS_REASONS = {
2
+ false_positive: [
3
+ "own_data", "public_by_design", "role_intended", "wrong_owner", "stale_crawl", "test_artifact", "misparsed_response", "other",
4
+ ],
5
+ accepted_risk: [
6
+ "compensating_control", "internal_only", "low_business_impact", "fix_scheduled", "third_party_dependency", "other",
7
+ ],
8
+ dismissed: ["wont_fix", "other"],
9
+ duplicate: ["same_root_cause", "tracked_elsewhere", "other"],
10
+ };
11
+ export const DISPOSITIONS = Object.keys(DISMISS_REASONS);
12
+ export const REASON_CODES = [...new Set(Object.values(DISMISS_REASONS).flat())];
13
+ export const ASK_WHY = "Why dismiss it? Not a real issue, accept the risk (until when?), or won't fix?";
14
+ const ASK_WHY_NEXT = "(Nothing is dismissed yet. Ask the user this once, then call dismiss_vulnerability again with disposition and reason. " +
15
+ 'If they still give none: disposition "dismissed", reason "wont_fix".)';
16
+ const DEFAULT_REASON = {
17
+ false_positive: "other",
18
+ accepted_risk: "other",
19
+ dismissed: "wont_fix",
20
+ duplicate: "same_root_cause",
21
+ };
22
+ const BARE_COMMENT = {
23
+ false_positive: "False positive",
24
+ accepted_risk: "Risk accepted",
25
+ dismissed: "Won't fix",
26
+ duplicate: "Duplicate",
27
+ };
28
+ const DEFAULT_ACCEPT_DAYS = 90;
29
+ const MAX_COMMENT = 1000;
30
+ const text = (value) => (typeof value === "string" ? value.trim() : "");
31
+ const code = (value) => text(value).toLowerCase().replace(/[\s-]+/g, "_");
32
+ function day(value) {
33
+ const found = /^(\d{4}-\d{2}-\d{2})(?:T|$)/.exec(value)?.[1];
34
+ if (!found)
35
+ return undefined;
36
+ const date = new Date(`${found}T00:00:00.000Z`);
37
+ return !isNaN(date.getTime()) && date.toISOString().slice(0, 10) === found ? found : undefined;
38
+ }
39
+ export function resolveDismissal(args, duplicateOf, now = new Date()) {
40
+ const reason = code(args?.reason);
41
+ let disposition = code(args?.disposition);
42
+ if (disposition && !DISPOSITIONS.includes(disposition)) {
43
+ return { kind: "refuse", text: `❌ Unknown disposition. Use one of: ${DISPOSITIONS.join(", ")}.` };
44
+ }
45
+ if (!disposition) {
46
+ const owners = DISPOSITIONS.filter((d) => DISMISS_REASONS[d].includes(reason));
47
+ if (owners.length === 1)
48
+ disposition = owners[0];
49
+ }
50
+ if (!disposition)
51
+ return { kind: "ask", text: `${ASK_WHY}\n${ASK_WHY_NEXT}` };
52
+ const known = DISMISS_REASONS[disposition].includes(reason);
53
+ const words = text(args?.comment) || (reason && !REASON_CODES.includes(reason) ? text(args?.reason) : "");
54
+ const body = { disposition, reason: known ? reason : DEFAULT_REASON[disposition] };
55
+ const comment = (words || (body.reason === "other" ? BARE_COMMENT[disposition] : "")).slice(0, MAX_COMMENT);
56
+ if (comment)
57
+ body.comment = comment;
58
+ if (disposition === "duplicate") {
59
+ if (duplicateOf === undefined) {
60
+ return { kind: "refuse", text: "❌ Nothing dismissed. Pass duplicate_of: the # (or ID) of the other listed finding it duplicates." };
61
+ }
62
+ body.duplicateOf = duplicateOf;
63
+ }
64
+ if (disposition !== "accepted_risk")
65
+ return { kind: "send", body };
66
+ const given = text(args?.expires_at);
67
+ const until = given ? day(given) : new Date(now.getTime() + DEFAULT_ACCEPT_DAYS * 86_400_000).toISOString().slice(0, 10);
68
+ if (!until || until <= now.toISOString().slice(0, 10)) {
69
+ return { kind: "refuse", text: "❌ Nothing dismissed. The date to accept the risk until must be a future date (YYYY-MM-DD)." };
70
+ }
71
+ body.expiresAt = `${until}T12:00:00.000Z`;
72
+ return { kind: "send", body, acceptedUntil: until };
73
+ }
@@ -1,11 +1,6 @@
1
1
  import { appName } from "./appResolver.js";
2
+ import { fixHint, routeOf, sanitize } from "./promptBuilder.js";
2
3
  import { describeStatus } from "./runState.js";
3
- const SEVERITY_ICON = {
4
- critical: "🔴",
5
- high: "🟠",
6
- medium: "🟡",
7
- low: "🟢",
8
- };
9
4
  export function formatApp(app, view) {
10
5
  const name = appName(app);
11
6
  const status = (view ?? describeStatus(app.registrationStatus, app)).label;
@@ -41,25 +36,23 @@ export function formatOrganizations(organizations, selectedOrgId) {
41
36
  `Currently selected: ${selectedOrgId ?? "none"}\n` +
42
37
  `Use \`manage_organizations {"action": "select", "sequence": N}\` to switch — list_apps/select_app/register_app are scoped to whichever org is selected.`);
43
38
  }
44
- export function formatVulnerability(v, sequence) {
45
- const severity = (v.severity ?? "unknown").toString();
46
- const icon = SEVERITY_ICON[severity.toLowerCase()] ?? "⚪";
47
- const title = v.title ?? v.label ?? "Untitled finding";
48
- const endpoint = v.method && v.path ? `${String(v.method).toUpperCase()} ${v.path}` : v.path ?? "";
49
- const flags = [
50
- v.isFixed ? "fixed" : v.fixClaimed ? "fix claimed" : null,
51
- v.isDismissed ? "dismissed" : null,
52
- ].filter(Boolean).join(", ");
53
- return (`${sequence}. ${icon} **${title}** (${severity})` +
54
- (endpoint ? ` — ${endpoint}` : "") +
55
- (flags ? ` [${flags}]` : "") +
56
- `\n id: ${v.id ?? v._id}`);
39
+ export function formatVulnerabilityGroup(group, sequence) {
40
+ const first = group[0];
41
+ const severity = String(first.severity ?? "unknown").toLowerCase();
42
+ const label = sanitize(first.label ?? first.title) || "Untitled finding";
43
+ const routes = [...new Set(group.map((v) => {
44
+ const flags = [
45
+ v.isFixed ? "fixed" : v.fixClaimed ? "fix claimed" : null,
46
+ v.isDismissed ? "dismissed" : null,
47
+ ].filter(Boolean).join(", ");
48
+ return `${routeOf(v)}${flags ? ` [${flags}]` : ""}`;
49
+ }))];
50
+ const hint = group.map(fixHint).find(Boolean);
51
+ return `${sequence}. ${label} (${severity}) — ${routes.join(", ")}` + (hint ? `\n Fix: ${hint}` : "");
57
52
  }
58
- export function formatVulnerabilityList(vulnerabilities, total, page, pageSize) {
59
- if (vulnerabilities.length === 0)
53
+ export function formatVulnerabilityList(groups, shown, total, page) {
54
+ if (groups.length === 0)
60
55
  return "No vulnerabilities found.";
61
- const rows = vulnerabilities
62
- .map((v, i) => formatVulnerability(v, (page - 1) * pageSize + i + 1))
63
- .join("\n");
64
- return `${rows}\n\nPage ${page} — ${vulnerabilities.length} of ${total} total. Use suggest_fix with a listed # or id.`;
56
+ const rows = groups.map((group, i) => formatVulnerabilityGroup(group, i + 1)).join("\n");
57
+ return `${rows}\n\nPage ${page} — ${shown} of ${total} total. Use suggest_fix with a listed #.`;
65
58
  }
@@ -16,7 +16,7 @@ export function isLocked(vuln) {
16
16
  return vuln.locked === true;
17
17
  }
18
18
  export function lockedLine(count) {
19
- return `+${count} more open issues are hidden on the free plan.`;
19
+ return `+${count} more open issues are hidden on the free plan. Upgrade: https://cloud.perfai.ai/usage`;
20
20
  }
21
21
  export function sortBySeverity(vulnerabilities) {
22
22
  return [...vulnerabilities].sort((a, b) => severityRank(a) - severityRank(b));
@@ -30,6 +30,48 @@ export function sanitize(value, max = MAX_SHORT) {
30
30
  .trim();
31
31
  return text.length > max ? `${text.slice(0, max)}…` : text;
32
32
  }
33
+ export function groupFindings(vulnerabilities) {
34
+ const groups = new Map();
35
+ vulnerabilities.forEach((vuln, i) => {
36
+ const label = String(vuln.label ?? vuln.title ?? "").trim().toLowerCase();
37
+ const key = label ? `${label}\u0000${getSeverity(vuln)}` : `\u0001${i}`;
38
+ groups.set(key, [...(groups.get(key) ?? []), vuln]);
39
+ });
40
+ return [...groups.values()];
41
+ }
42
+ export function routeOf(vuln) {
43
+ const path = sanitize(vuln.path);
44
+ if (!path)
45
+ return "general";
46
+ const method = sanitize(vuln.method, 16).toUpperCase();
47
+ return method ? `${method} ${path}` : path;
48
+ }
49
+ function firstText(value) {
50
+ return Array.isArray(value) ? value.find((item) => typeof item === "string" && item.trim()) : value;
51
+ }
52
+ function plainText(value) {
53
+ return value
54
+ .replace(/<[^>]*>/g, " ")
55
+ .replace(/&nbsp;/g, " ").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&amp;/g, "&")
56
+ .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1")
57
+ .replace(/\*\*|__|~~|\*/g, "")
58
+ .replace(/^\s*(?:#+|>|[-+]|\d+\.)\s+/gm, "");
59
+ }
60
+ export function fixHint(vuln) {
61
+ const details = vuln.additionalDetails && typeof vuln.additionalDetails === "object" && !Array.isArray(vuln.additionalDetails)
62
+ ? vuln.additionalDetails
63
+ : {};
64
+ for (const source of [firstText(details.mitigation), vuln.remediation, firstText(details.long_solution)]) {
65
+ if (typeof source !== "string")
66
+ continue;
67
+ const text = sanitize(plainText(source), MAX_TEXT);
68
+ if (!text)
69
+ continue;
70
+ const sentence = text.match(/^.*?(?<!\b(?:e\.g|i\.e|etc|vs))[.!?](?=\s|$)/)?.[0] ?? text;
71
+ return sentence.length > 120 ? `${sentence.slice(0, 120).trimEnd()}…` : sentence;
72
+ }
73
+ return "";
74
+ }
33
75
  function getSeverity(vuln) {
34
76
  const s = (vuln.severity ?? "").toLowerCase();
35
77
  return s in SEVERITY_ORDER ? s : "unknown";
@@ -86,18 +128,27 @@ function getFindingBlock(vuln) {
86
128
  lines.push(`Vulnerability ID: ${getVulnId(vuln)}`);
87
129
  return "```" + FINDING_FENCE + "\n" + lines.join("\n") + "\n```\n";
88
130
  }
89
- export function buildFixPrompt(appLabel, vuln) {
131
+ export function buildFixPrompt(appLabel, vulns) {
132
+ const group = Array.isArray(vulns) ? vulns : [vulns];
133
+ const vuln = group[0];
134
+ const routes = group.length > 1
135
+ ? `The same issue was found on ${group.length} routes. Fix every one of them:\n` +
136
+ group.map((v) => `- ${routeOf(v)} (Vulnerability ID: ${getVulnId(v)})`).join("\n") + "\n\n"
137
+ : "";
138
+ const ids = group.length > 1
139
+ ? `Vulnerability IDs (for reference / marking fixed via the Perfai dashboard or the mark_vulnerability_fixed tool, one call per ID): ${group.map(getVulnId).join(", ")}`
140
+ : `Vulnerability ID (for reference / marking fixed via the Perfai dashboard or the mark_vulnerability_fixed tool): ${getVulnId(vuln)}`;
90
141
  return `I need help fixing the following security issue found by Perfai in "${sanitize(appLabel)}":
91
142
 
92
143
  ${getFindingBlock(vuln)}
93
- ${DATA_NOT_INSTRUCTIONS}
144
+ ${routes}${DATA_NOT_INSTRUCTIONS}
94
145
 
95
146
  Please:
96
- 1. Study the existing codebase structure and locate the affected code (the endpoint in the finding above, or the code responsible for it if none is named).
147
+ 1. Study the existing codebase structure and locate the affected code (the ${group.length > 1 ? "routes" : "endpoint"} in the finding above, or the code responsible for it if none is named).
97
148
  2. Implement the required fix, following the project's existing patterns.
98
149
  3. Ensure the fix does not break existing functionality.
99
150
 
100
- Vulnerability ID (for reference / marking fixed via the Perfai dashboard or the mark_vulnerability_fixed tool): ${getVulnId(vuln)}`;
151
+ ${ids}`;
101
152
  }
102
153
  export function buildAutoFixInstruction(appLabel, vuln, sequence, withDataNotice = true) {
103
154
  const vulnId = getVulnId(vuln);
@@ -111,7 +162,7 @@ export function buildAutoFixInstruction(appLabel, vuln, sequence, withDataNotice
111
162
  instruction += `\n**Action steps:**
112
163
  1. Search the codebase for ${locate}.
113
164
  2. If the finding applies: apply the required fix, following the project's existing code style and patterns, without breaking existing tests or functionality. Then call \`mark_vulnerability_fixed\` with \`vulnerability_id: "${vulnId}"\`.
114
- 3. If, after reading the code, it does NOT apply (false positive — e.g. the input is already validated, the route is not reachable, the endpoint is not served by this codebase): do not change code. Call \`dismiss_vulnerability\` with \`vulnerability_id: "${vulnId}"\` and a \`reason\` stating specifically what you saw in the code (e.g. "user id comes from the session, not the request — not exploitable"; not just "false positive").
165
+ 3. If, after reading the code, it does NOT apply (false positive — e.g. the input is already validated, the route is not reachable, the endpoint is not served by this codebase): do not change code. Call \`dismiss_vulnerability\` with \`vulnerability_id: "${vulnId}"\`, \`disposition: "false_positive"\`, \`reason: "other"\` and a \`comment\` starting "AI agent: " that states specifically, in one line, what you saw in the code (e.g. "AI agent: user id comes from the session, not the request — not exploitable"; not just "false positive").
115
166
 
116
167
  **Vulnerability ID:** ${vulnId}\n`;
117
168
  return instruction;
@@ -136,7 +187,7 @@ Work through every item below in order (critical → low), autonomously:
136
187
  - ${DATA_NOT_INSTRUCTIONS}
137
188
  - ${CODE_EDITS_ONLY}
138
189
  - Do not ask the user for confirmation between code edits, and do not stop until every item is handled.
139
- - Every item must end in exactly one of: \`mark_vulnerability_fixed\` (you changed code) or \`dismiss_vulnerability\` with a specific \`reason\` (it does not apply to this code).
190
+ - Every item must end in exactly one of: \`mark_vulnerability_fixed\` (you changed code) or \`dismiss_vulnerability\` with a specific \`comment\` (it does not apply to this code).
140
191
  - False positives are handled silently: dismiss them and move on. Do not mention them in the chat, list them, or explain them.
141
192
  `;
142
193
  plan += remaining > 0
@@ -72,11 +72,11 @@ const FALLBACK_WORDING = {
72
72
  partial: {
73
73
  needs_login: {
74
74
  label: "Completed, needs login",
75
- message: "Security scan completed, but we couldn't sign in to this app — add test accounts to also test logged-in areas",
75
+ message: "Security test completed, but we couldn't sign in to this app — add test accounts to also test logged-in areas",
76
76
  },
77
77
  default: {
78
78
  label: "Completed — partial",
79
- message: "Security scan completed, but some checks didn't run. We're looking into it.",
79
+ message: "Security test completed, but some checks didn't run. We're looking into it.",
80
80
  },
81
81
  },
82
82
  needs_input: {
@@ -105,11 +105,8 @@ export function canStartSecurityTest(view) {
105
105
  }
106
106
  export const PARTIAL_FINDINGS_NOTE = "get_vulnerabilities lists what was found so far — it does not cover everything, so an area with no " +
107
107
  "finding was not necessarily tested.";
108
- export function onboardingStartedMessage(name) {
109
- return `🚀 Onboarding ${name}. Say perfai issues later to view issues.`;
110
- }
111
108
  export function stillOnboardingMessage(name) {
112
- return `⏳ ${name} is still onboarding. Check again later.`;
109
+ return `⏳ ${name} is still onboarding. Perfai emails the app's owner when its first test finishes. Check again later.`;
113
110
  }
114
111
  export function describeStatus(status, record, intervention) {
115
112
  const served = servedStateOf(record);
@@ -51,11 +51,41 @@ function lastTestLine(list, totalIsOpenCount) {
51
51
  const open = openSummary(list, totalIsOpenCount);
52
52
  return open ? `Last test: ${when} · ${open}` : `Last test: ${when}`;
53
53
  }
54
- export function testRunningLine(lastCompleted) {
55
- if (lastCompleted === undefined)
56
- return "A test is running now.";
57
- return `A test is running now. Last completed test: ${formatTestTime(lastCompleted) ?? "none"}.`;
54
+ const STAGE_TEXT = {
55
+ queued: "waiting to start",
56
+ setting_up: "signing in and setting up",
57
+ testing: "testing",
58
+ finishing: "finishing up",
59
+ };
60
+ export function testRunningReply(run) {
61
+ const stage = typeof run.stage === "string" ? STAGE_TEXT[run.stage] : undefined;
62
+ const minutes = Number.isInteger(run.estimatedMinutesLeft) && run.estimatedMinutesLeft >= 1
63
+ ? run.estimatedMinutesLeft
64
+ : null;
65
+ const lines = [
66
+ stage ? `A test is running now: ${stage}${minutes ? `, about ${minutes} min left` : ""}.` : "A test is running now.",
67
+ ];
68
+ if (run.lastRunCompletedAt === null) {
69
+ lines.push("Last completed test: none.");
70
+ }
71
+ else if (run.lastRunCompletedAt !== undefined) {
72
+ const when = formatTestTime(run.lastRunCompletedAt);
73
+ if (!when) {
74
+ lines.push("Last completed test: none.");
75
+ }
76
+ else if (validCounts(run.severityCounts)) {
77
+ const { critical, high, medium, low } = run.severityCounts;
78
+ lines.push(`Last completed test: ${when} · Open: ${critical + high + medium + low} ` +
79
+ `(${critical} critical, ${high} high, ${medium} medium, ${low} low)`);
80
+ }
81
+ else {
82
+ lines.push(`Last completed test: ${when}`);
83
+ }
84
+ }
85
+ lines.push("Perfai emails the app's owner when it finishes.");
86
+ return lines.join("\n");
58
87
  }
88
+ export const NEXT_LINE = 'Next: say "perfai fix" to fix these in your code, then "perfai test" to check again.';
59
89
  export function issuesFirstLine(list, totalIsOpenCount) {
60
90
  if (list.status === "NO_RUNS")
61
91
  return "No completed test yet.";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "perfai-cloud-mcp",
3
- "version": "0.7.2",
3
+ "version": "0.7.5",
4
4
  "description": "Standalone MCP client for the hosted Perfai cloud API — register an app by URL, run a security test, pull findings, and get fix prompts from Claude Code, Cursor, or any MCP client.",
5
5
  "repository": {
6
6
  "type": "git",