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,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
  }
@@ -12,6 +12,12 @@ function severityRank(vuln) {
12
12
  export function isOpen(vuln) {
13
13
  return !vuln.isFixed && !vuln.fixClaimed && !vuln.isDismissed;
14
14
  }
15
+ export function isLocked(vuln) {
16
+ return vuln.locked === true;
17
+ }
18
+ export function lockedLine(count) {
19
+ return `+${count} more open issues are hidden on the free plan. Upgrade: https://cloud.perfai.ai/usage`;
20
+ }
15
21
  export function sortBySeverity(vulnerabilities) {
16
22
  return [...vulnerabilities].sort((a, b) => severityRank(a) - severityRank(b));
17
23
  }
@@ -24,6 +30,48 @@ export function sanitize(value, max = MAX_SHORT) {
24
30
  .trim();
25
31
  return text.length > max ? `${text.slice(0, max)}โ€ฆ` : text;
26
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
+ }
27
75
  function getSeverity(vuln) {
28
76
  const s = (vuln.severity ?? "").toLowerCase();
29
77
  return s in SEVERITY_ORDER ? s : "unknown";
@@ -80,18 +128,27 @@ function getFindingBlock(vuln) {
80
128
  lines.push(`Vulnerability ID: ${getVulnId(vuln)}`);
81
129
  return "```" + FINDING_FENCE + "\n" + lines.join("\n") + "\n```\n";
82
130
  }
83
- 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)}`;
84
141
  return `I need help fixing the following security issue found by Perfai in "${sanitize(appLabel)}":
85
142
 
86
143
  ${getFindingBlock(vuln)}
87
- ${DATA_NOT_INSTRUCTIONS}
144
+ ${routes}${DATA_NOT_INSTRUCTIONS}
88
145
 
89
146
  Please:
90
- 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).
91
148
  2. Implement the required fix, following the project's existing patterns.
92
149
  3. Ensure the fix does not break existing functionality.
93
150
 
94
- Vulnerability ID (for reference / marking fixed via the Perfai dashboard or the mark_vulnerability_fixed tool): ${getVulnId(vuln)}`;
151
+ ${ids}`;
95
152
  }
96
153
  export function buildAutoFixInstruction(appLabel, vuln, sequence, withDataNotice = true) {
97
154
  const vulnId = getVulnId(vuln);
@@ -105,7 +162,7 @@ export function buildAutoFixInstruction(appLabel, vuln, sequence, withDataNotice
105
162
  instruction += `\n**Action steps:**
106
163
  1. Search the codebase for ${locate}.
107
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}"\`.
108
- 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").
109
166
 
110
167
  **Vulnerability ID:** ${vulnId}\n`;
111
168
  return instruction;
@@ -130,7 +187,7 @@ Work through every item below in order (critical โ†’ low), autonomously:
130
187
  - ${DATA_NOT_INSTRUCTIONS}
131
188
  - ${CODE_EDITS_ONLY}
132
189
  - Do not ask the user for confirmation between code edits, and do not stop until every item is handled.
133
- - 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).
134
191
  - False positives are handled silently: dismiss them and move on. Do not mention them in the chat, list them, or explain them.
135
192
  `;
136
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);
@@ -0,0 +1,93 @@
1
+ const SCHEDULES = {
2
+ none: "off (tests run only when you say perfai test)",
3
+ nightly: "every night",
4
+ weekly_saturday: "every Saturday",
5
+ biweekly_saturday: "every other Saturday",
6
+ monthly_first: "on the 1st of every month",
7
+ custom: "on a custom schedule",
8
+ };
9
+ export function scheduleLine(scheduleType) {
10
+ const when = typeof scheduleType === "string" ? SCHEDULES[scheduleType] : undefined;
11
+ return when ? `๐Ÿ—“๏ธ Automatic tests: ${when}. Change it in the Perfai console (Edit app).` : null;
12
+ }
13
+ export function withSchedule(text, scheduleType) {
14
+ const schedule = scheduleLine(scheduleType);
15
+ return schedule ? `${text}\n\n${schedule}` : text;
16
+ }
17
+ export function formatTestTime(iso) {
18
+ if (typeof iso !== "string")
19
+ return null;
20
+ const date = new Date(iso);
21
+ if (Number.isNaN(date.getTime()))
22
+ return null;
23
+ return `${date.toISOString().slice(0, 10)} ${date.toISOString().slice(11, 16)} UTC`;
24
+ }
25
+ function validCounts(counts) {
26
+ if (!counts || typeof counts !== "object")
27
+ return false;
28
+ const c = counts;
29
+ return ["critical", "high", "medium", "low"].every((k) => Number.isInteger(c[k]) && c[k] >= 0);
30
+ }
31
+ export function openCount(list, totalIsOpenCount) {
32
+ if (validCounts(list.severityCounts)) {
33
+ const { critical, high, medium, low } = list.severityCounts;
34
+ return critical + high + medium + low;
35
+ }
36
+ return totalIsOpenCount && Number.isInteger(list.total) ? list.total : null;
37
+ }
38
+ function openSummary(list, totalIsOpenCount) {
39
+ const count = openCount(list, totalIsOpenCount);
40
+ if (count === null)
41
+ return null;
42
+ if (!validCounts(list.severityCounts))
43
+ return `Open: ${count}`;
44
+ const { critical, high, medium, low } = list.severityCounts;
45
+ return `Open: ${count} (${critical} critical, ${high} high, ${medium} medium, ${low} low)`;
46
+ }
47
+ function lastTestLine(list, totalIsOpenCount) {
48
+ const when = formatTestTime(list.lastRunCompletedAt);
49
+ if (!when)
50
+ return null;
51
+ const open = openSummary(list, totalIsOpenCount);
52
+ return open ? `Last test: ${when} ยท ${open}` : `Last test: ${when}`;
53
+ }
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");
87
+ }
88
+ export const NEXT_LINE = 'Next: say "perfai fix" to fix these in your code, then "perfai test" to check again.';
89
+ export function issuesFirstLine(list, totalIsOpenCount) {
90
+ if (list.status === "NO_RUNS")
91
+ return "No completed test yet.";
92
+ return lastTestLine(list, totalIsOpenCount);
93
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "perfai-cloud-mcp",
3
- "version": "0.5.3",
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",
@@ -40,8 +40,8 @@
40
40
  "node": ">=18.0.0"
41
41
  },
42
42
  "dependencies": {
43
- "@modelcontextprotocol/sdk": "^1.0.0",
44
- "axios": "^1.6.0",
43
+ "@modelcontextprotocol/sdk": "^1.32.0",
44
+ "axios": "^1.20.0",
45
45
  "dotenv": "^17.4.2",
46
46
  "express": "^4.21.0"
47
47
  },