perfai-cloud-mcp 0.5.3 β†’ 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.
@@ -1,8 +1,10 @@
1
1
  import { getApp, getTask, getVulnerabilities } from "../../client/apiClient.js";
2
- import { isForbiddenError } from "../../client/errors.js";
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 { groupFindings, isLocked, lockedLine } from "../../utils/promptBuilder.js";
5
6
  import { describeStatus, stillOnboardingMessage } from "../../utils/runState.js";
7
+ import { issuesFirstLine, NEXT_LINE, testRunningReply } from "../../utils/testInfo.js";
6
8
  export const DISMISSED_STAFF_ONLY = "πŸ”’ Dismissed findings are not listable on this account. To undo a dismissal, call reopen_vulnerability " +
7
9
  "with the ID from the dismiss reply.";
8
10
  const STATUS_FILTERS = {
@@ -14,7 +16,8 @@ export const getVulnerabilitiesTool = {
14
16
  name: "get_vulnerabilities",
15
17
  description: 'πŸ” "Perfai issues": list findings for an app (GET /v1/apps/{appId}/vulnerabilities). While the app is ' +
16
18
  "still onboarding it says so instead β€” show that message and stop, do not poll. Results get sequence numbers " +
17
- "(#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.",
18
21
  inputSchema: {
19
22
  type: "object",
20
23
  properties: {
@@ -45,6 +48,21 @@ async function isTestRunning(auth, appId) {
45
48
  return false;
46
49
  }
47
50
  }
51
+ async function runInProgress(auth, appId) {
52
+ try {
53
+ const result = await getVulnerabilities(auth, appId, { pageSize: 1 });
54
+ return result.status === "RUN_IN_PROGRESS" ? result : null;
55
+ }
56
+ catch (error) {
57
+ console.error(`Findings lookup failed for onboarding app ${appId}:`, error instanceof Error ? error.message : String(error));
58
+ return null;
59
+ }
60
+ }
61
+ function lockedCountOf(result, lockedOnPage) {
62
+ if (typeof result.lockedCount === "number")
63
+ return result.lockedCount;
64
+ return result.data.length >= result.total ? lockedOnPage : 0;
65
+ }
48
66
  export async function handleGetVulnerabilities(auth, args) {
49
67
  try {
50
68
  const resolved = await resolveApp(auth, args);
@@ -55,14 +73,15 @@ export async function handleGetVulnerabilities(auth, args) {
55
73
  const name = appName(app);
56
74
  const view = describeStatus(app.registrationStatus, app);
57
75
  if (view.outcome === "pending") {
58
- return { content: [{ type: "text", text: stillOnboardingMessage(name) }] };
76
+ const running = await runInProgress(auth, appId);
77
+ const text = running
78
+ ? testRunningReply({ ...running, lastRunCompletedAt: running.lastRunCompletedAt ?? null })
79
+ : stillOnboardingMessage(name);
80
+ return { content: [{ type: "text", text }] };
59
81
  }
60
82
  const notes = [];
61
83
  if (view.outcome === "needs_input")
62
84
  notes.push(`⏸️ ${name}: ${view.message}`);
63
- if (await isTestRunning(auth, appId)) {
64
- notes.push(`⏳ A security test is still running for ${name} β€” these are the issues found so far. Check again later.`);
65
- }
66
85
  const status = String(args?.status ?? "open").toLowerCase();
67
86
  const result = await getVulnerabilities(auth, appId, {
68
87
  ...(STATUS_FILTERS[status] ?? STATUS_FILTERS.open),
@@ -70,24 +89,52 @@ export async function handleGetVulnerabilities(auth, args) {
70
89
  pageSize: args?.pageSize,
71
90
  search: args?.search,
72
91
  });
73
- auth.cacheVulnerabilities(appId, result.data);
92
+ if (result.status === "RUN_IN_PROGRESS") {
93
+ const lastCompleted = "lastRunCompletedAt" in result ? (result.lastRunCompletedAt ?? null) : auth.lastTestOf(appId);
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 }) }] };
96
+ }
97
+ if (result.status === "NO_RUNS") {
98
+ auth.rememberLastTest(appId, null);
99
+ return { content: [{ type: "text", text: "No completed test yet." }] };
100
+ }
101
+ if (typeof result.lastRunCompletedAt === "string")
102
+ auth.rememberLastTest(appId, result.lastRunCompletedAt);
74
103
  const isOpenView = !(status in STATUS_FILTERS) || status === "open";
75
- const list = result.data.length === 0 && !isOpenView
76
- ? `No ${status} findings for ${name}.`
77
- : formatVulnerabilityList(result.data, result.total, result.page, result.pageSize);
104
+ const shown = result.data.filter((v) => !isLocked(v));
105
+ const lockedOnPage = result.data.length - shown.length;
106
+ const lockedTotal = isOpenView && !args?.search ? lockedCountOf(result, lockedOnPage) : lockedOnPage;
107
+ if (lockedOnPage > 0)
108
+ console.error(`get_vulnerabilities: app=${appId} ${lockedOnPage} locked row(s) left out, lockedCount=${result.lockedCount ?? "missing"}`);
109
+ const groups = groupFindings(shown);
110
+ auth.cacheVulnerabilityGroups(appId, groups);
111
+ const firstLine = (await isTestRunning(auth, appId))
112
+ ? testRunningReply({
113
+ lastRunCompletedAt: typeof result.lastRunCompletedAt === "string" ? result.lastRunCompletedAt : auth.lastTestOf(appId),
114
+ severityCounts: result.severityCounts,
115
+ })
116
+ : issuesFirstLine(result, isOpenView && !args?.search);
117
+ const list = shown.length === 0 && lockedOnPage > 0
118
+ ? null
119
+ : shown.length === 0 && !isOpenView
120
+ ? `No ${status} findings for ${name}.`
121
+ : formatVulnerabilityList(groups, shown.length, Math.max(shown.length, result.total - lockedTotal), result.page ?? 1);
122
+ const locked = isOpenView && !args?.search && lockedTotal > 0 ? [lockedLine(lockedTotal)] : [];
78
123
  const dismissedCount = result.dismissedCount;
79
124
  const hidden = isOpenView && typeof dismissedCount === "number" && dismissedCount > 0
80
125
  ? [`πŸ™ˆ ${dismissedCount} dismissed finding${dismissedCount === 1 ? "" : "s"} not shown. ` +
81
126
  "reopen_vulnerability with a finding's ID brings it back."]
82
127
  : [];
83
- return { content: [{ type: "text", text: [...notes, list, ...hidden].join("\n\n") }] };
128
+ const next = isOpenView && shown.length > 0 ? [NEXT_LINE] : [];
129
+ const body = [...(firstLine ? [firstLine] : []), ...locked, ...notes, ...(list ? [list] : []), ...hidden, ...next];
130
+ return { content: [{ type: "text", text: body.join("\n\n") }] };
84
131
  }
85
132
  catch (error) {
86
133
  if (String(args?.status ?? "").toLowerCase() === "dismissed" && isForbiddenError(error)) {
87
134
  return { content: [{ type: "text", text: DISMISSED_STAFF_ONLY }] };
88
135
  }
89
136
  return {
90
- content: [{ type: "text", text: `❌ Failed to fetch vulnerabilities: ${error instanceof Error ? error.message : String(error)}` }],
137
+ content: [{ type: "text", text: findingsFailureText(error) }],
91
138
  };
92
139
  }
93
140
  }
@@ -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,10 +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";
6
+ import { withSchedule } from "../../utils/testInfo.js";
5
7
  export const registerAppTool = {
6
8
  name: "register_app",
7
- 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 ' +
8
11
  "onboarding runs the first security test itself β€” the returned app becomes the 'current app' for " +
9
12
  "subsequent tools. Do not wait or poll afterwards: show the user the returned message and stop.",
10
13
  inputSchema: {
@@ -61,7 +64,8 @@ export async function handleRegisterApp(auth, args) {
61
64
  tenantOneCredentials,
62
65
  });
63
66
  auth.setCurrentApp(app.appId, args.appUrl);
64
- return { content: [{ type: "text", text: onboardingStartedMessage(appName({ ...app, appUrl: app.appUrl ?? args.appUrl })) }] };
67
+ const started = settingUpMessage(appName({ ...app, appUrl: app.appUrl ?? args.appUrl }), knownEmail(auth));
68
+ return { content: [{ type: "text", text: withSchedule(started, app.scheduleType) }] };
65
69
  }
66
70
  catch (error) {
67
71
  if (error instanceof ApiError && error.status === 409 && typeof error.data?.appId === "string") {
@@ -1,11 +1,13 @@
1
- import { getApp, registerApp, runSecurityAgent } from "../../client/apiClient.js";
1
+ import { getApp, getVulnerabilities, registerApp, runSecurityAgent } from "../../client/apiClient.js";
2
2
  import { ApiError, isAppNotRegisteredError } from "../../client/errors.js";
3
3
  import { APP_NAME_PROPERTY, appName, resolveApp } from "../../utils/appResolver.js";
4
- import { canStartSecurityTest, describeStatus, onboardingStartedMessage, PARTIAL_FINDINGS_NOTE, stillOnboardingMessage, } from "../../utils/runState.js";
4
+ import { canStartSecurityTest, describeStatus, PARTIAL_FINDINGS_NOTE, stillOnboardingMessage, } from "../../utils/runState.js";
5
+ import { openCount } from "../../utils/testInfo.js";
5
6
  export const runSecurityTestTool = {
6
7
  name: "run_security_test",
7
- description: 'πŸš€ "Perfai test": start a security test run (POST /v1/apps/{appId}/security-agent). A full URL that ' +
8
- "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 " +
9
11
  "runs the first security test itself. An onboarded app (COMPLETED, or COMPLETED_PARTIAL β€” tried; Perfai " +
10
12
  "says if that app can't be tested yet) gets a new security test. Either way the work runs in the " +
11
13
  "background: show the user the returned message and stop β€” do not poll.",
@@ -14,15 +16,23 @@ export const runSecurityTestTool = {
14
16
  properties: {
15
17
  app: {
16
18
  ...APP_NAME_PROPERTY,
17
- 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.`,
18
20
  },
19
21
  appId: { type: "string", description: "App ID (alternative to app; defaults to the current app)" },
20
22
  },
21
23
  additionalProperties: false,
22
24
  },
23
25
  };
24
- function isFullUrl(value) {
25
- 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;
26
36
  }
27
37
  function notReadyMessage(name, view) {
28
38
  switch (view.outcome) {
@@ -39,10 +49,54 @@ function refusedMessage(view) {
39
49
  return (`${view.label}: ${view.message}\n\nPerfai can't start a new security test on this app until its ` +
40
50
  `onboarding finishes β€” resolve what the message above asks, then try again. ${PARTIAL_FINDINGS_NOTE}`);
41
51
  }
52
+ async function lastTestBefore(auth, appId) {
53
+ try {
54
+ const list = await getVulnerabilities(auth, appId, { page: 1, pageSize: 1 });
55
+ if (list.status === "RUN_IN_PROGRESS")
56
+ return { open: null };
57
+ if (list.status === "NO_RUNS") {
58
+ auth.rememberLastTest(appId, null);
59
+ return { open: null };
60
+ }
61
+ if (typeof list.lastRunCompletedAt === "string")
62
+ auth.rememberLastTest(appId, list.lastRunCompletedAt);
63
+ return { open: openCount(list, true) };
64
+ }
65
+ catch (error) {
66
+ console.error(`run_security_test: app=${appId} last-test lookup failed: ${error instanceof Error ? error.message : String(error)}`);
67
+ return { open: null };
68
+ }
69
+ }
70
+ export function knownEmail(auth) {
71
+ const email = auth.getAuthenticatedEmail();
72
+ return email && email.includes("@") ? email : undefined;
73
+ }
74
+ export function testStartedMessage(taskId, open) {
75
+ return [
76
+ `Test started β€” ID ${taskId}.`,
77
+ open === null ? null : `Open issues from the last test: ${open}`,
78
+ "Perfai emails the app's owner when it finishes.",
79
+ ]
80
+ .filter(Boolean)
81
+ .join("\n");
82
+ }
83
+ export function settingUpMessage(name, email) {
84
+ return (`Perfai is setting up ${name} and will run its first test automatically. This takes up to 20 minutes.\n` +
85
+ (email ? `You'll get an email at ${email} when the test finishes. ` : "") +
86
+ 'Say "perfai status" to check.');
87
+ }
42
88
  async function registerByUrl(auth, appUrl) {
43
89
  try {
44
90
  const app = await registerApp(auth, { appUrl });
45
91
  auth.setCurrentApp(app.appId, appUrl);
92
+ if (auth.getPlan() === undefined) {
93
+ try {
94
+ await getApp(auth, app.appId);
95
+ }
96
+ catch (error) {
97
+ console.error(`Plan lookup failed for new app ${app.appId}:`, error instanceof Error ? error.message : String(error));
98
+ }
99
+ }
46
100
  return { app, created: true };
47
101
  }
48
102
  catch (error) {
@@ -61,14 +115,13 @@ export async function handleRunSecurityTest(auth, args) {
61
115
  if (resolved.ok) {
62
116
  app = await getApp(auth, resolved.app.appId);
63
117
  }
64
- else if (resolved.notFound && isFullUrl(args?.app)) {
65
- const appUrl = args.app.trim();
118
+ else if (resolved.notFound && appUrlOf(args?.app)) {
119
+ const appUrl = appUrlOf(args.app);
66
120
  const registered = await registerByUrl(auth, appUrl);
67
121
  if (registered.created) {
68
122
  console.error(`run_security_test: registered ${appUrl} as app=${registered.app.appId}`);
69
- return {
70
- content: [{ type: "text", text: onboardingStartedMessage(appName({ ...registered.app, appUrl: registered.app.appUrl ?? appUrl })) }],
71
- };
123
+ const name = appName({ ...registered.app, appUrl: registered.app.appUrl ?? appUrl });
124
+ return { content: [{ type: "text", text: settingUpMessage(name, knownEmail(auth)) }] };
72
125
  }
73
126
  app = registered.app;
74
127
  }
@@ -82,6 +135,7 @@ export async function handleRunSecurityTest(auth, args) {
82
135
  console.error(`run_security_test: app=${appId} not ready, status=${app.registrationStatus ?? "none"} outcome=${view.outcome}`);
83
136
  return { content: [{ type: "text", text: notReadyMessage(name, view) }] };
84
137
  }
138
+ const lastTest = await lastTestBefore(auth, appId);
85
139
  let task;
86
140
  try {
87
141
  task = await runSecurityAgent(auth, appId);
@@ -95,7 +149,7 @@ export async function handleRunSecurityTest(auth, args) {
95
149
  }
96
150
  auth.setCurrentTask(task.taskId, appId);
97
151
  return {
98
- content: [{ type: "text", text: `πŸš€ Security test started for ${name}. Say perfai issues later to view issues.` }],
152
+ content: [{ type: "text", text: testStartedMessage(task.taskId, lastTest.open) }],
99
153
  };
100
154
  }
101
155
  catch (error) {
@@ -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,8 @@
1
+ export function clientLabel(info) {
2
+ const clean = (value, max) => typeof value === "string" ? value.replace(/[^A-Za-z0-9 ._@/+-]/g, "").trim().slice(0, max) : "";
3
+ const name = clean(info?.name, 60);
4
+ if (!name)
5
+ return "unknown";
6
+ const version = clean(info?.version, 20);
7
+ return version ? `${name} ${version}` : name;
8
+ }
@@ -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
+ }