perfai-cloud-mcp 0.5.3 → 0.7.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -10
- package/dist/auth/bearerAuth.js +103 -19
- package/dist/auth/tokenValidator.js +3 -2
- package/dist/client/apiClient.js +45 -11
- package/dist/client/authManager.js +46 -10
- package/dist/client/errors.js +11 -0
- package/dist/client/relay.js +63 -0
- package/dist/config.js +23 -4
- package/dist/http.js +125 -0
- package/dist/mcpServer.js +132 -0
- package/dist/server.js +18 -207
- package/dist/tools/protected/autoFix.js +13 -10
- package/dist/tools/protected/autoFixAll.js +16 -8
- package/dist/tools/protected/getFixSummary.js +2 -2
- package/dist/tools/protected/getVulnerabilities.js +59 -12
- package/dist/tools/protected/listApps.js +1 -1
- package/dist/tools/protected/registerApp.js +7 -3
- package/dist/tools/protected/runSecurityTest.js +67 -13
- package/dist/tools/protected/suggestFix.js +5 -4
- package/dist/tools/protected/vulnerabilityActions.js +104 -33
- package/dist/utils/appResolver.js +8 -0
- package/dist/utils/clientInfo.js +8 -0
- package/dist/utils/dismissReason.js +73 -0
- package/dist/utils/formatters.js +18 -25
- package/dist/utils/promptBuilder.js +63 -6
- package/dist/utils/runState.js +3 -6
- package/dist/utils/testInfo.js +93 -0
- package/package.json +3 -3
package/dist/http.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import express from "express";
|
|
3
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
4
|
+
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
|
5
|
+
import { createBearerAuth, protectedResourceMetadata, sameCaller, sessionKey, } from "./auth/bearerAuth.js";
|
|
6
|
+
import { AuthManager } from "./client/authManager.js";
|
|
7
|
+
import { MCP_OAUTH_DOCS_URL } from "./config.js";
|
|
8
|
+
import { createMcpServer } from "./mcpServer.js";
|
|
9
|
+
const AUTH_METHOD = {
|
|
10
|
+
api_key: "api_key",
|
|
11
|
+
jwt: "oauth",
|
|
12
|
+
mcp_oauth: "mcp_oauth",
|
|
13
|
+
};
|
|
14
|
+
function applyGate(auth, gate) {
|
|
15
|
+
if (gate.method === "mcp_api_key" || !gate.token)
|
|
16
|
+
return;
|
|
17
|
+
auth.setToken(gate.token, gate.email, AUTH_METHOD[gate.method]);
|
|
18
|
+
auth.setScopes(gate.method === "mcp_oauth" ? gate.scopes : undefined);
|
|
19
|
+
}
|
|
20
|
+
function jsonRpcError(res, status, code, message) {
|
|
21
|
+
res.status(status).json({ jsonrpc: "2.0", error: { code, message }, id: null });
|
|
22
|
+
}
|
|
23
|
+
export function createHttpApp(options) {
|
|
24
|
+
const app = express();
|
|
25
|
+
app.use(express.json());
|
|
26
|
+
if (options.resourceUrl) {
|
|
27
|
+
const metadata = protectedResourceMetadata(options.resourceUrl, MCP_OAUTH_DOCS_URL);
|
|
28
|
+
const serveMetadata = (_req, res) => {
|
|
29
|
+
res.setHeader("Cache-Control", "public, max-age=3600");
|
|
30
|
+
res.json(metadata);
|
|
31
|
+
};
|
|
32
|
+
app.get("/.well-known/oauth-protected-resource", serveMetadata);
|
|
33
|
+
app.get("/.well-known/oauth-protected-resource/mcp", serveMetadata);
|
|
34
|
+
}
|
|
35
|
+
app.use("/mcp", createBearerAuth(options));
|
|
36
|
+
const transports = {};
|
|
37
|
+
const sessions = {};
|
|
38
|
+
function sessionTransport(req, res) {
|
|
39
|
+
const sessionId = req.headers["mcp-session-id"];
|
|
40
|
+
if (!sessionId) {
|
|
41
|
+
jsonRpcError(res, 400, -32000, "Bad Request: Mcp-Session-Id header is required");
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
const session = sessions[sessionId];
|
|
45
|
+
if (!session || !transports[sessionId]) {
|
|
46
|
+
jsonRpcError(res, 404, -32001, "Session not found");
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
if (!sameCaller(req, session.key)) {
|
|
50
|
+
console.error(`Rejected session ${sessionId}: caller differs from the one that opened it.`);
|
|
51
|
+
jsonRpcError(res, 403, -32001, "Forbidden: this session belongs to a different caller.");
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
applyGate(session.auth, req.perfaiAuth);
|
|
55
|
+
return transports[sessionId];
|
|
56
|
+
}
|
|
57
|
+
app.post("/mcp", async (req, res) => {
|
|
58
|
+
const sessionId = req.headers["mcp-session-id"];
|
|
59
|
+
try {
|
|
60
|
+
if (sessionId) {
|
|
61
|
+
const transport = sessionTransport(req, res);
|
|
62
|
+
if (transport)
|
|
63
|
+
await transport.handleRequest(req, res, req.body);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
const gate = req.perfaiAuth;
|
|
67
|
+
if (gate && isInitializeRequest(req.body)) {
|
|
68
|
+
const auth = new AuthManager({ useEnv: false });
|
|
69
|
+
applyGate(auth, gate);
|
|
70
|
+
const transport = new StreamableHTTPServerTransport({
|
|
71
|
+
sessionIdGenerator: () => randomUUID(),
|
|
72
|
+
onsessioninitialized: (sid) => {
|
|
73
|
+
transports[sid] = transport;
|
|
74
|
+
sessions[sid] = { auth, key: sessionKey(gate) };
|
|
75
|
+
console.error(`Session initialized: ${sid} (${gate.method}: ${auth.describeIdentity()})`);
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
transport.onclose = () => {
|
|
79
|
+
const sid = transport.sessionId;
|
|
80
|
+
if (sid) {
|
|
81
|
+
delete transports[sid];
|
|
82
|
+
delete sessions[sid];
|
|
83
|
+
console.error(`Session closed: ${sid}`);
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
const server = createMcpServer(auth);
|
|
87
|
+
await server.connect(transport);
|
|
88
|
+
await transport.handleRequest(req, res, req.body);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
jsonRpcError(res, 400, -32000, "Bad Request: No valid session ID provided");
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
console.error("Error handling MCP request:", error instanceof Error ? error.message : String(error));
|
|
95
|
+
if (!res.headersSent)
|
|
96
|
+
jsonRpcError(res, 500, -32603, "Internal server error");
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
app.get("/mcp", async (req, res) => {
|
|
100
|
+
const transport = sessionTransport(req, res);
|
|
101
|
+
if (transport)
|
|
102
|
+
await transport.handleRequest(req, res);
|
|
103
|
+
});
|
|
104
|
+
app.delete("/mcp", async (req, res) => {
|
|
105
|
+
const transport = sessionTransport(req, res);
|
|
106
|
+
if (transport)
|
|
107
|
+
await transport.handleRequest(req, res);
|
|
108
|
+
});
|
|
109
|
+
app.get("/", (_req, res) => {
|
|
110
|
+
res.json({ status: "ok" });
|
|
111
|
+
});
|
|
112
|
+
app.get("/health", (_req, res) => {
|
|
113
|
+
res.json({ status: "ok" });
|
|
114
|
+
});
|
|
115
|
+
return {
|
|
116
|
+
app,
|
|
117
|
+
async closeAll() {
|
|
118
|
+
for (const sid of Object.keys(transports)) {
|
|
119
|
+
await transports[sid].close().catch(() => { });
|
|
120
|
+
delete transports[sid];
|
|
121
|
+
delete sessions[sid];
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
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 { learnPlan } from "./client/apiClient.js";
|
|
8
|
+
import { runTool } from "./client/relay.js";
|
|
9
|
+
import { clientLabel } from "./utils/clientInfo.js";
|
|
10
|
+
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";
|
|
11
|
+
export const OAUTH_HIDDEN_TOOLS = new Set(["login", "logout"]);
|
|
12
|
+
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.";
|
|
13
|
+
export const ISSUES_WRITE_TOOLS = new Set([
|
|
14
|
+
"dismiss_vulnerability",
|
|
15
|
+
"reopen_vulnerability",
|
|
16
|
+
"mark_vulnerability_fixed",
|
|
17
|
+
]);
|
|
18
|
+
export const ISSUES_WRITE_MISSING_TEXT = 'Reconnect Perfai in your AI tool and allow "Mark issues fixed or dismissed".';
|
|
19
|
+
function oauthRefusal(auth, name) {
|
|
20
|
+
if (auth.getAuthMethod() !== "mcp_oauth")
|
|
21
|
+
return undefined;
|
|
22
|
+
if (OAUTH_HIDDEN_TOOLS.has(name)) {
|
|
23
|
+
return { content: [{ type: "text", text: OAUTH_SIGNED_IN_TEXT }] };
|
|
24
|
+
}
|
|
25
|
+
if (ISSUES_WRITE_TOOLS.has(name) && !auth.hasScope("issues:write")) {
|
|
26
|
+
return { isError: true, content: [{ type: "text", text: ISSUES_WRITE_MISSING_TEXT }] };
|
|
27
|
+
}
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
export function createMcpServer(auth) {
|
|
31
|
+
const server = new Server(SERVER_INFO, {
|
|
32
|
+
capabilities: { tools: {}, prompts: {} },
|
|
33
|
+
instructions: SERVER_INSTRUCTIONS,
|
|
34
|
+
});
|
|
35
|
+
server.oninitialized = () => {
|
|
36
|
+
console.error(`Client connected: ${clientLabel(server.getClientVersion())}`);
|
|
37
|
+
};
|
|
38
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
39
|
+
const tools = [...Object.values(PUBLIC_TOOLS), ...Object.values(PROTECTED_TOOLS)];
|
|
40
|
+
return {
|
|
41
|
+
tools: auth.getAuthMethod() === "mcp_oauth" ? tools.filter((tool) => !OAUTH_HIDDEN_TOOLS.has(tool.name)) : tools,
|
|
42
|
+
};
|
|
43
|
+
});
|
|
44
|
+
server.setRequestHandler(ListPromptsRequestSchema, async () => ({ prompts: PROMPTS }));
|
|
45
|
+
server.setRequestHandler(GetPromptRequestSchema, async (request) => {
|
|
46
|
+
const { name, arguments: args } = request.params;
|
|
47
|
+
try {
|
|
48
|
+
const prompt = getPrompt(name, args);
|
|
49
|
+
if (!prompt)
|
|
50
|
+
throw new McpError(ErrorCode.InvalidParams, `Unknown prompt: ${name}`);
|
|
51
|
+
return prompt;
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
if (error instanceof McpError)
|
|
55
|
+
throw error;
|
|
56
|
+
throw new McpError(ErrorCode.InvalidParams, error instanceof Error ? error.message : String(error));
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
60
|
+
const { name, arguments: args } = request.params;
|
|
61
|
+
console.error(`→ Tool call: ${name} (client: ${clientLabel(server.getClientVersion())})`);
|
|
62
|
+
try {
|
|
63
|
+
const refusal = oauthRefusal(auth, name);
|
|
64
|
+
return await runTool(async () => refusal ?? (await callTool(auth, name, args)), () => auth.getPlan() === "free", async () => { if (!refusal)
|
|
65
|
+
await learnPlan(auth); });
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (error instanceof McpError)
|
|
69
|
+
throw error;
|
|
70
|
+
console.error(`Tool '${name}' failed:`, loggable(error));
|
|
71
|
+
throw new McpError(ErrorCode.InternalError, `Tool '${name}' failed — see server logs`);
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
server.onerror = (error) => {
|
|
75
|
+
console.error("[MCP Error]", error);
|
|
76
|
+
};
|
|
77
|
+
return server;
|
|
78
|
+
}
|
|
79
|
+
async function callTool(auth, name, args) {
|
|
80
|
+
switch (name) {
|
|
81
|
+
case "login":
|
|
82
|
+
return await handleLogin(auth, args);
|
|
83
|
+
case "auth_status":
|
|
84
|
+
return await handleAuthStatus(auth);
|
|
85
|
+
}
|
|
86
|
+
if (!auth.isAuthenticated() && !auth.hasCredentials()) {
|
|
87
|
+
if (process.env.MCP_TRANSPORT?.toLowerCase() === "http") {
|
|
88
|
+
throw new McpError(ErrorCode.InvalidRequest, `Authentication required. Run the 'login' tool first to access '${name}'.`);
|
|
89
|
+
}
|
|
90
|
+
if (!(await ensureLoggedIn(auth))) {
|
|
91
|
+
return { content: [{ type: "text", text: LOGIN_PENDING_TEXT }] };
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
switch (name) {
|
|
95
|
+
case "logout":
|
|
96
|
+
return await handleLogout(auth);
|
|
97
|
+
case "manage_organizations":
|
|
98
|
+
return await handleManageOrganizations(auth, args);
|
|
99
|
+
case "register_app":
|
|
100
|
+
return await handleRegisterApp(auth, args);
|
|
101
|
+
case "check_app_status":
|
|
102
|
+
return await handleCheckAppStatus(auth, args);
|
|
103
|
+
case "list_apps":
|
|
104
|
+
return await handleListApps(auth, args);
|
|
105
|
+
case "select_app":
|
|
106
|
+
return await handleSelectApp(auth, args);
|
|
107
|
+
case "submit_app_credentials":
|
|
108
|
+
return await handleSubmitAppCredentials(auth, args);
|
|
109
|
+
case "run_security_test":
|
|
110
|
+
return await handleRunSecurityTest(auth, args);
|
|
111
|
+
case "check_task_status":
|
|
112
|
+
return await handleCheckTaskStatus(auth, args);
|
|
113
|
+
case "get_vulnerabilities":
|
|
114
|
+
return await handleGetVulnerabilities(auth, args);
|
|
115
|
+
case "suggest_fix":
|
|
116
|
+
return await handleSuggestFix(auth, args);
|
|
117
|
+
case "auto_fix":
|
|
118
|
+
return await handleAutoFix(auth, args);
|
|
119
|
+
case "auto_fix_all":
|
|
120
|
+
return await handleAutoFixAll(auth, args);
|
|
121
|
+
case "get_fix_summary":
|
|
122
|
+
return await handleGetFixSummary(auth, args);
|
|
123
|
+
case "dismiss_vulnerability":
|
|
124
|
+
return await handleDismissVulnerability(auth, args);
|
|
125
|
+
case "reopen_vulnerability":
|
|
126
|
+
return await handleReopenVulnerability(auth, args);
|
|
127
|
+
case "mark_vulnerability_fixed":
|
|
128
|
+
return await handleMarkVulnerabilityFixed(auth, args);
|
|
129
|
+
default:
|
|
130
|
+
throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
|
|
131
|
+
}
|
|
132
|
+
}
|
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 {
|
|
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 {
|
|
15
|
-
import {
|
|
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 {
|
|
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
|
-
|
|
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
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
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
|
-
|
|
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, groupFindings, 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 " +
|
|
@@ -31,25 +32,25 @@ export async function handleAutoFix(auth, args) {
|
|
|
31
32
|
};
|
|
32
33
|
}
|
|
33
34
|
let appLabel;
|
|
34
|
-
let
|
|
35
|
+
let group;
|
|
35
36
|
try {
|
|
36
37
|
const resolved = await resolveApp(auth, args);
|
|
37
38
|
if (!resolved.ok)
|
|
38
39
|
return { content: [{ type: "text", text: resolved.message }] };
|
|
39
40
|
const { appId } = resolved.app;
|
|
40
41
|
appLabel = resolved.app.label;
|
|
41
|
-
|
|
42
|
-
if (!
|
|
43
|
-
auth.
|
|
44
|
-
|
|
42
|
+
group = auth.getCachedGroup(appId, String(args.vulnerability_id));
|
|
43
|
+
if (!group?.length) {
|
|
44
|
+
auth.cacheVulnerabilityGroups(appId, groupFindings((await getAllVulnerabilities(auth, appId)).filter((v) => !isLocked(v))));
|
|
45
|
+
group = auth.getCachedGroup(appId, String(args.vulnerability_id));
|
|
45
46
|
}
|
|
46
47
|
}
|
|
47
48
|
catch (error) {
|
|
48
49
|
return {
|
|
49
|
-
content: [{ type: "text", text:
|
|
50
|
+
content: [{ type: "text", text: findingsFailureText(error) }],
|
|
50
51
|
};
|
|
51
52
|
}
|
|
52
|
-
if (!
|
|
53
|
+
if (!group?.length) {
|
|
53
54
|
return {
|
|
54
55
|
content: [
|
|
55
56
|
{
|
|
@@ -60,9 +61,11 @@ export async function handleAutoFix(auth, args) {
|
|
|
60
61
|
],
|
|
61
62
|
};
|
|
62
63
|
}
|
|
64
|
+
const open = group.filter((v) => !v.isFixed && !v.fixClaimed && !v.isDismissed);
|
|
65
|
+
const vuln = open[0] ?? group[0];
|
|
63
66
|
if (vuln.isFixed || vuln.fixClaimed) {
|
|
64
67
|
return {
|
|
65
|
-
content: [{ type: "text", text: `✅ Vulnerability #${args.vulnerability_id} is already ${vuln.isFixed ? "fixed" : "claimed fixed (pending
|
|
68
|
+
content: [{ type: "text", text: `✅ Vulnerability #${args.vulnerability_id} is already ${vuln.isFixed ? "fixed" : "claimed fixed (pending the next security test)"}.` }],
|
|
66
69
|
};
|
|
67
70
|
}
|
|
68
71
|
if (vuln.isDismissed) {
|
|
@@ -73,6 +76,6 @@ export async function handleAutoFix(auth, args) {
|
|
|
73
76
|
const seq = Number(args.vulnerability_id);
|
|
74
77
|
const sequence = Number.isInteger(seq) && seq > 0 ? seq : 1;
|
|
75
78
|
return {
|
|
76
|
-
content: [{ type: "text", text: buildAutoFixInstruction(appLabel,
|
|
79
|
+
content: [{ type: "text", text: open.map((v, i) => buildAutoFixInstruction(appLabel, v, sequence, i === 0)).join("\n---\n\n") }],
|
|
77
80
|
};
|
|
78
81
|
}
|
|
@@ -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\" " +
|
|
@@ -12,7 +13,7 @@ export const autoFixAllTool = {
|
|
|
12
13
|
"(the N most severe). Returns a prioritized plan (critical → low) that you execute autonomously, " +
|
|
13
14
|
"by editing code only (no shell or network commands): " +
|
|
14
15
|
"fix each finding and call mark_vulnerability_fixed, or — if it does not apply to the code — " +
|
|
15
|
-
"silently call dismiss_vulnerability
|
|
16
|
+
"silently call dismiss_vulnerability (false_positive / other, comment \"AI agent: <specific reason>\").",
|
|
16
17
|
inputSchema: {
|
|
17
18
|
type: "object",
|
|
18
19
|
properties: {
|
|
@@ -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
|
-
|
|
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 =
|
|
55
|
-
?
|
|
56
|
-
:
|
|
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:
|
|
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:
|
|
114
|
+
text: findingsFailureText(error),
|
|
115
115
|
},
|
|
116
116
|
],
|
|
117
117
|
};
|