perfai-cloud-mcp 0.3.0 โ†’ 0.5.3

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.
Files changed (104) hide show
  1. package/README.md +45 -24
  2. package/dist/auth/bearerAuth.js +53 -0
  3. package/dist/auth/oauthFlow.js +1 -19
  4. package/dist/auth/pkce.js +0 -8
  5. package/dist/auth/tokenValidator.js +77 -67
  6. package/dist/cli.js +85 -52
  7. package/dist/client/apiClient.js +18 -25
  8. package/dist/client/authManager.js +42 -51
  9. package/dist/client/errors.js +42 -14
  10. package/dist/config.js +35 -38
  11. package/dist/env.js +0 -6
  12. package/dist/log-guard.js +0 -9
  13. package/dist/prompts.js +2 -8
  14. package/dist/server.js +45 -176
  15. package/dist/tools/protected/autoFix.js +0 -1
  16. package/dist/tools/protected/autoFixAll.js +4 -7
  17. package/dist/tools/protected/checkAppStatus.js +34 -32
  18. package/dist/tools/protected/checkTaskStatus.js +29 -28
  19. package/dist/tools/protected/getFixSummary.js +41 -11
  20. package/dist/tools/protected/getVulnerabilities.js +58 -8
  21. package/dist/tools/protected/manageOrganizations.js +4 -5
  22. package/dist/tools/protected/registerApp.js +17 -33
  23. package/dist/tools/protected/runSecurityTest.js +82 -26
  24. package/dist/tools/protected/submitAppCredentials.js +4 -3
  25. package/dist/tools/protected/vulnerabilityActions.js +32 -8
  26. package/dist/tools/public/authStatus.js +2 -2
  27. package/dist/tools/public/login.js +3 -27
  28. package/dist/utils/appResolver.js +25 -85
  29. package/dist/utils/formatters.js +9 -9
  30. package/dist/utils/poll.js +0 -7
  31. package/dist/utils/promptBuilder.js +93 -94
  32. package/dist/utils/registrationState.js +28 -0
  33. package/dist/utils/runState.js +129 -0
  34. package/package.json +6 -2
  35. package/dist/auth/oauthFlow.d.ts +0 -23
  36. package/dist/auth/oauthFlow.d.ts.map +0 -1
  37. package/dist/auth/pkce.d.ts +0 -11
  38. package/dist/auth/pkce.d.ts.map +0 -1
  39. package/dist/auth/tokenValidator.d.ts +0 -40
  40. package/dist/auth/tokenValidator.d.ts.map +0 -1
  41. package/dist/cli.d.ts +0 -3
  42. package/dist/cli.d.ts.map +0 -1
  43. package/dist/client/apiClient.d.ts +0 -36
  44. package/dist/client/apiClient.d.ts.map +0 -1
  45. package/dist/client/authManager.d.ts +0 -61
  46. package/dist/client/authManager.d.ts.map +0 -1
  47. package/dist/client/errors.d.ts +0 -10
  48. package/dist/client/errors.d.ts.map +0 -1
  49. package/dist/client/types.d.ts +0 -72
  50. package/dist/client/types.d.ts.map +0 -1
  51. package/dist/config.d.ts +0 -27
  52. package/dist/config.d.ts.map +0 -1
  53. package/dist/env.d.ts +0 -2
  54. package/dist/env.d.ts.map +0 -1
  55. package/dist/log-guard.d.ts +0 -2
  56. package/dist/log-guard.d.ts.map +0 -1
  57. package/dist/prompts.d.ts +0 -31
  58. package/dist/prompts.d.ts.map +0 -1
  59. package/dist/server.d.ts +0 -4
  60. package/dist/server.d.ts.map +0 -1
  61. package/dist/tools/index.d.ts +0 -404
  62. package/dist/tools/index.d.ts.map +0 -1
  63. package/dist/tools/protected/autoFix.d.ts +0 -26
  64. package/dist/tools/protected/autoFix.d.ts.map +0 -1
  65. package/dist/tools/protected/autoFixAll.d.ts +0 -30
  66. package/dist/tools/protected/autoFixAll.d.ts.map +0 -1
  67. package/dist/tools/protected/checkAppStatus.d.ts +0 -21
  68. package/dist/tools/protected/checkAppStatus.d.ts.map +0 -1
  69. package/dist/tools/protected/checkTaskStatus.d.ts +0 -21
  70. package/dist/tools/protected/checkTaskStatus.d.ts.map +0 -1
  71. package/dist/tools/protected/getFixSummary.d.ts +0 -21
  72. package/dist/tools/protected/getFixSummary.d.ts.map +0 -1
  73. package/dist/tools/protected/getVulnerabilities.d.ts +0 -33
  74. package/dist/tools/protected/getVulnerabilities.d.ts.map +0 -1
  75. package/dist/tools/protected/listApps.d.ts +0 -25
  76. package/dist/tools/protected/listApps.d.ts.map +0 -1
  77. package/dist/tools/protected/logout.d.ts +0 -12
  78. package/dist/tools/protected/logout.d.ts.map +0 -1
  79. package/dist/tools/protected/manageOrganizations.d.ts +0 -26
  80. package/dist/tools/protected/manageOrganizations.d.ts.map +0 -1
  81. package/dist/tools/protected/registerApp.d.ts +0 -33
  82. package/dist/tools/protected/registerApp.d.ts.map +0 -1
  83. package/dist/tools/protected/runSecurityTest.d.ts +0 -21
  84. package/dist/tools/protected/runSecurityTest.d.ts.map +0 -1
  85. package/dist/tools/protected/selectApp.d.ts +0 -18
  86. package/dist/tools/protected/selectApp.d.ts.map +0 -1
  87. package/dist/tools/protected/submitAppCredentials.d.ts +0 -22
  88. package/dist/tools/protected/submitAppCredentials.d.ts.map +0 -1
  89. package/dist/tools/protected/suggestFix.d.ts +0 -22
  90. package/dist/tools/protected/suggestFix.d.ts.map +0 -1
  91. package/dist/tools/protected/vulnerabilityActions.d.ts +0 -70
  92. package/dist/tools/protected/vulnerabilityActions.d.ts.map +0 -1
  93. package/dist/tools/public/authStatus.d.ts +0 -12
  94. package/dist/tools/public/authStatus.d.ts.map +0 -1
  95. package/dist/tools/public/login.d.ts +0 -31
  96. package/dist/tools/public/login.d.ts.map +0 -1
  97. package/dist/utils/appResolver.d.ts +0 -24
  98. package/dist/utils/appResolver.d.ts.map +0 -1
  99. package/dist/utils/formatters.d.ts +0 -8
  100. package/dist/utils/formatters.d.ts.map +0 -1
  101. package/dist/utils/poll.d.ts +0 -19
  102. package/dist/utils/poll.d.ts.map +0 -1
  103. package/dist/utils/promptBuilder.d.ts +0 -26
  104. package/dist/utils/promptBuilder.d.ts.map +0 -1
@@ -1,20 +1,14 @@
1
1
  import { getTask } from "../../client/apiClient.js";
2
- import { formatTask } from "../../utils/formatters.js";
3
- import { pollWithBudget } from "../../utils/poll.js";
4
- import { DEFAULT_TOOL_POLL_BUDGET_MS, MAX_TOOL_POLL_BUDGET_MS, POLL_MAX_INTERVAL_MS, POLL_START_MS, TASK_TERMINAL_STATES } from "../../config.js";
2
+ import { describeStatus, PARTIAL_FINDINGS_NOTE } from "../../utils/runState.js";
5
3
  export const checkTaskStatusTool = {
6
4
  name: "check_task_status",
7
- description: "โณ Poll GET /v1/tasks/{taskId} (e.g. a security test run). Polls in-process (5sโ†’60s backoff) for " +
8
- "up to wait_seconds before returning โ€” call again if it's still QUEUED/RUNNING. Terminal states: " +
9
- "COMPLETED, FAILED, CANCELLED, INTERRUPTED.",
5
+ description: "โณ Check a task once (GET /v1/tasks/{taskId}, e.g. a security test run) and return right away. " +
6
+ "Call it only when the user asks for the status โ€” never repeatedly to wait for the security test, " +
7
+ "which runs in the background. Show the user the returned message as-is.",
10
8
  inputSchema: {
11
9
  type: "object",
12
10
  properties: {
13
11
  taskId: { type: "string", description: "Task ID (defaults to the most recently started task)" },
14
- wait_seconds: {
15
- type: "number",
16
- description: "Max seconds to poll before returning current status (default 20, max 240)",
17
- },
18
12
  },
19
13
  additionalProperties: false,
20
14
  },
@@ -24,26 +18,33 @@ export async function handleCheckTaskStatus(auth, args) {
24
18
  if (!taskId) {
25
19
  return { content: [{ type: "text", text: "โŒ No task to check. Run run_security_test first." }] };
26
20
  }
27
- const budgetMs = Math.min(args?.wait_seconds ? args.wait_seconds * 1000 : DEFAULT_TOOL_POLL_BUDGET_MS, MAX_TOOL_POLL_BUDGET_MS);
28
21
  try {
29
- const { value: task, terminal } = await pollWithBudget({
30
- fetch: () => getTask(auth, taskId),
31
- isTerminal: (t) => TASK_TERMINAL_STATES.has(t.state ?? ""),
32
- budgetMs,
33
- startIntervalMs: POLL_START_MS,
34
- maxIntervalMs: POLL_MAX_INTERVAL_MS,
35
- });
36
- let hint = "";
37
- if (task.state === "COMPLETED") {
38
- hint = "\n\nโœ… Done โ€” run get_vulnerabilities to see findings.";
22
+ const task = await getTask(auth, taskId);
23
+ const view = describeStatus(task.state, task, task.result?.intervention);
24
+ console.error(`check_task_status: task=${taskId} state=${task.state ?? "none"} outcome=${view.outcome}`);
25
+ let text;
26
+ switch (view.outcome) {
27
+ case "ready":
28
+ text = "โœ… Security test is complete. Say perfai issues to view issues.";
29
+ break;
30
+ case "partial":
31
+ text = `${view.message}\n\nThis security test did not cover everything. ${PARTIAL_FINDINGS_NOTE}`;
32
+ break;
33
+ case "needs_input":
34
+ text =
35
+ `โธ๏ธ ${view.message}\n\nIf it needs a login, supply one with submit_app_credentials. ` +
36
+ "Otherwise resolve it in the Perfai console.";
37
+ break;
38
+ case "interrupted":
39
+ text = `${view.message}\n\nYou can start a new security test later with run_security_test.`;
40
+ break;
41
+ case "cancelled":
42
+ text = view.message;
43
+ break;
44
+ default:
45
+ text = "โณ Security test is still running. Check again later.";
39
46
  }
40
- else if (task.state === "FAILED" || task.state === "CANCELLED" || task.state === "INTERRUPTED") {
41
- hint = `\n\nโŒ Run did not complete successfully (${task.state}).`;
42
- }
43
- else if (!terminal) {
44
- hint = `\n\nโณ Still ${task.state ?? "pending"} after ${Math.round(budgetMs / 1000)}s โ€” call check_task_status again.`;
45
- }
46
- return { content: [{ type: "text", text: formatTask(task) + hint }] };
47
+ return { content: [{ type: "text", text }] };
47
48
  }
48
49
  catch (error) {
49
50
  return {
@@ -1,10 +1,12 @@
1
- import { getAllVulnerabilities } from "../../client/apiClient.js";
1
+ import { listAllVulnerabilities } from "../../client/apiClient.js";
2
+ import { isForbiddenError } from "../../client/errors.js";
2
3
  import { APP_NAME_PROPERTY, resolveApp } from "../../utils/appResolver.js";
3
4
  import { isOpen } from "../../utils/promptBuilder.js";
4
5
  export const getFixSummaryTool = {
5
6
  name: "get_fix_summary",
6
7
  description: "๐Ÿ“Š Show fix progress for an app โ€” fixed, skipped as not applicable (dismissed), and still open, " +
7
- "broken down by severity. Call it at the end of an auto_fix_all run and report its one-line counts.",
8
+ "broken down by severity. Call it at the end of an auto_fix_all run and report its one-line counts. " +
9
+ "Every account gets the skipped total; only Perfai staff get it broken down by severity.",
8
10
  inputSchema: {
9
11
  type: "object",
10
12
  properties: {
@@ -23,25 +25,44 @@ const SEVERITY_ICON = {
23
25
  medium: "๐ŸŸก",
24
26
  low: "๐ŸŸข",
25
27
  };
26
- // A fix claim counts as fixed here; it is confirmed (isFixed) or dropped by the next scan.
27
28
  const isFixedOrClaimed = (v) => Boolean(v.isFixed || v.fixClaimed);
28
29
  const isSkipped = (v) => Boolean(v.isDismissed && !isFixedOrClaimed(v));
30
+ async function getEveryFinding(auth, appId) {
31
+ const byId = new Map();
32
+ const add = (list) => list.forEach(v => byId.set(String(v.id ?? v._id ?? `#${byId.size}`), v));
33
+ const current = await listAllVulnerabilities(auth, appId);
34
+ add(current.data);
35
+ add((await listAllVulnerabilities(auth, appId, { isFixed: true })).data);
36
+ let dismissed;
37
+ try {
38
+ add((await listAllVulnerabilities(auth, appId, { isDismissed: true })).data);
39
+ dismissed = { listed: true };
40
+ }
41
+ catch (error) {
42
+ if (!isForbiddenError(error))
43
+ throw error;
44
+ dismissed = { listed: false, count: current.dismissedCount };
45
+ }
46
+ return { findings: [...byId.values()], dismissed };
47
+ }
29
48
  export async function handleGetFixSummary(auth, args) {
30
49
  try {
31
50
  const resolved = await resolveApp(auth, args);
32
51
  if (!resolved.ok)
33
52
  return { content: [{ type: "text", text: resolved.message }] };
34
53
  const { appId, label } = resolved.app;
35
- const allVulnerabilities = await getAllVulnerabilities(auth, appId);
36
- const total = allVulnerabilities.length;
54
+ const { findings: allVulnerabilities, dismissed } = await getEveryFinding(auth, appId);
55
+ const unknown = !dismissed.listed && typeof dismissed.count !== "number";
56
+ const countOnly = !dismissed.listed && !unknown ? dismissed.count : 0;
57
+ const total = allVulnerabilities.length + countOnly;
37
58
  if (total === 0) {
38
59
  return { content: [{ type: "text", text: `No vulnerabilities found for "${label}".` }] };
39
60
  }
40
61
  const fixed = allVulnerabilities.filter(isFixedOrClaimed);
41
62
  const pendingRescan = allVulnerabilities.filter(v => v.fixClaimed && !v.isFixed);
42
- const skipped = allVulnerabilities.filter(isSkipped);
63
+ const skipped = allVulnerabilities.filter(isSkipped).length + countOnly;
43
64
  const open = allVulnerabilities.filter(isOpen);
44
- // Breakdown by severity
65
+ const skippedCell = unknown ? "?" : String(skipped);
45
66
  const severities = ["critical", "high", "medium", "low"];
46
67
  const breakdownRows = severities
47
68
  .map(s => {
@@ -50,7 +71,7 @@ export async function handleGetFixSummary(auth, args) {
50
71
  if (all.length === 0)
51
72
  return null;
52
73
  const f = all.filter(isFixedOrClaimed).length;
53
- const d = all.filter(isSkipped).length;
74
+ const d = dismissed.listed ? String(all.filter(isSkipped).length) : "โ€”";
54
75
  const o = all.filter(isOpen).length;
55
76
  return `| ${icon} ${s.charAt(0).toUpperCase() + s.slice(1)} | ${all.length} | ${f} | ${d} | ${o} |`;
56
77
  })
@@ -59,15 +80,24 @@ export async function handleGetFixSummary(auth, args) {
59
80
  const pct = Math.round((fixed.length / total) * 100);
60
81
  const progressBar = "โ–ˆ".repeat(Math.round(pct / 5)) + "โ–‘".repeat(20 - Math.round(pct / 5));
61
82
  let summary = `# Fix Progress: ${label}\n\n`;
62
- summary += `**${fixed.length} fixed, ${skipped.length} skipped as not applicable, ${open.length} still open.**\n\n`;
83
+ summary += unknown
84
+ ? `**${fixed.length} fixed, ${open.length} still open** (dismissed findings could not be counted).\n\n`
85
+ : `**${fixed.length} fixed, ${skipped} skipped as not applicable, ${open.length} still open.**\n\n`;
63
86
  summary += `\`${progressBar}\` **${pct}%** (${fixed.length}/${total} fixed)\n\n`;
64
87
  summary += `| Severity | Total | Fixed | Skipped | Open |\n`;
65
88
  summary += `| --- | --- | --- | --- | --- |\n`;
66
- summary += breakdownRows + "\n";
67
- summary += `| **Total** | **${total}** | **${fixed.length}** | **${skipped.length}** | **${open.length}** |\n\n`;
89
+ if (breakdownRows)
90
+ summary += breakdownRows + "\n";
91
+ summary += `| **Total** | **${total}** | **${fixed.length}** | **${skippedCell}** | **${open.length}** |\n\n`;
68
92
  if (pendingRescan.length > 0) {
69
93
  summary += `${pendingRescan.length} of the fixed are claimed fixes โ€” the next security test confirms them.\n`;
70
94
  }
95
+ if (unknown) {
96
+ summary += `Dismissed findings could not be counted right now, so the total leaves them out โ€” check again later.\n`;
97
+ }
98
+ else if (!dismissed.listed && skipped > 0) {
99
+ summary += `Skipped is a total only: dismissed findings are not listable on this account.\n`;
100
+ }
71
101
  if (open.length > 0) {
72
102
  summary += `**${open.length} vulnerabilities still need fixing.** Run \`auto_fix_all\` to continue.\n`;
73
103
  }
@@ -1,15 +1,31 @@
1
- import { getVulnerabilities } from "../../client/apiClient.js";
2
- import { APP_NAME_PROPERTY, resolveApp } from "../../utils/appResolver.js";
1
+ import { getApp, getTask, getVulnerabilities } from "../../client/apiClient.js";
2
+ import { isForbiddenError } from "../../client/errors.js";
3
+ import { APP_NAME_PROPERTY, appName, resolveApp } from "../../utils/appResolver.js";
3
4
  import { formatVulnerabilityList } from "../../utils/formatters.js";
5
+ import { describeStatus, stillOnboardingMessage } from "../../utils/runState.js";
6
+ export const DISMISSED_STAFF_ONLY = "๐Ÿ”’ Dismissed findings are not listable on this account. To undo a dismissal, call reopen_vulnerability " +
7
+ "with the ID from the dismiss reply.";
8
+ const STATUS_FILTERS = {
9
+ open: {},
10
+ fixed: { isFixed: true },
11
+ dismissed: { isDismissed: true },
12
+ };
4
13
  export const getVulnerabilitiesTool = {
5
14
  name: "get_vulnerabilities",
6
- description: "๐Ÿ” List findings for an app (GET /v1/apps/{appId}/vulnerabilities). Results get sequence numbers " +
15
+ description: '๐Ÿ” "Perfai issues": list findings for an app (GET /v1/apps/{appId}/vulnerabilities). While the app is ' +
16
+ "still onboarding it says so instead โ€” show that message and stop, do not poll. Results get sequence numbers " +
7
17
  "(#1, #2, ...) you can pass to suggest_fix / dismiss_vulnerability / reopen_vulnerability / mark_vulnerability_fixed.",
8
18
  inputSchema: {
9
19
  type: "object",
10
20
  properties: {
11
21
  app: APP_NAME_PROPERTY,
12
22
  appId: { type: "string", description: "App ID (alternative to app; defaults to the current app)" },
23
+ status: {
24
+ type: "string",
25
+ enum: ["open", "fixed", "dismissed"],
26
+ description: "open (default): findings still to fix, including claimed fixes. fixed: fixes Perfai has confirmed. " +
27
+ "dismissed: dismissed findings โ€” Perfai staff only; other accounts are told they are not listable.",
28
+ },
13
29
  search: { type: "string", description: "Case-insensitive keyword search" },
14
30
  page: { type: "number", description: "Page number (default 1)" },
15
31
  pageSize: { type: "number", description: "Results per page, 1-100 (default 20)" },
@@ -17,25 +33,59 @@ export const getVulnerabilitiesTool = {
17
33
  additionalProperties: false,
18
34
  },
19
35
  };
36
+ async function isTestRunning(auth, appId) {
37
+ if (!auth.currentTaskId || auth.currentTaskAppId !== appId)
38
+ return false;
39
+ try {
40
+ const task = await getTask(auth, auth.currentTaskId);
41
+ return describeStatus(task.state, task).outcome === "pending";
42
+ }
43
+ catch (error) {
44
+ console.error(`Task lookup failed for ${auth.currentTaskId}:`, error instanceof Error ? error.message : String(error));
45
+ return false;
46
+ }
47
+ }
20
48
  export async function handleGetVulnerabilities(auth, args) {
21
49
  try {
22
50
  const resolved = await resolveApp(auth, args);
23
51
  if (!resolved.ok)
24
52
  return { content: [{ type: "text", text: resolved.message }] };
25
53
  const { appId } = resolved.app;
54
+ const app = await getApp(auth, appId);
55
+ const name = appName(app);
56
+ const view = describeStatus(app.registrationStatus, app);
57
+ if (view.outcome === "pending") {
58
+ return { content: [{ type: "text", text: stillOnboardingMessage(name) }] };
59
+ }
60
+ const notes = [];
61
+ if (view.outcome === "needs_input")
62
+ 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
+ const status = String(args?.status ?? "open").toLowerCase();
26
67
  const result = await getVulnerabilities(auth, appId, {
68
+ ...(STATUS_FILTERS[status] ?? STATUS_FILTERS.open),
27
69
  page: args?.page,
28
70
  pageSize: args?.pageSize,
29
71
  search: args?.search,
30
72
  });
31
73
  auth.cacheVulnerabilities(appId, result.data);
32
- return {
33
- content: [
34
- { type: "text", text: formatVulnerabilityList(result.data, result.total, result.page, result.pageSize) },
35
- ],
36
- };
74
+ 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);
78
+ const dismissedCount = result.dismissedCount;
79
+ const hidden = isOpenView && typeof dismissedCount === "number" && dismissedCount > 0
80
+ ? [`๐Ÿ™ˆ ${dismissedCount} dismissed finding${dismissedCount === 1 ? "" : "s"} not shown. ` +
81
+ "reopen_vulnerability with a finding's ID brings it back."]
82
+ : [];
83
+ return { content: [{ type: "text", text: [...notes, list, ...hidden].join("\n\n") }] };
37
84
  }
38
85
  catch (error) {
86
+ if (String(args?.status ?? "").toLowerCase() === "dismissed" && isForbiddenError(error)) {
87
+ return { content: [{ type: "text", text: DISMISSED_STAFF_ONLY }] };
88
+ }
39
89
  return {
40
90
  content: [{ type: "text", text: `โŒ Failed to fetch vulnerabilities: ${error instanceof Error ? error.message : String(error)}` }],
41
91
  };
@@ -2,10 +2,10 @@ import { getUserOrganizations } from "../../client/apiClient.js";
2
2
  import { formatOrganizations } from "../../utils/formatters.js";
3
3
  export const manageOrganizationsTool = {
4
4
  name: "manage_organizations",
5
- description: "๐Ÿข List and switch between organizations (tenants) this account belongs to. Not needed before " +
6
- "fixing or scanning: tools that take an app name search every org and select the right one " +
7
- "automatically. Use this only when the user asks about orgs, or before register_app / list_apps " +
8
- "in a non-default org. Use action=select with sequence (number from the list) or org_id.",
5
+ description: "๐Ÿข List and switch between organizations (tenants) this account belongs to. Every other tool works " +
6
+ "in the selected organization only โ€” an app name is never looked up in another org. Use this when " +
7
+ "the user asks about orgs or asks to work in another org (e.g. an app was not found in the current " +
8
+ "one). Use action=select with sequence (number from the list) or org_id.",
9
9
  inputSchema: {
10
10
  type: "object",
11
11
  properties: {
@@ -111,7 +111,6 @@ export async function handleManageOrganizations(auth, args) {
111
111
  ],
112
112
  };
113
113
  }
114
- // Default action: list (fetch first if nothing cached yet)
115
114
  let organizations = auth.getOrganizations();
116
115
  if (organizations.length === 0) {
117
116
  organizations = await fetchAndCacheOrganizations(auth);
@@ -1,11 +1,12 @@
1
1
  import { registerApp, getApp } from "../../client/apiClient.js";
2
2
  import { ApiError } from "../../client/errors.js";
3
- import { formatApp } from "../../utils/formatters.js";
3
+ import { appName } from "../../utils/appResolver.js";
4
+ import { canStartSecurityTest, describeStatus, onboardingStartedMessage, stillOnboardingMessage } from "../../utils/runState.js";
4
5
  export const registerAppTool = {
5
6
  name: "register_app",
6
- description: "๐Ÿ“ฑ Register an app by its deployed URL (POST /v1/apps). Perfai onboards it autonomously โ€” " +
7
- "the returned app becomes the 'current app' for subsequent tools. First onboarding can take a " +
8
- "while; follow up with check_app_status until registrationStatus is COMPLETED.",
7
+ description: "๐Ÿ“ฑ Register an app by its deployed URL (POST /v1/apps). Perfai onboards it in the background, and " +
8
+ "onboarding runs the first security test itself โ€” the returned app becomes the 'current app' for " +
9
+ "subsequent tools. Do not wait or poll afterwards: show the user the returned message and stop.",
9
10
  inputSchema: {
10
11
  type: "object",
11
12
  properties: {
@@ -28,6 +29,16 @@ export const registerAppTool = {
28
29
  additionalProperties: false,
29
30
  },
30
31
  };
32
+ function existingAppMessage(app, appUrl) {
33
+ const name = appName({ ...app, appUrl: app.appUrl ?? appUrl });
34
+ const view = describeStatus(app.registrationStatus, app);
35
+ if (view.outcome === "pending")
36
+ return stillOnboardingMessage(name);
37
+ if (canStartSecurityTest(view)) {
38
+ return `โ„น๏ธ ${name} is already onboarded. Say perfai test to run a new security test, or perfai issues to view issues.`;
39
+ }
40
+ return `${name}: ${view.message}`;
41
+ }
31
42
  function isPlainObject(value) {
32
43
  return typeof value === "object" && value !== null && !Array.isArray(value);
33
44
  }
@@ -35,10 +46,6 @@ export async function handleRegisterApp(auth, args) {
35
46
  if (!args?.appUrl) {
36
47
  return { content: [{ type: "text", text: "โŒ appUrl is required." }] };
37
48
  }
38
- // Some MCP clients pre-fill optional object/array fields with placeholder
39
- // values (e.g. a description string) when a tool is invoked with defaults.
40
- // Only forward these if they're actually well-formed, so a bad client
41
- // default can't get misinterpreted by the API's validation.
42
49
  const tenantOneCredentials = isPlainObject(args.tenantOneCredentials) && Object.keys(args.tenantOneCredentials).length > 0
43
50
  ? args.tenantOneCredentials
44
51
  : undefined;
@@ -54,39 +61,16 @@ export async function handleRegisterApp(auth, args) {
54
61
  tenantOneCredentials,
55
62
  });
56
63
  auth.setCurrentApp(app.appId, args.appUrl);
57
- return {
58
- content: [
59
- {
60
- type: "text",
61
- text: `โœ… App registered.\n\n${formatApp(app)}\n\n` +
62
- `Next: check_app_status to poll until registrationStatus is COMPLETED, then run_security_test.`,
63
- },
64
- ],
65
- };
64
+ return { content: [{ type: "text", text: onboardingStartedMessage(appName({ ...app, appUrl: app.appUrl ?? args.appUrl })) }] };
66
65
  }
67
66
  catch (error) {
68
- // Perfai treats appUrl as unique โ€” a 409 here means it's already
69
- // registered. Rather than just failing, pick up the existing app so the
70
- // rest of the workflow (check_app_status, run_security_test, ...) keeps
71
- // working without the caller having to copy the appId out of the error.
72
67
  if (error instanceof ApiError && error.status === 409 && typeof error.data?.appId === "string") {
73
68
  try {
74
69
  const existing = await getApp(auth, error.data.appId);
75
70
  auth.setCurrentApp(existing.appId, args.appUrl);
76
- return {
77
- content: [
78
- {
79
- type: "text",
80
- text: `โ„น๏ธ This URL is already registered โ€” selected the existing app instead.\n\n${formatApp(existing)}\n\n` +
81
- (existing.registrationStatus === "COMPLETED"
82
- ? "Ready โ€” run run_security_test to start a scan."
83
- : "Run check_app_status to check on it."),
84
- },
85
- ],
86
- };
71
+ return { content: [{ type: "text", text: existingAppMessage(existing, args.appUrl) }] };
87
72
  }
88
73
  catch {
89
- // fall through to the generic error below
90
74
  }
91
75
  }
92
76
  return {
@@ -1,45 +1,101 @@
1
- import { getApp, runSecurityAgent } from "../../client/apiClient.js";
2
- import { APP_NAME_PROPERTY, resolveApp } from "../../utils/appResolver.js";
1
+ import { getApp, registerApp, runSecurityAgent } from "../../client/apiClient.js";
2
+ import { ApiError, isAppNotRegisteredError } from "../../client/errors.js";
3
+ import { APP_NAME_PROPERTY, appName, resolveApp } from "../../utils/appResolver.js";
4
+ import { canStartSecurityTest, describeStatus, onboardingStartedMessage, PARTIAL_FINDINGS_NOTE, stillOnboardingMessage, } from "../../utils/runState.js";
3
5
  export const runSecurityTestTool = {
4
6
  name: "run_security_test",
5
- description: "๐Ÿš€ Start a security test run (POST /v1/apps/{appId}/security-agent). Requires registrationStatus " +
6
- "COMPLETED โ€” run check_app_status first. Returns a taskId; poll it with check_task_status.",
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 " +
9
+ "runs the first security test itself. An onboarded app (COMPLETED, or COMPLETED_PARTIAL โ€” tried; Perfai " +
10
+ "says if that app can't be tested yet) gets a new security test. Either way the work runs in the " +
11
+ "background: show the user the returned message and stop โ€” do not poll.",
7
12
  inputSchema: {
8
13
  type: "object",
9
14
  properties: {
10
- app: APP_NAME_PROPERTY,
15
+ app: {
16
+ ...APP_NAME_PROPERTY,
17
+ description: `${APP_NAME_PROPERTY.description} A full https:// URL that is not registered yet is registered.`,
18
+ },
11
19
  appId: { type: "string", description: "App ID (alternative to app; defaults to the current app)" },
12
20
  },
13
21
  additionalProperties: false,
14
22
  },
15
23
  };
24
+ function isFullUrl(value) {
25
+ return typeof value === "string" && /^https?:\/\/\S+$/i.test(value.trim());
26
+ }
27
+ function notReadyMessage(name, view) {
28
+ switch (view.outcome) {
29
+ case "pending":
30
+ return stillOnboardingMessage(name);
31
+ case "needs_input":
32
+ return (`โธ๏ธ ${name}: ${view.message}\n\nIf it needs a login, supply one with submit_app_credentials, ` +
33
+ "then say perfai test again.");
34
+ default:
35
+ return `${name}: ${view.message}\n\nRun register_app again with the same URL to restart onboarding.`;
36
+ }
37
+ }
38
+ function refusedMessage(view) {
39
+ return (`${view.label}: ${view.message}\n\nPerfai can't start a new security test on this app until its ` +
40
+ `onboarding finishes โ€” resolve what the message above asks, then try again. ${PARTIAL_FINDINGS_NOTE}`);
41
+ }
42
+ async function registerByUrl(auth, appUrl) {
43
+ try {
44
+ const app = await registerApp(auth, { appUrl });
45
+ auth.setCurrentApp(app.appId, appUrl);
46
+ return { app, created: true };
47
+ }
48
+ catch (error) {
49
+ if (error instanceof ApiError && error.status === 409 && typeof error.data?.appId === "string") {
50
+ const existing = await getApp(auth, error.data.appId);
51
+ auth.setCurrentApp(existing.appId, appUrl);
52
+ return { app: existing, created: false };
53
+ }
54
+ throw error;
55
+ }
56
+ }
16
57
  export async function handleRunSecurityTest(auth, args) {
17
58
  try {
59
+ let app;
18
60
  const resolved = await resolveApp(auth, args);
19
- if (!resolved.ok)
61
+ if (resolved.ok) {
62
+ app = await getApp(auth, resolved.app.appId);
63
+ }
64
+ else if (resolved.notFound && isFullUrl(args?.app)) {
65
+ const appUrl = args.app.trim();
66
+ const registered = await registerByUrl(auth, appUrl);
67
+ if (registered.created) {
68
+ 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
+ };
72
+ }
73
+ app = registered.app;
74
+ }
75
+ else {
20
76
  return { content: [{ type: "text", text: resolved.message }] };
21
- const { appId } = resolved.app;
22
- // Pre-flight check so we can give a clearer message than the API's bare 400.
23
- const app = await getApp(auth, appId);
24
- if (app.registrationStatus !== "COMPLETED") {
25
- return {
26
- content: [
27
- {
28
- type: "text",
29
- text: `โŒ App is not ready (registrationStatus: ${app.registrationStatus ?? "UNKNOWN"}). Run check_app_status until it's COMPLETED before starting a test.`,
30
- },
31
- ],
32
- };
33
77
  }
34
- const task = await runSecurityAgent(auth, appId);
35
- auth.currentTaskId = task.taskId;
78
+ const { appId } = app;
79
+ const name = appName(app);
80
+ const view = describeStatus(app.registrationStatus, app);
81
+ if (!canStartSecurityTest(view)) {
82
+ console.error(`run_security_test: app=${appId} not ready, status=${app.registrationStatus ?? "none"} outcome=${view.outcome}`);
83
+ return { content: [{ type: "text", text: notReadyMessage(name, view) }] };
84
+ }
85
+ let task;
86
+ try {
87
+ task = await runSecurityAgent(auth, appId);
88
+ }
89
+ catch (error) {
90
+ if (!isAppNotRegisteredError(error))
91
+ throw error;
92
+ const refused = describeStatus(error.data?.registrationStatus ?? app.registrationStatus, app);
93
+ console.error(`run_security_test: app=${appId} refused by API, status=${String(error.data?.registrationStatus ?? "none")}`);
94
+ return { content: [{ type: "text", text: refusedMessage(refused) }] };
95
+ }
96
+ auth.setCurrentTask(task.taskId, appId);
36
97
  return {
37
- content: [
38
- {
39
- type: "text",
40
- text: `๐Ÿš€ Security test started.\n\nTask ID: ${task.taskId}\n\nNext: check_task_status to poll until state is COMPLETED (can take up to ~30 min).`,
41
- },
42
- ],
98
+ content: [{ type: "text", text: `๐Ÿš€ Security test started for ${name}. Say perfai issues later to view issues.` }],
43
99
  };
44
100
  }
45
101
  catch (error) {
@@ -1,8 +1,9 @@
1
1
  import { submitAccountSetup } from "../../client/apiClient.js";
2
2
  export const submitAppCredentialsTool = {
3
3
  name: "submit_app_credentials",
4
- description: "๐Ÿ”‘ Supply login credentials when an app's onboarding is stuck in AWAITING_INPUT " +
5
- "(POST /v1/apps/{appId}/account-setup). Only needed if check_app_status reports AWAITING_INPUT.",
4
+ description: "๐Ÿ”‘ Supply login credentials when an app's onboarding is waiting for them " +
5
+ "(POST /v1/apps/{appId}/account-setup). Only needed if check_app_status or check_task_status " +
6
+ "reports Needs input / Needs login.",
6
7
  inputSchema: {
7
8
  type: "object",
8
9
  properties: {
@@ -30,7 +31,7 @@ export async function handleSubmitAppCredentials(auth, args) {
30
31
  content: [
31
32
  {
32
33
  type: "text",
33
- text: `โœ… Credentials submitted, onboarding resumed (task ${task.taskId ?? "n/a"}).\n\nRun check_app_status to continue polling.`,
34
+ text: `โœ… Credentials submitted, onboarding resumed (task ${task.taskId ?? "n/a"}). Say perfai issues later to view issues.`,
34
35
  },
35
36
  ],
36
37
  };
@@ -1,4 +1,5 @@
1
1
  import { dismissVulnerability, fixVulnerability, reopenVulnerability } from "../../client/apiClient.js";
2
+ import { sanitize } from "../../utils/promptBuilder.js";
2
3
  function resolveArgs(auth, args) {
3
4
  const appId = args?.appId ?? auth.currentAppId;
4
5
  if (!appId)
@@ -7,6 +8,14 @@ function resolveArgs(auth, args) {
7
8
  return { error: "vulnerability_id is required." };
8
9
  return { appId, id: auth.resolveVulnerabilityId(appId, args.vulnerability_id) };
9
10
  }
11
+ function describeFinding(id, ...sources) {
12
+ const v = sources.find(s => s?.title || s?.label);
13
+ const name = sanitize(v?.title ?? v?.label, 120);
14
+ if (!name)
15
+ return `ID ${id}`;
16
+ const endpoint = v?.path ? sanitize(`${v.method ? String(v.method).toUpperCase() + " " : ""}${v.path}`, 120) : "";
17
+ return `"${name}"${endpoint ? ` on ${endpoint}` : ""} (ID ${id})`;
18
+ }
10
19
  const idSchema = {
11
20
  type: "object",
12
21
  properties: {
@@ -18,9 +27,12 @@ const idSchema = {
18
27
  };
19
28
  export const dismissVulnerabilityTool = {
20
29
  name: "dismiss_vulnerability",
21
- description: "๐Ÿ™ˆ Dismiss a finding as a false positive / won't-fix (POST /v1/vulnerabilities/{id}/dismiss). " +
22
- "During an auto_fix_all run, call this silently for findings that do not apply to the code, with a " +
23
- "specific reason โ€” it is stored on the finding and used to triage false positives.",
30
+ description: '๐Ÿ™ˆ "Perfai dismiss <n>": dismiss a finding (POST /v1/vulnerabilities/{id}/dismiss). Use it whenever the ' +
31
+ "user asks to dismiss, skip, ignore, suppress, hide or accept the risk of a finding, or calls it a false " +
32
+ "positive, not applicable or won't fix โ€” do it here, never send the user to the web app. The finding leaves " +
33
+ "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.",
24
36
  inputSchema: {
25
37
  ...idSchema,
26
38
  properties: {
@@ -38,8 +50,16 @@ export async function handleDismissVulnerability(auth, args) {
38
50
  if ("error" in resolved)
39
51
  return { content: [{ type: "text", text: `โŒ ${resolved.error}` }] };
40
52
  try {
41
- await dismissVulnerability(auth, resolved.id, args?.reason);
42
- return { content: [{ type: "text", text: `๐Ÿ™ˆ Dismissed vulnerability ${resolved.id}.` }] };
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
+ };
43
63
  }
44
64
  catch (error) {
45
65
  return { content: [{ type: "text", text: `โŒ Failed to dismiss: ${error instanceof Error ? error.message : String(error)}` }] };
@@ -47,7 +67,9 @@ export async function handleDismissVulnerability(auth, args) {
47
67
  }
48
68
  export const reopenVulnerabilityTool = {
49
69
  name: "reopen_vulnerability",
50
- description: "๐Ÿ” Reopen a dismissed/fixed finding (POST /v1/vulnerabilities/{id}/reopen).",
70
+ description: '๐Ÿ” "Perfai reopen <n>": reopen a finding (POST /v1/vulnerabilities/{id}/reopen) โ€” undoes a dismissal or a ' +
71
+ "fix claim and returns it to the open list. Use it whenever the user asks to undo, restore, un-dismiss or " +
72
+ "reopen a dismissed or skipped finding. Pass the ID from the dismiss_vulnerability reply.",
51
73
  inputSchema: idSchema,
52
74
  };
53
75
  export async function handleReopenVulnerability(auth, args) {
@@ -55,8 +77,10 @@ export async function handleReopenVulnerability(auth, args) {
55
77
  if ("error" in resolved)
56
78
  return { content: [{ type: "text", text: `โŒ ${resolved.error}` }] };
57
79
  try {
58
- await reopenVulnerability(auth, resolved.id);
59
- return { content: [{ type: "text", text: `๐Ÿ” Reopened vulnerability ${resolved.id}.` }] };
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.` }] };
60
84
  }
61
85
  catch (error) {
62
86
  return { content: [{ type: "text", text: `โŒ Failed to reopen: ${error instanceof Error ? error.message : String(error)}` }] };
@@ -5,9 +5,9 @@ export const authStatusTool = {
5
5
  };
6
6
  export async function handleAuthStatus(auth) {
7
7
  const text = auth.isAuthenticated()
8
- ? `โœ… Authenticated as ${auth.getAuthenticatedEmail() ?? `unknown (${auth.getAuthMethod()}-based session)`}` +
8
+ ? `โœ… Authenticated as ${auth.describeIdentity()}` +
9
9
  (auth.currentAppId ? `\n๐Ÿ“ฑ Current app: ${auth.currentAppId}` : "") +
10
10
  (auth.currentTaskId ? `\n๐Ÿงช Current task: ${auth.currentTaskId}` : "")
11
- : `โŒ Not authenticated. Run \`login\` (credentials from args, or PERFAI_EMAIL/PERFAI_PASSWORD env).`;
11
+ : `โŒ Not authenticated. Run \`login\` (credentials from args, or PERFAI_API_KEY / PERFAI_EMAIL+PERFAI_PASSWORD env).`;
12
12
  return { content: [{ type: "text", text }] };
13
13
  }