perfai-cloud-mcp 0.5.3 → 0.7.2

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.
@@ -0,0 +1,129 @@
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import { CallToolRequestSchema, ErrorCode, GetPromptRequestSchema, ListPromptsRequestSchema, ListToolsRequestSchema, McpError, } from "@modelcontextprotocol/sdk/types.js";
3
+ import { SERVER_INFO, SERVER_INSTRUCTIONS } from "./config.js";
4
+ import { PROMPTS, getPrompt } from "./prompts.js";
5
+ import { LOGIN_PENDING_TEXT, ensureLoggedIn } from "./tools/public/login.js";
6
+ import { loggable } from "./client/errors.js";
7
+ import { runTool } from "./client/relay.js";
8
+ import { clientLabel } from "./utils/clientInfo.js";
9
+ 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";
10
+ export const OAUTH_HIDDEN_TOOLS = new Set(["login", "logout"]);
11
+ export const OAUTH_SIGNED_IN_TEXT = "You're signed in through your AI tool's Perfai connector. To switch accounts, disconnect and reconnect Perfai there.";
12
+ export const ISSUES_WRITE_TOOLS = new Set([
13
+ "dismiss_vulnerability",
14
+ "reopen_vulnerability",
15
+ "mark_vulnerability_fixed",
16
+ ]);
17
+ export const ISSUES_WRITE_MISSING_TEXT = 'Reconnect Perfai in your AI tool and allow "Mark issues fixed or dismissed".';
18
+ function oauthRefusal(auth, name) {
19
+ if (auth.getAuthMethod() !== "mcp_oauth")
20
+ return undefined;
21
+ if (OAUTH_HIDDEN_TOOLS.has(name)) {
22
+ return { content: [{ type: "text", text: OAUTH_SIGNED_IN_TEXT }] };
23
+ }
24
+ if (ISSUES_WRITE_TOOLS.has(name) && !auth.hasScope("issues:write")) {
25
+ return { isError: true, content: [{ type: "text", text: ISSUES_WRITE_MISSING_TEXT }] };
26
+ }
27
+ return undefined;
28
+ }
29
+ export function createMcpServer(auth) {
30
+ const server = new Server(SERVER_INFO, {
31
+ capabilities: { tools: {}, prompts: {} },
32
+ instructions: SERVER_INSTRUCTIONS,
33
+ });
34
+ server.oninitialized = () => {
35
+ console.error(`Client connected: ${clientLabel(server.getClientVersion())}`);
36
+ };
37
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
38
+ const tools = [...Object.values(PUBLIC_TOOLS), ...Object.values(PROTECTED_TOOLS)];
39
+ return {
40
+ tools: auth.getAuthMethod() === "mcp_oauth" ? tools.filter((tool) => !OAUTH_HIDDEN_TOOLS.has(tool.name)) : tools,
41
+ };
42
+ });
43
+ server.setRequestHandler(ListPromptsRequestSchema, async () => ({ prompts: PROMPTS }));
44
+ server.setRequestHandler(GetPromptRequestSchema, async (request) => {
45
+ const { name, arguments: args } = request.params;
46
+ try {
47
+ const prompt = getPrompt(name, args);
48
+ if (!prompt)
49
+ throw new McpError(ErrorCode.InvalidParams, `Unknown prompt: ${name}`);
50
+ return prompt;
51
+ }
52
+ catch (error) {
53
+ if (error instanceof McpError)
54
+ throw error;
55
+ throw new McpError(ErrorCode.InvalidParams, error instanceof Error ? error.message : String(error));
56
+ }
57
+ });
58
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
59
+ const { name, arguments: args } = request.params;
60
+ console.error(`→ Tool call: ${name} (client: ${clientLabel(server.getClientVersion())})`);
61
+ try {
62
+ return await runTool(async () => oauthRefusal(auth, name) ?? (await callTool(auth, name, args)), () => auth.getPlan() === "free");
63
+ }
64
+ catch (error) {
65
+ if (error instanceof McpError)
66
+ throw error;
67
+ console.error(`Tool '${name}' failed:`, loggable(error));
68
+ throw new McpError(ErrorCode.InternalError, `Tool '${name}' failed — see server logs`);
69
+ }
70
+ });
71
+ server.onerror = (error) => {
72
+ console.error("[MCP Error]", error);
73
+ };
74
+ return server;
75
+ }
76
+ async function callTool(auth, name, args) {
77
+ switch (name) {
78
+ case "login":
79
+ return await handleLogin(auth, args);
80
+ case "auth_status":
81
+ return await handleAuthStatus(auth);
82
+ }
83
+ if (!auth.isAuthenticated() && !auth.hasCredentials()) {
84
+ if (process.env.MCP_TRANSPORT?.toLowerCase() === "http") {
85
+ throw new McpError(ErrorCode.InvalidRequest, `Authentication required. Run the 'login' tool first to access '${name}'.`);
86
+ }
87
+ if (!(await ensureLoggedIn(auth))) {
88
+ return { content: [{ type: "text", text: LOGIN_PENDING_TEXT }] };
89
+ }
90
+ }
91
+ switch (name) {
92
+ case "logout":
93
+ return await handleLogout(auth);
94
+ case "manage_organizations":
95
+ return await handleManageOrganizations(auth, args);
96
+ case "register_app":
97
+ return await handleRegisterApp(auth, args);
98
+ case "check_app_status":
99
+ return await handleCheckAppStatus(auth, args);
100
+ case "list_apps":
101
+ return await handleListApps(auth, args);
102
+ case "select_app":
103
+ return await handleSelectApp(auth, args);
104
+ case "submit_app_credentials":
105
+ return await handleSubmitAppCredentials(auth, args);
106
+ case "run_security_test":
107
+ return await handleRunSecurityTest(auth, args);
108
+ case "check_task_status":
109
+ return await handleCheckTaskStatus(auth, args);
110
+ case "get_vulnerabilities":
111
+ return await handleGetVulnerabilities(auth, args);
112
+ case "suggest_fix":
113
+ return await handleSuggestFix(auth, args);
114
+ case "auto_fix":
115
+ return await handleAutoFix(auth, args);
116
+ case "auto_fix_all":
117
+ return await handleAutoFixAll(auth, args);
118
+ case "get_fix_summary":
119
+ return await handleGetFixSummary(auth, args);
120
+ case "dismiss_vulnerability":
121
+ return await handleDismissVulnerability(auth, args);
122
+ case "reopen_vulnerability":
123
+ return await handleReopenVulnerability(auth, args);
124
+ case "mark_vulnerability_fixed":
125
+ return await handleMarkVulnerabilityFixed(auth, args);
126
+ default:
127
+ throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
128
+ }
129
+ }
package/dist/server.js CHANGED
@@ -1,110 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import "./log-guard.js";
3
3
  import "./env.js";
4
- import { randomUUID } from "node:crypto";
5
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
6
4
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
7
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
8
- import { CallToolRequestSchema, ErrorCode, GetPromptRequestSchema, ListPromptsRequestSchema, ListToolsRequestSchema, McpError, } from "@modelcontextprotocol/sdk/types.js";
9
- import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
10
- import { SERVER_INFO, SERVER_INSTRUCTIONS } from "./config.js";
11
- import { PROMPTS, getPrompt } from "./prompts.js";
12
- import { LOGIN_PENDING_TEXT, ensureLoggedIn } from "./tools/public/login.js";
5
+ import { MCP_RESOURCE_URL, SERVER_INFO, WEBUI_CLIENT_IDS } from "./config.js";
13
6
  import { AuthManager } from "./client/authManager.js";
14
- import { loggable } from "./client/errors.js";
15
- 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";
16
- function createMcpServer(auth) {
17
- const server = new Server(SERVER_INFO, {
18
- capabilities: { tools: {}, prompts: {} },
19
- instructions: SERVER_INSTRUCTIONS,
20
- });
21
- server.setRequestHandler(ListToolsRequestSchema, async () => {
22
- return { tools: [...Object.values(PUBLIC_TOOLS), ...Object.values(PROTECTED_TOOLS)] };
23
- });
24
- server.setRequestHandler(ListPromptsRequestSchema, async () => ({ prompts: PROMPTS }));
25
- server.setRequestHandler(GetPromptRequestSchema, async (request) => {
26
- const { name, arguments: args } = request.params;
27
- try {
28
- const prompt = getPrompt(name, args);
29
- if (!prompt)
30
- throw new McpError(ErrorCode.InvalidParams, `Unknown prompt: ${name}`);
31
- return prompt;
32
- }
33
- catch (error) {
34
- if (error instanceof McpError)
35
- throw error;
36
- throw new McpError(ErrorCode.InvalidParams, error instanceof Error ? error.message : String(error));
37
- }
38
- });
39
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
40
- const { name, arguments: args } = request.params;
41
- console.error(`→ Tool call: ${name}`);
42
- try {
43
- switch (name) {
44
- case "login":
45
- return await handleLogin(auth, args);
46
- case "auth_status":
47
- return await handleAuthStatus(auth);
48
- }
49
- if (!auth.isAuthenticated() && !auth.hasCredentials()) {
50
- if (process.env.MCP_TRANSPORT?.toLowerCase() === "http") {
51
- throw new McpError(ErrorCode.InvalidRequest, `Authentication required. Run the 'login' tool first to access '${name}'.`);
52
- }
53
- if (!(await ensureLoggedIn(auth))) {
54
- return { content: [{ type: "text", text: LOGIN_PENDING_TEXT }] };
55
- }
56
- }
57
- switch (name) {
58
- case "logout":
59
- return await handleLogout(auth);
60
- case "manage_organizations":
61
- return await handleManageOrganizations(auth, args);
62
- case "register_app":
63
- return await handleRegisterApp(auth, args);
64
- case "check_app_status":
65
- return await handleCheckAppStatus(auth, args);
66
- case "list_apps":
67
- return await handleListApps(auth, args);
68
- case "select_app":
69
- return await handleSelectApp(auth, args);
70
- case "submit_app_credentials":
71
- return await handleSubmitAppCredentials(auth, args);
72
- case "run_security_test":
73
- return await handleRunSecurityTest(auth, args);
74
- case "check_task_status":
75
- return await handleCheckTaskStatus(auth, args);
76
- case "get_vulnerabilities":
77
- return await handleGetVulnerabilities(auth, args);
78
- case "suggest_fix":
79
- return await handleSuggestFix(auth, args);
80
- case "auto_fix":
81
- return await handleAutoFix(auth, args);
82
- case "auto_fix_all":
83
- return await handleAutoFixAll(auth, args);
84
- case "get_fix_summary":
85
- return await handleGetFixSummary(auth, args);
86
- case "dismiss_vulnerability":
87
- return await handleDismissVulnerability(auth, args);
88
- case "reopen_vulnerability":
89
- return await handleReopenVulnerability(auth, args);
90
- case "mark_vulnerability_fixed":
91
- return await handleMarkVulnerabilityFixed(auth, args);
92
- default:
93
- throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
94
- }
95
- }
96
- catch (error) {
97
- if (error instanceof McpError)
98
- throw error;
99
- console.error(`Tool '${name}' failed:`, loggable(error));
100
- throw new McpError(ErrorCode.InternalError, `Tool '${name}' failed — see server logs`);
101
- }
102
- });
103
- server.onerror = (error) => {
104
- console.error("[MCP Error]", error);
105
- };
106
- return server;
107
- }
7
+ import { createMcpServer } from "./mcpServer.js";
8
+ import { PROTECTED_TOOLS, PUBLIC_TOOLS } from "./tools/index.js";
108
9
  async function startStdio() {
109
10
  const auth = new AuthManager();
110
11
  const server = createMcpServer(auth);
@@ -121,109 +22,23 @@ async function startStdio() {
121
22
  process.exit(0);
122
23
  });
123
24
  }
124
- import { createBearerAuth, sameCaller } from "./auth/bearerAuth.js";
125
25
  async function startHttp() {
126
- const { default: express } = await import("express");
127
- const app = express();
128
- app.use(express.json());
26
+ const { createHttpApp } = await import("./http.js");
129
27
  const MCP_API_KEY = process.env.MCP_API_KEY;
130
- console.error("Auth mode: PerfAI API keys + OAuth tokens" +
28
+ if (MCP_RESOURCE_URL)
29
+ new URL(MCP_RESOURCE_URL);
30
+ console.error("Auth mode: PerfAI API keys" +
31
+ (MCP_RESOURCE_URL ? ` + MCP OAuth (resource ${MCP_RESOURCE_URL})` : "") +
32
+ (WEBUI_CLIENT_IDS.length ? ` + WebUI tokens (${WEBUI_CLIENT_IDS.length} audience(s))` : "") +
131
33
  (MCP_API_KEY ? " + static MCP_API_KEY (legacy)" : ""));
132
- app.use("/mcp", createBearerAuth({ mcpApiKey: MCP_API_KEY }));
133
- const transports = {};
134
- const sessions = {};
135
- function sessionTransport(req, res) {
136
- const sessionId = req.headers["mcp-session-id"];
137
- if (!sessionId || !transports[sessionId]) {
138
- res.status(400).json({
139
- jsonrpc: "2.0",
140
- error: { code: -32000, message: "Invalid or missing session ID" },
141
- id: null,
142
- });
143
- return undefined;
144
- }
145
- if (!sameCaller(req, sessions[sessionId].credentialHash)) {
146
- console.error(`Rejected session ${sessionId}: bearer differs from the one that opened it.`);
147
- res.status(403).json({
148
- jsonrpc: "2.0",
149
- error: { code: -32001, message: "Forbidden: this session belongs to a different credential." },
150
- id: null,
151
- });
152
- return undefined;
153
- }
154
- return transports[sessionId];
155
- }
156
- app.post("/mcp", async (req, res) => {
157
- const sessionId = req.headers["mcp-session-id"];
158
- try {
159
- if (sessionId) {
160
- const transport = sessionTransport(req, res);
161
- if (transport)
162
- await transport.handleRequest(req, res, req.body);
163
- return;
164
- }
165
- const gate = req.perfaiAuth;
166
- if (gate && isInitializeRequest(req.body)) {
167
- const auth = new AuthManager({ useEnv: false });
168
- if (gate.method === "api_key" && gate.token) {
169
- auth.setToken(gate.token, undefined, "api_key");
170
- }
171
- else if (gate.method === "jwt" && gate.token) {
172
- auth.setToken(gate.token, gate.email, "oauth");
173
- }
174
- const transport = new StreamableHTTPServerTransport({
175
- sessionIdGenerator: () => randomUUID(),
176
- onsessioninitialized: (sid) => {
177
- transports[sid] = transport;
178
- sessions[sid] = { auth, credentialHash: gate.credentialHash };
179
- console.error(`Session initialized: ${sid} (${gate.method}: ${auth.describeIdentity()})`);
180
- },
181
- });
182
- transport.onclose = () => {
183
- const sid = transport.sessionId;
184
- if (sid) {
185
- delete transports[sid];
186
- delete sessions[sid];
187
- console.error(`Session closed: ${sid}`);
188
- }
189
- };
190
- const server = createMcpServer(auth);
191
- await server.connect(transport);
192
- await transport.handleRequest(req, res, req.body);
193
- return;
194
- }
195
- res.status(400).json({
196
- jsonrpc: "2.0",
197
- error: { code: -32000, message: "Bad Request: No valid session ID provided" },
198
- id: null,
199
- });
200
- }
201
- catch (error) {
202
- console.error("Error handling MCP request:", error instanceof Error ? error.message : String(error));
203
- if (!res.headersSent) {
204
- res.status(500).json({
205
- jsonrpc: "2.0",
206
- error: { code: -32603, message: "Internal server error" },
207
- id: null,
208
- });
209
- }
210
- }
211
- });
212
- app.get("/mcp", async (req, res) => {
213
- const transport = sessionTransport(req, res);
214
- if (transport)
215
- await transport.handleRequest(req, res);
216
- });
217
- app.delete("/mcp", async (req, res) => {
218
- const transport = sessionTransport(req, res);
219
- if (transport)
220
- await transport.handleRequest(req, res);
221
- });
222
- app.get("/", (_req, res) => {
223
- res.json({ status: "ok" });
224
- });
225
- app.get("/health", (_req, res) => {
226
- res.json({ status: "ok" });
34
+ if (!MCP_RESOURCE_URL)
35
+ console.error("MCP_RESOURCE_URL is not set: OAuth sign-in is off (no metadata, no MCP tokens).");
36
+ if (!WEBUI_CLIENT_IDS.length)
37
+ console.error("WEBUI_CLIENT_IDS is not set: WebUI id_tokens are refused.");
38
+ const { app, closeAll } = createHttpApp({
39
+ mcpApiKey: MCP_API_KEY,
40
+ resourceUrl: MCP_RESOURCE_URL,
41
+ webuiClientIds: WEBUI_CLIENT_IDS,
227
42
  });
228
43
  const PORT = parseInt(process.env.PORT || "3000", 10);
229
44
  app.listen(PORT, "0.0.0.0", () => {
@@ -232,11 +47,7 @@ async function startHttp() {
232
47
  });
233
48
  process.on("SIGINT", async () => {
234
49
  console.error("Shutting down...");
235
- for (const sid of Object.keys(transports)) {
236
- await transports[sid].close().catch(() => { });
237
- delete transports[sid];
238
- delete sessions[sid];
239
- }
50
+ await closeAll();
240
51
  process.exit(0);
241
52
  });
242
53
  }
@@ -1,6 +1,7 @@
1
1
  import { getAllVulnerabilities } from "../../client/apiClient.js";
2
+ import { findingsFailureText } from "../../client/errors.js";
2
3
  import { APP_NAME_PROPERTY, resolveApp } from "../../utils/appResolver.js";
3
- import { buildAutoFixInstruction } from "../../utils/promptBuilder.js";
4
+ import { buildAutoFixInstruction, isLocked } from "../../utils/promptBuilder.js";
4
5
  export const autoFixTool = {
5
6
  name: "auto_fix",
6
7
  description: "🔧 Auto-fix a single vulnerability. Returns structured, step-by-step fix instructions " +
@@ -40,13 +41,13 @@ export async function handleAutoFix(auth, args) {
40
41
  appLabel = resolved.app.label;
41
42
  vuln = auth.getCachedVulnerability(appId, args.vulnerability_id);
42
43
  if (!vuln) {
43
- auth.cacheVulnerabilities(appId, await getAllVulnerabilities(auth, appId));
44
+ auth.cacheVulnerabilities(appId, (await getAllVulnerabilities(auth, appId)).filter((v) => !isLocked(v)));
44
45
  vuln = auth.getCachedVulnerability(appId, args.vulnerability_id);
45
46
  }
46
47
  }
47
48
  catch (error) {
48
49
  return {
49
- content: [{ type: "text", text: `❌ Failed to fetch vulnerabilities: ${error instanceof Error ? error.message : String(error)}` }],
50
+ content: [{ type: "text", text: findingsFailureText(error) }],
50
51
  };
51
52
  }
52
53
  if (!vuln) {
@@ -1,7 +1,8 @@
1
1
  import { getAllVulnerabilities } from "../../client/apiClient.js";
2
+ import { findingsFailureText } from "../../client/errors.js";
2
3
  import { FIX_BATCH_SIZE } from "../../config.js";
3
4
  import { APP_NAME_PROPERTY, resolveApp } from "../../utils/appResolver.js";
4
- import { buildBatchFixPlan, isOpen, sortBySeverity } from "../../utils/promptBuilder.js";
5
+ import { buildBatchFixPlan, isLocked, isOpen, lockedLine, sortBySeverity } from "../../utils/promptBuilder.js";
5
6
  export const autoFixAllTool = {
6
7
  name: "auto_fix_all",
7
8
  description: "🔧 ONE-CALL FIX. When the user says \"<App> fix all\", \"<App> fix critical\" or \"<App> fix 3\" " +
@@ -42,7 +43,12 @@ export async function handleAutoFixAll(auth, args) {
42
43
  const { appId, label } = resolved.app;
43
44
  const allVulnerabilities = await getAllVulnerabilities(auth, appId);
44
45
  auth.cacheVulnerabilities(appId, allVulnerabilities);
45
- let toFix = sortBySeverity(allVulnerabilities.filter(isOpen));
46
+ const open = allVulnerabilities.filter(isOpen);
47
+ const lockedOpen = open.filter(isLocked).length;
48
+ if (lockedOpen > 0)
49
+ console.error(`auto_fix_all: app=${appId} ${lockedOpen} locked finding(s) left out of the plan`);
50
+ const note = lockedOpen > 0 ? `\n\n${lockedLine(lockedOpen)}` : "";
51
+ let toFix = sortBySeverity(open.filter((v) => !isLocked(v)));
46
52
  if (args?.severity) {
47
53
  const target = args.severity.toLowerCase();
48
54
  toFix = toFix.filter(v => (v.severity ?? "").toLowerCase() === target);
@@ -51,21 +57,23 @@ export async function handleAutoFixAll(auth, args) {
51
57
  toFix = toFix.slice(0, args.max_fixes);
52
58
  }
53
59
  if (toFix.length === 0) {
54
- const msg = args?.severity
55
- ? `✅ No open ${args.severity} vulnerabilities for "${label}".`
56
- : `✅ No open vulnerabilities for "${label}" — everything is fixed, claimed fixed, or dismissed.`;
60
+ const msg = lockedOpen > 0
61
+ ? lockedLine(lockedOpen)
62
+ : args?.severity
63
+ ? `✅ No open ${args.severity} vulnerabilities for "${label}".`
64
+ : `✅ No open vulnerabilities for "${label}" — everything is fixed, claimed fixed, or dismissed.`;
57
65
  return { content: [{ type: "text", text: msg }] };
58
66
  }
59
67
  const batch = toFix.slice(0, FIX_BATCH_SIZE);
60
68
  const plan = buildBatchFixPlan(label, batch, toFix.length - batch.length);
61
- return { content: [{ type: "text", text: plan }] };
69
+ return { content: [{ type: "text", text: plan + note }] };
62
70
  }
63
71
  catch (error) {
64
72
  return {
65
73
  content: [
66
74
  {
67
75
  type: "text",
68
- text: `❌ Failed to fetch vulnerabilities: ${error instanceof Error ? error.message : String(error)}`,
76
+ text: findingsFailureText(error),
69
77
  },
70
78
  ],
71
79
  };
@@ -1,5 +1,5 @@
1
1
  import { listAllVulnerabilities } 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, resolveApp } from "../../utils/appResolver.js";
4
4
  import { isOpen } from "../../utils/promptBuilder.js";
5
5
  export const getFixSummaryTool = {
@@ -111,7 +111,7 @@ export async function handleGetFixSummary(auth, args) {
111
111
  content: [
112
112
  {
113
113
  type: "text",
114
- text: `❌ Failed to fetch vulnerabilities: ${error instanceof Error ? error.message : String(error)}`,
114
+ text: findingsFailureText(error),
115
115
  },
116
116
  ],
117
117
  };
@@ -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 { isLocked, lockedLine } from "../../utils/promptBuilder.js";
5
6
  import { describeStatus, stillOnboardingMessage } from "../../utils/runState.js";
7
+ import { issuesFirstLine, testRunningLine } 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 = {
@@ -45,6 +47,21 @@ async function isTestRunning(auth, appId) {
45
47
  return false;
46
48
  }
47
49
  }
50
+ async function runInProgress(auth, appId) {
51
+ try {
52
+ const result = await getVulnerabilities(auth, appId, { pageSize: 1 });
53
+ return result.status === "RUN_IN_PROGRESS" ? result : null;
54
+ }
55
+ catch (error) {
56
+ console.error(`Findings lookup failed for onboarding app ${appId}:`, error instanceof Error ? error.message : String(error));
57
+ return null;
58
+ }
59
+ }
60
+ function lockedCountOf(result, lockedOnPage) {
61
+ if (typeof result.lockedCount === "number")
62
+ return result.lockedCount;
63
+ return result.data.length >= result.total ? lockedOnPage : 0;
64
+ }
48
65
  export async function handleGetVulnerabilities(auth, args) {
49
66
  try {
50
67
  const resolved = await resolveApp(auth, args);
@@ -55,14 +72,13 @@ export async function handleGetVulnerabilities(auth, args) {
55
72
  const name = appName(app);
56
73
  const view = describeStatus(app.registrationStatus, app);
57
74
  if (view.outcome === "pending") {
58
- return { content: [{ type: "text", text: stillOnboardingMessage(name) }] };
75
+ const running = await runInProgress(auth, appId);
76
+ const text = running ? testRunningLine(running.lastRunCompletedAt ?? null) : stillOnboardingMessage(name);
77
+ return { content: [{ type: "text", text }] };
59
78
  }
60
79
  const notes = [];
61
80
  if (view.outcome === "needs_input")
62
81
  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
82
  const status = String(args?.status ?? "open").toLowerCase();
67
83
  const result = await getVulnerabilities(auth, appId, {
68
84
  ...(STATUS_FILTERS[status] ?? STATUS_FILTERS.open),
@@ -70,24 +86,48 @@ export async function handleGetVulnerabilities(auth, args) {
70
86
  pageSize: args?.pageSize,
71
87
  search: args?.search,
72
88
  });
73
- auth.cacheVulnerabilities(appId, result.data);
89
+ if (result.status === "RUN_IN_PROGRESS") {
90
+ const lastCompleted = "lastRunCompletedAt" in result ? (result.lastRunCompletedAt ?? null) : auth.lastTestOf(appId);
91
+ return { content: [{ type: "text", text: testRunningLine(lastCompleted) }] };
92
+ }
93
+ if (result.status === "NO_RUNS") {
94
+ auth.rememberLastTest(appId, null);
95
+ return { content: [{ type: "text", text: "No completed test yet." }] };
96
+ }
97
+ if (typeof result.lastRunCompletedAt === "string")
98
+ auth.rememberLastTest(appId, result.lastRunCompletedAt);
74
99
  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);
100
+ const shown = result.data.filter((v) => !isLocked(v));
101
+ const lockedOnPage = result.data.length - shown.length;
102
+ const lockedTotal = isOpenView && !args?.search ? lockedCountOf(result, lockedOnPage) : lockedOnPage;
103
+ if (lockedOnPage > 0)
104
+ console.error(`get_vulnerabilities: app=${appId} ${lockedOnPage} locked row(s) left out, lockedCount=${result.lockedCount ?? "missing"}`);
105
+ auth.cacheVulnerabilities(appId, shown);
106
+ const firstLine = (await isTestRunning(auth, appId))
107
+ ? testRunningLine(typeof result.lastRunCompletedAt === "string" ? result.lastRunCompletedAt : auth.lastTestOf(appId))
108
+ : issuesFirstLine(result, isOpenView && !args?.search);
109
+ if (firstLine)
110
+ notes.unshift(firstLine);
111
+ const list = shown.length === 0 && lockedOnPage > 0
112
+ ? null
113
+ : shown.length === 0 && !isOpenView
114
+ ? `No ${status} findings for ${name}.`
115
+ : formatVulnerabilityList(shown, Math.max(shown.length, result.total - lockedTotal), result.page, result.pageSize);
116
+ const locked = isOpenView && !args?.search && lockedTotal > 0 ? [lockedLine(lockedTotal)] : [];
78
117
  const dismissedCount = result.dismissedCount;
79
118
  const hidden = isOpenView && typeof dismissedCount === "number" && dismissedCount > 0
80
119
  ? [`🙈 ${dismissedCount} dismissed finding${dismissedCount === 1 ? "" : "s"} not shown. ` +
81
120
  "reopen_vulnerability with a finding's ID brings it back."]
82
121
  : [];
83
- return { content: [{ type: "text", text: [...notes, list, ...hidden].join("\n\n") }] };
122
+ const body = [...notes, ...(list ? [list] : []), ...locked, ...hidden];
123
+ return { content: [{ type: "text", text: body.join("\n\n") }] };
84
124
  }
85
125
  catch (error) {
86
126
  if (String(args?.status ?? "").toLowerCase() === "dismissed" && isForbiddenError(error)) {
87
127
  return { content: [{ type: "text", text: DISMISSED_STAFF_ONLY }] };
88
128
  }
89
129
  return {
90
- content: [{ type: "text", text: `❌ Failed to fetch vulnerabilities: ${error instanceof Error ? error.message : String(error)}` }],
130
+ content: [{ type: "text", text: findingsFailureText(error) }],
91
131
  };
92
132
  }
93
133
  }
@@ -2,6 +2,7 @@ import { registerApp, getApp } from "../../client/apiClient.js";
2
2
  import { ApiError } from "../../client/errors.js";
3
3
  import { appName } from "../../utils/appResolver.js";
4
4
  import { canStartSecurityTest, describeStatus, onboardingStartedMessage, stillOnboardingMessage } from "../../utils/runState.js";
5
+ import { withSchedule } from "../../utils/testInfo.js";
5
6
  export const registerAppTool = {
6
7
  name: "register_app",
7
8
  description: "📱 Register an app by its deployed URL (POST /v1/apps). Perfai onboards it in the background, and " +
@@ -61,7 +62,8 @@ export async function handleRegisterApp(auth, args) {
61
62
  tenantOneCredentials,
62
63
  });
63
64
  auth.setCurrentApp(app.appId, args.appUrl);
64
- return { content: [{ type: "text", text: onboardingStartedMessage(appName({ ...app, appUrl: app.appUrl ?? args.appUrl })) }] };
65
+ const started = onboardingStartedMessage(appName({ ...app, appUrl: app.appUrl ?? args.appUrl }));
66
+ return { content: [{ type: "text", text: withSchedule(started, app.scheduleType) }] };
65
67
  }
66
68
  catch (error) {
67
69
  if (error instanceof ApiError && error.status === 409 && typeof error.data?.appId === "string") {