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.
- package/README.md +45 -24
- package/dist/auth/bearerAuth.js +53 -0
- package/dist/auth/oauthFlow.js +1 -19
- package/dist/auth/pkce.js +0 -8
- package/dist/auth/tokenValidator.js +77 -67
- package/dist/cli.js +85 -52
- package/dist/client/apiClient.js +18 -25
- package/dist/client/authManager.js +42 -51
- package/dist/client/errors.js +42 -14
- package/dist/config.js +35 -38
- package/dist/env.js +0 -6
- package/dist/log-guard.js +0 -9
- package/dist/prompts.js +2 -8
- package/dist/server.js +45 -176
- package/dist/tools/protected/autoFix.js +0 -1
- package/dist/tools/protected/autoFixAll.js +4 -7
- package/dist/tools/protected/checkAppStatus.js +34 -32
- package/dist/tools/protected/checkTaskStatus.js +29 -28
- package/dist/tools/protected/getFixSummary.js +41 -11
- package/dist/tools/protected/getVulnerabilities.js +58 -8
- package/dist/tools/protected/manageOrganizations.js +4 -5
- package/dist/tools/protected/registerApp.js +17 -33
- package/dist/tools/protected/runSecurityTest.js +82 -26
- package/dist/tools/protected/submitAppCredentials.js +4 -3
- package/dist/tools/protected/vulnerabilityActions.js +32 -8
- package/dist/tools/public/authStatus.js +2 -2
- package/dist/tools/public/login.js +3 -27
- package/dist/utils/appResolver.js +25 -85
- package/dist/utils/formatters.js +9 -9
- package/dist/utils/poll.js +0 -7
- package/dist/utils/promptBuilder.js +93 -94
- package/dist/utils/registrationState.js +28 -0
- package/dist/utils/runState.js +129 -0
- package/package.json +6 -2
- package/dist/auth/oauthFlow.d.ts +0 -23
- package/dist/auth/oauthFlow.d.ts.map +0 -1
- package/dist/auth/pkce.d.ts +0 -11
- package/dist/auth/pkce.d.ts.map +0 -1
- package/dist/auth/tokenValidator.d.ts +0 -40
- package/dist/auth/tokenValidator.d.ts.map +0 -1
- package/dist/cli.d.ts +0 -3
- package/dist/cli.d.ts.map +0 -1
- package/dist/client/apiClient.d.ts +0 -36
- package/dist/client/apiClient.d.ts.map +0 -1
- package/dist/client/authManager.d.ts +0 -61
- package/dist/client/authManager.d.ts.map +0 -1
- package/dist/client/errors.d.ts +0 -10
- package/dist/client/errors.d.ts.map +0 -1
- package/dist/client/types.d.ts +0 -72
- package/dist/client/types.d.ts.map +0 -1
- package/dist/config.d.ts +0 -27
- package/dist/config.d.ts.map +0 -1
- package/dist/env.d.ts +0 -2
- package/dist/env.d.ts.map +0 -1
- package/dist/log-guard.d.ts +0 -2
- package/dist/log-guard.d.ts.map +0 -1
- package/dist/prompts.d.ts +0 -31
- package/dist/prompts.d.ts.map +0 -1
- package/dist/server.d.ts +0 -4
- package/dist/server.d.ts.map +0 -1
- package/dist/tools/index.d.ts +0 -404
- package/dist/tools/index.d.ts.map +0 -1
- package/dist/tools/protected/autoFix.d.ts +0 -26
- package/dist/tools/protected/autoFix.d.ts.map +0 -1
- package/dist/tools/protected/autoFixAll.d.ts +0 -30
- package/dist/tools/protected/autoFixAll.d.ts.map +0 -1
- package/dist/tools/protected/checkAppStatus.d.ts +0 -21
- package/dist/tools/protected/checkAppStatus.d.ts.map +0 -1
- package/dist/tools/protected/checkTaskStatus.d.ts +0 -21
- package/dist/tools/protected/checkTaskStatus.d.ts.map +0 -1
- package/dist/tools/protected/getFixSummary.d.ts +0 -21
- package/dist/tools/protected/getFixSummary.d.ts.map +0 -1
- package/dist/tools/protected/getVulnerabilities.d.ts +0 -33
- package/dist/tools/protected/getVulnerabilities.d.ts.map +0 -1
- package/dist/tools/protected/listApps.d.ts +0 -25
- package/dist/tools/protected/listApps.d.ts.map +0 -1
- package/dist/tools/protected/logout.d.ts +0 -12
- package/dist/tools/protected/logout.d.ts.map +0 -1
- package/dist/tools/protected/manageOrganizations.d.ts +0 -26
- package/dist/tools/protected/manageOrganizations.d.ts.map +0 -1
- package/dist/tools/protected/registerApp.d.ts +0 -33
- package/dist/tools/protected/registerApp.d.ts.map +0 -1
- package/dist/tools/protected/runSecurityTest.d.ts +0 -21
- package/dist/tools/protected/runSecurityTest.d.ts.map +0 -1
- package/dist/tools/protected/selectApp.d.ts +0 -18
- package/dist/tools/protected/selectApp.d.ts.map +0 -1
- package/dist/tools/protected/submitAppCredentials.d.ts +0 -22
- package/dist/tools/protected/submitAppCredentials.d.ts.map +0 -1
- package/dist/tools/protected/suggestFix.d.ts +0 -22
- package/dist/tools/protected/suggestFix.d.ts.map +0 -1
- package/dist/tools/protected/vulnerabilityActions.d.ts +0 -70
- package/dist/tools/protected/vulnerabilityActions.d.ts.map +0 -1
- package/dist/tools/public/authStatus.d.ts +0 -12
- package/dist/tools/public/authStatus.d.ts.map +0 -1
- package/dist/tools/public/login.d.ts +0 -31
- package/dist/tools/public/login.d.ts.map +0 -1
- package/dist/utils/appResolver.d.ts +0 -24
- package/dist/utils/appResolver.d.ts.map +0 -1
- package/dist/utils/formatters.d.ts +0 -8
- package/dist/utils/formatters.d.ts.map +0 -1
- package/dist/utils/poll.d.ts +0 -19
- package/dist/utils/poll.d.ts.map +0 -1
- package/dist/utils/promptBuilder.d.ts +0 -26
- package/dist/utils/promptBuilder.d.ts.map +0 -1
package/dist/config.js
CHANGED
|
@@ -1,69 +1,66 @@
|
|
|
1
|
-
// Server identity reported to MCP clients.
|
|
2
1
|
export const SERVER_INFO = {
|
|
3
2
|
name: "perfai-cloud-mcp",
|
|
4
|
-
version: "0.
|
|
3
|
+
version: "0.5.3",
|
|
5
4
|
};
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
export const SERVER_INSTRUCTIONS = "Perfai security testing and auto-fix. Each user command is ONE tool call: " +
|
|
6
|
+
'"Perfai test <url or app>" β run_security_test (a URL that is not registered yet is onboarded, and ' +
|
|
7
|
+
'onboarding runs the first security test itself); "Perfai issues" β get_vulnerabilities; ' +
|
|
8
|
+
'"Perfai status" / "check status" β check_app_status; ' +
|
|
9
|
+
'"Perfai dismiss <n>" β dismiss_vulnerability (also when the user asks to skip, ignore or accept the risk of ' +
|
|
10
|
+
"a finding, or calls it a false positive, not applicable or won't fix); " +
|
|
11
|
+
'"Perfai reopen <n>" β reopen_vulnerability (undo a dismissal, using the ID from the dismiss reply). ' +
|
|
12
|
+
"Dismiss and reopen are available whenever the user asks, not only during a fix run; never tell the user to " +
|
|
13
|
+
'use the web app for them. "Perfai issues dismissed" β get_vulnerabilities with status: "dismissed" ' +
|
|
14
|
+
"(Perfai staff only; other accounts are told so). For a bare command omit app (the current app is used), " +
|
|
15
|
+
"or pass the deployed URL of the project you are working in if you know it. " +
|
|
16
|
+
"Onboarding and security tests run in the background on Perfai: never call check_app_status or " +
|
|
17
|
+
"check_task_status again to wait for them β relay the returned message as-is and stop. Only check again " +
|
|
18
|
+
"when the user asks. " +
|
|
19
|
+
'When the user says "Perfai fix", "<App> fix all", "<App> fix critical|high|medium|low" ' +
|
|
8
20
|
'or "<App> fix N" (e.g. "Bookstore fix all"), make ONE call: auto_fix_all with app: "<App>" ' +
|
|
9
21
|
"(plus severity, or max_fixes: N). Do not call login, list_apps, select_app or manage_organizations first β " +
|
|
10
22
|
"sign-in happens automatically on the first call, and " +
|
|
11
|
-
"the app name is
|
|
12
|
-
"
|
|
13
|
-
"
|
|
14
|
-
"
|
|
15
|
-
|
|
23
|
+
"the app name is looked up in the current organization only. If it is not found there, relay that " +
|
|
24
|
+
"message and stop β switch organizations (manage_organizations select) only when the user asks. " +
|
|
25
|
+
"Then execute the returned plan " +
|
|
26
|
+
"autonomously, by editing code only β never run shell, network or install commands while executing it " +
|
|
27
|
+
"unless the user asks: fix each finding and call mark_vulnerability_fixed. Inside an auto_fix_all run only: " +
|
|
28
|
+
"if a finding does not apply to the code, call dismiss_vulnerability with a specific reason without " +
|
|
29
|
+
"mentioning it in chat. Finish with get_fix_summary and a one-line count. " +
|
|
30
|
+
'Always write the product name as "Perfai", never "PerfAI", and relay each returned message as-is, without rewording it.';
|
|
16
31
|
const API_HOST = process.env.PERFAI_API_HOST || "api.perfai.ai";
|
|
17
|
-
// Per docs.perfai.ai/docs/api/overview: token exchange lives under /api/v1,
|
|
18
|
-
// everything else (apps, tasks, vulnerabilities) lives under /v1.
|
|
19
32
|
export const AUTH_TOKEN_URL = `https://${API_HOST}/api/v1/auth/token`;
|
|
20
33
|
export const API_BASE_URL = `https://${API_HOST}/v1`;
|
|
21
|
-
// Multi-tenant accounts (e.g. SuperAdmin/support) belong to more than one
|
|
22
|
-
// org; app requests are scoped by X-Org-ID, resolved from this endpoint.
|
|
23
34
|
export const ORGANIZATIONS_URL = `https://${API_HOST}/api/v1/org-users/get_users_orgs`;
|
|
24
|
-
// Credentials for non-interactive login (recommended for MCP client configs).
|
|
25
35
|
export const PERFAI_EMAIL = process.env.PERFAI_EMAIL;
|
|
26
36
|
export const PERFAI_PASSWORD = process.env.PERFAI_PASSWORD;
|
|
27
|
-
|
|
28
|
-
// Users copy this from the Perfai console after a normal browser login.
|
|
29
|
-
export const PERFAI_TOKEN = process.env.PERFAI_TOKEN;
|
|
30
|
-
// ββ OAuth / Auth0 PKCE configuration βββββββββββββββββββββββββββββββ
|
|
31
|
-
// Used for the browser-based login flow (Cursor, Claude Code, VS Code, etc.).
|
|
32
|
-
// The PKCE flow produces the same id_token that Perfai's API already accepts.
|
|
37
|
+
export const PERFAI_TOKEN = process.env.PERFAI_TOKEN || process.env.PERFAI_API_KEY;
|
|
33
38
|
export const AUTH0_DOMAIN = process.env.AUTH0_DOMAIN ?? "auth.perfai.ai";
|
|
34
39
|
export const AUTH0_CLIENT_ID = process.env.AUTH0_CLIENT_ID ?? "OxipoJS8EIdpN3KzhVQ280zkKxwzGLfI";
|
|
35
40
|
export const AUTH0_AUDIENCE = process.env.AUTH0_AUDIENCE ?? "";
|
|
36
41
|
export const OAUTH_CALLBACK_PORT = parseInt(process.env.OAUTH_CALLBACK_PORT ?? "5173", 10);
|
|
37
42
|
export const OAUTH_SCOPES = process.env.OAUTH_SCOPES ?? "openid profile email offline_access";
|
|
38
|
-
// How long a tool call waits for the browser sign-in before returning "call
|
|
39
|
-
// again". Keep it under the MCP client's own tool-call timeout.
|
|
40
43
|
export const LOGIN_WAIT_MS = parseInt(process.env.LOGIN_WAIT_SECONDS ?? "90", 10) * 1000;
|
|
41
|
-
// Polling guidance from the API docs: start at 5s, exponential backoff
|
|
42
|
-
// capped at 60s, allow up to 30 minutes total for a security test run.
|
|
43
44
|
export const POLL_START_MS = 5_000;
|
|
44
45
|
export const POLL_MAX_INTERVAL_MS = 60_000;
|
|
45
46
|
export const POLL_TASK_TIMEOUT_MS = 30 * 60 * 1000;
|
|
46
47
|
export const POLL_REGISTRATION_TIMEOUT_MS = 30 * 60 * 1000;
|
|
47
|
-
// A single `check_*_status` tool call polls in-process for at most this long
|
|
48
|
-
// before returning the current (possibly non-terminal) state, so it never
|
|
49
|
-
// hangs past a calling client's own request timeout. Callers re-invoke the
|
|
50
|
-
// tool to keep polling β mirrors the `wait_seconds` pattern.
|
|
51
|
-
// Kept short by default since some MCP clients (e.g. the Inspector) use a
|
|
52
|
-
// client-side request timeout well under a minute; pass a larger
|
|
53
|
-
// wait_seconds explicitly if your client's timeout is raised to allow it.
|
|
54
|
-
export const DEFAULT_TOOL_POLL_BUDGET_MS = 8_000;
|
|
55
|
-
export const MAX_TOOL_POLL_BUDGET_MS = 240_000;
|
|
56
|
-
// auto_fix_all returns at most this many findings per call so a large app's
|
|
57
|
-
// plan stays under MCP clients' tool-output limits; the agent calls again
|
|
58
|
-
// for the next batch.
|
|
59
48
|
export const FIX_BATCH_SIZE = 15;
|
|
60
49
|
export const TASK_TERMINAL_STATES = new Set([
|
|
61
50
|
"COMPLETED",
|
|
62
|
-
"
|
|
63
|
-
"
|
|
51
|
+
"COMPLETED_PARTIAL",
|
|
52
|
+
"NEEDS_INPUT",
|
|
64
53
|
"INTERRUPTED",
|
|
54
|
+
"CANCELLED",
|
|
55
|
+
"FAILED",
|
|
56
|
+
"AWAITING_INPUT",
|
|
65
57
|
]);
|
|
66
58
|
export const APP_TERMINAL_STATES = new Set([
|
|
67
59
|
"COMPLETED",
|
|
60
|
+
"COMPLETED_PARTIAL",
|
|
61
|
+
"NEEDS_INPUT",
|
|
62
|
+
"INTERRUPTED",
|
|
63
|
+
"CANCELLED",
|
|
68
64
|
"FAILED",
|
|
65
|
+
"AWAITING_INPUT",
|
|
69
66
|
]);
|
package/dist/env.js
CHANGED
|
@@ -1,8 +1,2 @@
|
|
|
1
|
-
// Loads .env into process.env as a side effect of importing this module.
|
|
2
|
-
// Must be imported before any module that reads process.env at its own
|
|
3
|
-
// top level (e.g. config.ts) β ES module imports are fully evaluated before
|
|
4
|
-
// the importing file's own statements run, so calling dotenv.config() as a
|
|
5
|
-
// plain statement further down in server.ts would run too late.
|
|
6
1
|
import dotenv from "dotenv";
|
|
7
|
-
// dotenvx v17 writes to stdout by default, which would corrupt MCP stdio.
|
|
8
2
|
dotenv.config({ quiet: true });
|
package/dist/log-guard.js
CHANGED
|
@@ -1,12 +1,3 @@
|
|
|
1
|
-
// MCP stdio transport requires that stdout carry ONLY JSON-RPC messages.
|
|
2
|
-
// Any stray write to stdout (e.g. a dependency's banner/tips, a stray
|
|
3
|
-
// console.log) corrupts the stream and the client drops the connection with
|
|
4
|
-
// "MCP error -32000: Connection closed".
|
|
5
|
-
//
|
|
6
|
-
// This module is imported first (before any other import) so that every
|
|
7
|
-
// console.* call β ours or a dependency's β is redirected to stderr, leaving
|
|
8
|
-
// stdout exclusively for the protocol. The MCP SDK writes protocol frames via
|
|
9
|
-
// process.stdout.write directly, so it is unaffected by this redirect.
|
|
10
1
|
const toStderr = (...args) => {
|
|
11
2
|
console.error(...args);
|
|
12
3
|
};
|
package/dist/prompts.js
CHANGED
|
@@ -1,9 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* MCP prompts β clients that support them (e.g. Claude Code exposes them as
|
|
3
|
-
* /mcp__<server>__fix_all) get a real slash command, so the one-line fix
|
|
4
|
-
* doesn't depend on how an agent reads a sentence. Each prompt just expands
|
|
5
|
-
* into a message that makes a single auto_fix_all call.
|
|
6
|
-
*/
|
|
7
1
|
const SEVERITIES = new Set(["critical", "high", "medium", "low"]);
|
|
8
2
|
export const PROMPTS = [
|
|
9
3
|
{
|
|
@@ -20,7 +14,6 @@ export const PROMPTS = [
|
|
|
20
14
|
],
|
|
21
15
|
},
|
|
22
16
|
];
|
|
23
|
-
/** Maps "all" / "critical" / "3" / "top 3" / "#3" onto auto_fix_all arguments. */
|
|
24
17
|
export function parseFixTarget(target) {
|
|
25
18
|
const t = (target ?? "").trim().toLowerCase().replace(/^top\s+/, "").replace(/^#/, "");
|
|
26
19
|
if (SEVERITIES.has(t))
|
|
@@ -45,7 +38,8 @@ export function getPrompt(name, args = {}) {
|
|
|
45
38
|
content: {
|
|
46
39
|
type: "text",
|
|
47
40
|
text: `Call the Perfai \`auto_fix_all\` tool with ${JSON.stringify(toolArgs)} β do not log in, or list or ` +
|
|
48
|
-
`select orgs or apps first. Then follow the plan it returns, autonomously and without asking me anything
|
|
41
|
+
`select orgs or apps first. Then follow the plan it returns, autonomously and without asking me anything β ` +
|
|
42
|
+
`by editing code only, without running shell or network commands.`,
|
|
49
43
|
},
|
|
50
44
|
},
|
|
51
45
|
],
|
package/dist/server.js
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// Must be first: redirects console.* to stderr so stdout carries only JSON-RPC.
|
|
3
2
|
import "./log-guard.js";
|
|
4
|
-
// Must be second: loads .env before config.js reads process.env at import time.
|
|
5
3
|
import "./env.js";
|
|
6
4
|
import { randomUUID } from "node:crypto";
|
|
7
5
|
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
@@ -13,6 +11,7 @@ import { SERVER_INFO, SERVER_INSTRUCTIONS } from "./config.js";
|
|
|
13
11
|
import { PROMPTS, getPrompt } from "./prompts.js";
|
|
14
12
|
import { LOGIN_PENDING_TEXT, ensureLoggedIn } from "./tools/public/login.js";
|
|
15
13
|
import { AuthManager } from "./client/authManager.js";
|
|
14
|
+
import { loggable } from "./client/errors.js";
|
|
16
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";
|
|
17
16
|
function createMcpServer(auth) {
|
|
18
17
|
const server = new Server(SERVER_INFO, {
|
|
@@ -48,11 +47,9 @@ function createMcpServer(auth) {
|
|
|
48
47
|
return await handleAuthStatus(auth);
|
|
49
48
|
}
|
|
50
49
|
if (!auth.isAuthenticated() && !auth.hasCredentials()) {
|
|
51
|
-
// HTTP sessions are authenticated by bearer token; a browser on the server host is no use.
|
|
52
50
|
if (process.env.MCP_TRANSPORT?.toLowerCase() === "http") {
|
|
53
51
|
throw new McpError(ErrorCode.InvalidRequest, `Authentication required. Run the 'login' tool first to access '${name}'.`);
|
|
54
52
|
}
|
|
55
|
-
// Local: sign in on first use, so "<App> fix all" works as the very first message.
|
|
56
53
|
if (!(await ensureLoggedIn(auth))) {
|
|
57
54
|
return { content: [{ type: "text", text: LOGIN_PENDING_TEXT }] };
|
|
58
55
|
}
|
|
@@ -99,8 +96,8 @@ function createMcpServer(auth) {
|
|
|
99
96
|
catch (error) {
|
|
100
97
|
if (error instanceof McpError)
|
|
101
98
|
throw error;
|
|
102
|
-
console.error(`Tool '${name}' failed:`, error);
|
|
103
|
-
throw new McpError(ErrorCode.InternalError, `Tool
|
|
99
|
+
console.error(`Tool '${name}' failed:`, loggable(error));
|
|
100
|
+
throw new McpError(ErrorCode.InternalError, `Tool '${name}' failed β see server logs`);
|
|
104
101
|
}
|
|
105
102
|
});
|
|
106
103
|
server.onerror = (error) => {
|
|
@@ -108,174 +105,78 @@ function createMcpServer(auth) {
|
|
|
108
105
|
};
|
|
109
106
|
return server;
|
|
110
107
|
}
|
|
111
|
-
/* ------------------------------------------------------------------ */
|
|
112
|
-
/* Stdio transport (default β used by Cursor, Claude Code, etc.) */
|
|
113
|
-
/* ------------------------------------------------------------------ */
|
|
114
108
|
async function startStdio() {
|
|
115
109
|
const auth = new AuthManager();
|
|
116
110
|
const server = createMcpServer(auth);
|
|
117
111
|
const transport = new StdioServerTransport();
|
|
118
112
|
await server.connect(transport);
|
|
119
113
|
if (auth.isAuthenticated()) {
|
|
120
|
-
console.error(`Ready (stdio). Already authenticated as ${auth.
|
|
114
|
+
console.error(`Ready (stdio). Already authenticated as ${auth.describeIdentity()} via ${auth.getAuthMethod()}.`);
|
|
121
115
|
}
|
|
122
116
|
else {
|
|
123
|
-
console.error("Ready (stdio). Run 'login' to authenticate (or set PERFAI_TOKEN / PERFAI_EMAIL+PERFAI_PASSWORD).");
|
|
117
|
+
console.error("Ready (stdio). Run 'login' to authenticate (or set PERFAI_API_KEY / PERFAI_TOKEN / PERFAI_EMAIL+PERFAI_PASSWORD).");
|
|
124
118
|
}
|
|
125
119
|
process.on("SIGINT", async () => {
|
|
126
120
|
await server.close();
|
|
127
121
|
process.exit(0);
|
|
128
122
|
});
|
|
129
123
|
}
|
|
130
|
-
|
|
131
|
-
/* HTTP transport (for ChatGPT, remote MCP clients, etc.) */
|
|
132
|
-
/* ------------------------------------------------------------------ */
|
|
133
|
-
import { validateBearerToken, isJWT } from "./auth/tokenValidator.js";
|
|
134
|
-
function decodeCredentialToken(token) {
|
|
135
|
-
try {
|
|
136
|
-
const decoded = Buffer.from(token, "base64").toString("utf-8");
|
|
137
|
-
const colonIndex = decoded.indexOf(":");
|
|
138
|
-
if (colonIndex <= 0 || colonIndex === decoded.length - 1)
|
|
139
|
-
return null;
|
|
140
|
-
// Heuristic: if decoded looks like email:password (has @ before colon),
|
|
141
|
-
// it's likely the legacy format. JWTs won't decode to this pattern.
|
|
142
|
-
if (!decoded.slice(0, colonIndex).includes("@"))
|
|
143
|
-
return null;
|
|
144
|
-
return {
|
|
145
|
-
email: decoded.slice(0, colonIndex),
|
|
146
|
-
password: decoded.slice(colonIndex + 1),
|
|
147
|
-
};
|
|
148
|
-
}
|
|
149
|
-
catch {
|
|
150
|
-
return null;
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
async function validatePerfAICredentials(email, password) {
|
|
154
|
-
const { default: axios } = await import("axios");
|
|
155
|
-
const { AUTH_TOKEN_URL } = await import("./config.js");
|
|
156
|
-
try {
|
|
157
|
-
const response = await axios.post(AUTH_TOKEN_URL, { username: email, password }, { headers: { "Content-Type": "application/json" }, timeout: 15_000 });
|
|
158
|
-
return Boolean(response.data?.id_token);
|
|
159
|
-
}
|
|
160
|
-
catch {
|
|
161
|
-
return false;
|
|
162
|
-
}
|
|
163
|
-
}
|
|
124
|
+
import { createBearerAuth, sameCaller } from "./auth/bearerAuth.js";
|
|
164
125
|
async function startHttp() {
|
|
165
126
|
const { default: express } = await import("express");
|
|
166
127
|
const app = express();
|
|
167
128
|
app.use(express.json());
|
|
168
129
|
const MCP_API_KEY = process.env.MCP_API_KEY;
|
|
169
|
-
console.error("Auth mode: OAuth tokens
|
|
170
|
-
(MCP_API_KEY ? " + static MCP_API_KEY (legacy)" : "")
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
const authHeader = req.headers.authorization;
|
|
179
|
-
if (!authHeader || !authHeader.startsWith("Bearer ")) {
|
|
180
|
-
res.status(401).json({
|
|
181
|
-
jsonrpc: "2.0",
|
|
182
|
-
error: {
|
|
183
|
-
code: -32001,
|
|
184
|
-
message: "Unauthorized: Bearer token required. " +
|
|
185
|
-
"Use your Perfai id_token (from OAuth login or PERFAI_TOKEN) as the bearer value.",
|
|
186
|
-
},
|
|
187
|
-
id: null,
|
|
188
|
-
});
|
|
189
|
-
return;
|
|
190
|
-
}
|
|
191
|
-
const token = authHeader.slice(7);
|
|
192
|
-
// 1. Check static MCP_API_KEY first (backward compatible)
|
|
193
|
-
if (MCP_API_KEY && token === MCP_API_KEY) {
|
|
194
|
-
return next();
|
|
195
|
-
}
|
|
196
|
-
// 2. Real token (JWT) β primary path
|
|
197
|
-
if (isJWT(token)) {
|
|
198
|
-
const result = await validateBearerToken(token);
|
|
199
|
-
if (result.valid) {
|
|
200
|
-
req.perfaiToken = token;
|
|
201
|
-
req.perfaiEmail = result.email;
|
|
202
|
-
console.error(`Authenticated (token): ${result.email ?? "unknown"}`);
|
|
203
|
-
return next();
|
|
204
|
-
}
|
|
205
|
-
res.status(401).json({
|
|
130
|
+
console.error("Auth mode: PerfAI API keys + OAuth tokens" +
|
|
131
|
+
(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({
|
|
206
139
|
jsonrpc: "2.0",
|
|
207
|
-
error: {
|
|
208
|
-
code: -32001,
|
|
209
|
-
message: `Token validation failed: ${result.error ?? "invalid token"}. ` +
|
|
210
|
-
"Get a fresh token via OAuth login at https://cloud.perfai.ai or set PERFAI_TOKEN.",
|
|
211
|
-
},
|
|
140
|
+
error: { code: -32000, message: "Invalid or missing session ID" },
|
|
212
141
|
id: null,
|
|
213
142
|
});
|
|
214
|
-
return;
|
|
143
|
+
return undefined;
|
|
215
144
|
}
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
if (creds) {
|
|
219
|
-
console.error(`DEPRECATED: base64(email:password) auth from ${creds.email}. ` +
|
|
220
|
-
"Migrate to OAuth tokens (id_token) β see docs.");
|
|
221
|
-
const valid = await validatePerfAICredentials(creds.email, creds.password);
|
|
222
|
-
if (valid) {
|
|
223
|
-
req.perfaiCredentials = creds;
|
|
224
|
-
req.perfaiEmail = creds.email;
|
|
225
|
-
return next();
|
|
226
|
-
}
|
|
145
|
+
if (!sameCaller(req, sessions[sessionId].credentialHash)) {
|
|
146
|
+
console.error(`Rejected session ${sessionId}: bearer differs from the one that opened it.`);
|
|
227
147
|
res.status(403).json({
|
|
228
148
|
jsonrpc: "2.0",
|
|
229
|
-
error: {
|
|
230
|
-
code: -32001,
|
|
231
|
-
message: `Authentication failed for ${creds.email}. ` +
|
|
232
|
-
"Verify credentials at https://cloud.perfai.ai, or migrate to OAuth token auth.",
|
|
233
|
-
},
|
|
149
|
+
error: { code: -32001, message: "Forbidden: this session belongs to a different credential." },
|
|
234
150
|
id: null,
|
|
235
151
|
});
|
|
236
|
-
return;
|
|
152
|
+
return undefined;
|
|
237
153
|
}
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
jsonrpc: "2.0",
|
|
241
|
-
error: {
|
|
242
|
-
code: -32001,
|
|
243
|
-
message: "Unrecognized token format. Provide either: " +
|
|
244
|
-
"(1) a Perfai id_token from OAuth login, or " +
|
|
245
|
-
"(2) PERFAI_TOKEN from your Perfai console.",
|
|
246
|
-
},
|
|
247
|
-
id: null,
|
|
248
|
-
});
|
|
249
|
-
};
|
|
250
|
-
app.use("/mcp", bearerAuth);
|
|
251
|
-
// Per-session state
|
|
252
|
-
const transports = {};
|
|
253
|
-
const sessions = {};
|
|
254
|
-
// POST /mcp β main MCP request endpoint
|
|
154
|
+
return transports[sessionId];
|
|
155
|
+
}
|
|
255
156
|
app.post("/mcp", async (req, res) => {
|
|
256
157
|
const sessionId = req.headers["mcp-session-id"];
|
|
257
158
|
try {
|
|
258
|
-
if (sessionId
|
|
259
|
-
|
|
159
|
+
if (sessionId) {
|
|
160
|
+
const transport = sessionTransport(req, res);
|
|
161
|
+
if (transport)
|
|
162
|
+
await transport.handleRequest(req, res, req.body);
|
|
260
163
|
return;
|
|
261
164
|
}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
if (
|
|
266
|
-
|
|
267
|
-
auth.setToken(req.perfaiToken, req.perfaiEmail, "oauth");
|
|
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");
|
|
268
170
|
}
|
|
269
|
-
else if (
|
|
270
|
-
|
|
271
|
-
auth.setCredentials(req.perfaiCredentials.email, req.perfaiCredentials.password);
|
|
171
|
+
else if (gate.method === "jwt" && gate.token) {
|
|
172
|
+
auth.setToken(gate.token, gate.email, "oauth");
|
|
272
173
|
}
|
|
273
174
|
const transport = new StreamableHTTPServerTransport({
|
|
274
175
|
sessionIdGenerator: () => randomUUID(),
|
|
275
176
|
onsessioninitialized: (sid) => {
|
|
276
177
|
transports[sid] = transport;
|
|
277
|
-
sessions[sid] = { auth };
|
|
278
|
-
console.error(`Session initialized: ${sid} (
|
|
178
|
+
sessions[sid] = { auth, credentialHash: gate.credentialHash };
|
|
179
|
+
console.error(`Session initialized: ${sid} (${gate.method}: ${auth.describeIdentity()})`);
|
|
279
180
|
},
|
|
280
181
|
});
|
|
281
182
|
transport.onclose = () => {
|
|
@@ -298,7 +199,7 @@ async function startHttp() {
|
|
|
298
199
|
});
|
|
299
200
|
}
|
|
300
201
|
catch (error) {
|
|
301
|
-
console.error("Error handling MCP request:", error);
|
|
202
|
+
console.error("Error handling MCP request:", error instanceof Error ? error.message : String(error));
|
|
302
203
|
if (!res.headersSent) {
|
|
303
204
|
res.status(500).json({
|
|
304
205
|
jsonrpc: "2.0",
|
|
@@ -308,50 +209,21 @@ async function startHttp() {
|
|
|
308
209
|
}
|
|
309
210
|
}
|
|
310
211
|
});
|
|
311
|
-
// GET /mcp β SSE stream for server-initiated messages
|
|
312
212
|
app.get("/mcp", async (req, res) => {
|
|
313
|
-
const
|
|
314
|
-
if (
|
|
315
|
-
|
|
316
|
-
jsonrpc: "2.0",
|
|
317
|
-
error: { code: -32000, message: "Invalid or missing session ID" },
|
|
318
|
-
id: null,
|
|
319
|
-
});
|
|
320
|
-
return;
|
|
321
|
-
}
|
|
322
|
-
await transports[sessionId].handleRequest(req, res);
|
|
213
|
+
const transport = sessionTransport(req, res);
|
|
214
|
+
if (transport)
|
|
215
|
+
await transport.handleRequest(req, res);
|
|
323
216
|
});
|
|
324
|
-
// DELETE /mcp β session termination
|
|
325
217
|
app.delete("/mcp", async (req, res) => {
|
|
326
|
-
const
|
|
327
|
-
if (
|
|
328
|
-
|
|
329
|
-
jsonrpc: "2.0",
|
|
330
|
-
error: { code: -32000, message: "Invalid or missing session ID" },
|
|
331
|
-
id: null,
|
|
332
|
-
});
|
|
333
|
-
return;
|
|
334
|
-
}
|
|
335
|
-
await transports[sessionId].handleRequest(req, res);
|
|
218
|
+
const transport = sessionTransport(req, res);
|
|
219
|
+
if (transport)
|
|
220
|
+
await transport.handleRequest(req, res);
|
|
336
221
|
});
|
|
337
|
-
// Root β friendly landing page
|
|
338
222
|
app.get("/", (_req, res) => {
|
|
339
|
-
res.json({
|
|
340
|
-
name: SERVER_INFO.name,
|
|
341
|
-
version: SERVER_INFO.version,
|
|
342
|
-
status: "running",
|
|
343
|
-
mcp_endpoint: "/mcp",
|
|
344
|
-
auth: {
|
|
345
|
-
primary: "Bearer <id_token> β use your Perfai OAuth token",
|
|
346
|
-
headless: "Set PERFAI_TOKEN env var with your token from https://cloud.perfai.ai",
|
|
347
|
-
deprecated: "base64(email:password) still accepted but will be removed",
|
|
348
|
-
},
|
|
349
|
-
docs: "This is a Model Context Protocol (MCP) server for Perfai. Connect to /mcp from any MCP-compatible client (ChatGPT, Cursor, Claude, etc.).",
|
|
350
|
-
});
|
|
223
|
+
res.json({ status: "ok" });
|
|
351
224
|
});
|
|
352
|
-
// Health-check endpoint
|
|
353
225
|
app.get("/health", (_req, res) => {
|
|
354
|
-
res.json({ status: "ok"
|
|
226
|
+
res.json({ status: "ok" });
|
|
355
227
|
});
|
|
356
228
|
const PORT = parseInt(process.env.PORT || "3000", 10);
|
|
357
229
|
app.listen(PORT, "0.0.0.0", () => {
|
|
@@ -368,9 +240,6 @@ async function startHttp() {
|
|
|
368
240
|
process.exit(0);
|
|
369
241
|
});
|
|
370
242
|
}
|
|
371
|
-
/* ------------------------------------------------------------------ */
|
|
372
|
-
/* Entry point */
|
|
373
|
-
/* ------------------------------------------------------------------ */
|
|
374
243
|
async function main() {
|
|
375
244
|
console.error(`Starting ${SERVER_INFO.name} v${SERVER_INFO.version}...`);
|
|
376
245
|
console.error("Public tools:", Object.keys(PUBLIC_TOOLS).join(", "));
|
|
@@ -40,7 +40,6 @@ export async function handleAutoFix(auth, args) {
|
|
|
40
40
|
appLabel = resolved.app.label;
|
|
41
41
|
vuln = auth.getCachedVulnerability(appId, args.vulnerability_id);
|
|
42
42
|
if (!vuln) {
|
|
43
|
-
// Fresh session (e.g. the user named the app directly) β load findings instead of failing.
|
|
44
43
|
auth.cacheVulnerabilities(appId, await getAllVulnerabilities(auth, appId));
|
|
45
44
|
vuln = auth.getCachedVulnerability(appId, args.vulnerability_id);
|
|
46
45
|
}
|
|
@@ -6,10 +6,11 @@ export const autoFixAllTool = {
|
|
|
6
6
|
name: "auto_fix_all",
|
|
7
7
|
description: "π§ ONE-CALL FIX. When the user says \"<App> fix all\", \"<App> fix critical\" or \"<App> fix 3\" " +
|
|
8
8
|
"(e.g. \"Bookstore fix all\"), call this tool directly with app: \"<App>\" β do NOT call login, list_apps, " +
|
|
9
|
-
"select_app or manage_organizations first; sign-in happens automatically and the name is
|
|
10
|
-
"
|
|
9
|
+
"select_app or manage_organizations first; sign-in happens automatically and the name is looked up " +
|
|
10
|
+
"in the current organization (if it is not there, relay the reply β switch orgs only when the user asks). " +
|
|
11
11
|
"\"fix all\" β no filter; \"fix critical|high|medium|low\" β severity; \"fix N\" β max_fixes: N " +
|
|
12
|
-
"(the N most severe). Returns a prioritized plan (critical β low) that you execute autonomously
|
|
12
|
+
"(the N most severe). Returns a prioritized plan (critical β low) that you execute autonomously, " +
|
|
13
|
+
"by editing code only (no shell or network commands): " +
|
|
13
14
|
"fix each finding and call mark_vulnerability_fixed, or β if it does not apply to the code β " +
|
|
14
15
|
"silently call dismiss_vulnerability with a specific reason.",
|
|
15
16
|
inputSchema: {
|
|
@@ -40,9 +41,7 @@ export async function handleAutoFixAll(auth, args) {
|
|
|
40
41
|
return { content: [{ type: "text", text: resolved.message }] };
|
|
41
42
|
const { appId, label } = resolved.app;
|
|
42
43
|
const allVulnerabilities = await getAllVulnerabilities(auth, appId);
|
|
43
|
-
// Cache them for mark_vulnerability_fixed / dismiss_vulnerability calls later
|
|
44
44
|
auth.cacheVulnerabilities(appId, allVulnerabilities);
|
|
45
|
-
// Sort before limiting, so "fix 1" means the most severe open finding.
|
|
46
45
|
let toFix = sortBySeverity(allVulnerabilities.filter(isOpen));
|
|
47
46
|
if (args?.severity) {
|
|
48
47
|
const target = args.severity.toLowerCase();
|
|
@@ -57,8 +56,6 @@ export async function handleAutoFixAll(auth, args) {
|
|
|
57
56
|
: `β
No open vulnerabilities for "${label}" β everything is fixed, claimed fixed, or dismissed.`;
|
|
58
57
|
return { content: [{ type: "text", text: msg }] };
|
|
59
58
|
}
|
|
60
|
-
// Large apps are returned in batches so one response never blows the client's
|
|
61
|
-
// tool-output limit; handled items drop out of isOpen, so the next call is the next batch.
|
|
62
59
|
const batch = toFix.slice(0, FIX_BATCH_SIZE);
|
|
63
60
|
const plan = buildBatchFixPlan(label, batch, toFix.length - batch.length);
|
|
64
61
|
return { content: [{ type: "text", text: plan }] };
|
|
@@ -1,20 +1,16 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { APP_TERMINAL_STATES, DEFAULT_TOOL_POLL_BUDGET_MS, MAX_TOOL_POLL_BUDGET_MS, POLL_START_MS, POLL_MAX_INTERVAL_MS } from "../../config.js";
|
|
1
|
+
import { appName } from "../../utils/appResolver.js";
|
|
2
|
+
import { getRegistrationSnapshot } from "../../utils/registrationState.js";
|
|
3
|
+
import { PARTIAL_FINDINGS_NOTE, stillOnboardingMessage } from "../../utils/runState.js";
|
|
5
4
|
export const checkAppStatusTool = {
|
|
6
5
|
name: "check_app_status",
|
|
7
|
-
description: "β³
|
|
8
|
-
"
|
|
9
|
-
"
|
|
6
|
+
description: "β³ Check an app's onboarding once (GET /v1/apps/{appId}, plus its registration task for pauses) and " +
|
|
7
|
+
"return right away. Call it only when the user asks for the status β never repeatedly to wait for " +
|
|
8
|
+
"onboarding, which runs in the background and includes the first security test. " +
|
|
9
|
+
"Show the user the returned message as-is.",
|
|
10
10
|
inputSchema: {
|
|
11
11
|
type: "object",
|
|
12
12
|
properties: {
|
|
13
13
|
appId: { type: "string", description: "App ID (defaults to the most recently registered/selected app)" },
|
|
14
|
-
wait_seconds: {
|
|
15
|
-
type: "number",
|
|
16
|
-
description: "Max seconds to poll before returning current status (default 20, max 240)",
|
|
17
|
-
},
|
|
18
14
|
},
|
|
19
15
|
additionalProperties: false,
|
|
20
16
|
},
|
|
@@ -24,30 +20,36 @@ export async function handleCheckAppStatus(auth, args) {
|
|
|
24
20
|
if (!appId) {
|
|
25
21
|
return { content: [{ type: "text", text: "β No app selected. Run register_app or select_app first." }] };
|
|
26
22
|
}
|
|
27
|
-
const budgetMs = Math.min((args?.wait_seconds ? args.wait_seconds * 1000 : DEFAULT_TOOL_POLL_BUDGET_MS), MAX_TOOL_POLL_BUDGET_MS);
|
|
28
23
|
try {
|
|
29
|
-
const {
|
|
30
|
-
fetch: () => getApp(auth, appId),
|
|
31
|
-
isTerminal: (a) => APP_TERMINAL_STATES.has(a.registrationStatus ?? "") || a.registrationStatus === "AWAITING_INPUT",
|
|
32
|
-
budgetMs,
|
|
33
|
-
startIntervalMs: POLL_START_MS,
|
|
34
|
-
maxIntervalMs: POLL_MAX_INTERVAL_MS,
|
|
35
|
-
});
|
|
24
|
+
const { app, view } = await getRegistrationSnapshot(auth, appId);
|
|
36
25
|
auth.setCurrentApp(app.appId, app.appUrl ?? auth.currentAppUrl);
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
26
|
+
console.error(`check_app_status: app=${app.appId} status=${app.registrationStatus ?? "none"} outcome=${view.outcome}`);
|
|
27
|
+
const name = appName(app);
|
|
28
|
+
let text;
|
|
29
|
+
switch (view.outcome) {
|
|
30
|
+
case "ready":
|
|
31
|
+
text = `β
${name} onboarding is complete. Say perfai issues to view issues.`;
|
|
32
|
+
break;
|
|
33
|
+
case "partial":
|
|
34
|
+
text = `${name}: ${view.message}\n\n${PARTIAL_FINDINGS_NOTE}`;
|
|
35
|
+
break;
|
|
36
|
+
case "needs_input":
|
|
37
|
+
text =
|
|
38
|
+
`βΈοΈ ${name}: ${view.message}\n\nIf it needs a login, supply one with submit_app_credentials. ` +
|
|
39
|
+
"Otherwise resolve it in the Perfai console.";
|
|
40
|
+
break;
|
|
41
|
+
case "interrupted":
|
|
42
|
+
text =
|
|
43
|
+
`${name}: ${view.message}\n\nIf it stays this way, run register_app again with the same URL β ` +
|
|
44
|
+
"it replaces this registration.";
|
|
45
|
+
break;
|
|
46
|
+
case "cancelled":
|
|
47
|
+
text = `${name}: ${view.message}\n\nRun register_app again with the same URL to restart onboarding.`;
|
|
48
|
+
break;
|
|
49
|
+
default:
|
|
50
|
+
text = stillOnboardingMessage(name);
|
|
40
51
|
}
|
|
41
|
-
|
|
42
|
-
hint = "\n\nβ οΈ Onboarding needs credentials β use submit_app_credentials, then check_app_status again.";
|
|
43
|
-
}
|
|
44
|
-
else if (app.registrationStatus === "FAILED") {
|
|
45
|
-
hint = "\n\nβ Registration failed β check the app URL and try register_app again.";
|
|
46
|
-
}
|
|
47
|
-
else if (!terminal) {
|
|
48
|
-
hint = `\n\nβ³ Still ${app.registrationStatus ?? "pending"} after ${Math.round(budgetMs / 1000)}s β call check_app_status again.`;
|
|
49
|
-
}
|
|
50
|
-
return { content: [{ type: "text", text: formatApp(app) + hint }] };
|
|
52
|
+
return { content: [{ type: "text", text }] };
|
|
51
53
|
}
|
|
52
54
|
catch (error) {
|
|
53
55
|
return {
|