@codacy/codacy-mcp 0.6.23 → 0.6.24
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/dist/index.js +7 -3
- package/dist/src/cli/CodacyCli.js +265 -68
- package/dist/src/cli/index.js +9 -41
- package/dist/src/cli/utils.js +31 -0
- package/dist/src/handlers/cliAnalyze.js +3 -15
- package/dist/src/handlers/cliInstall.js +1 -1
- package/package.json +6 -3
- package/dist/src/cli/LinuxCodacyCli.js +0 -3
- package/dist/src/cli/MacCodacyCli.js +0 -123
- package/dist/src/cli/WinCodacyCli.js +0 -22
- package/dist/src/cli/WinWSLCodacyCli.js +0 -45
- package/dist/src/proxy.js +0 -74
package/dist/index.js
CHANGED
|
@@ -5,9 +5,13 @@ import { OpenAPI } from './src/api/client/index.js';
|
|
|
5
5
|
import * as Tools from './src/tools/index.js';
|
|
6
6
|
import * as Handlers from './src/handlers/index.js';
|
|
7
7
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
8
|
-
import {
|
|
9
|
-
//
|
|
10
|
-
|
|
8
|
+
import { configureProxy } from '@codacy/analysis-runner';
|
|
9
|
+
// Route the server's own outbound fetch — Codacy API calls and, through the
|
|
10
|
+
// runner, tool/runtime downloads — via the standard proxy environment variables
|
|
11
|
+
// (HTTP(S)_PROXY, NO_PROXY, SSL_CERT_FILE / NODE_EXTRA_CA_CERTS, CODACY_CLI_INSECURE).
|
|
12
|
+
// `configureProxy` installs undici's global dispatcher, which Node's native fetch
|
|
13
|
+
// does not otherwise read proxy vars from. Must run before any request is made.
|
|
14
|
+
configureProxy();
|
|
11
15
|
// Check for API key
|
|
12
16
|
const CODACY_ACCOUNT_TOKEN = process.env.CODACY_ACCOUNT_TOKEN;
|
|
13
17
|
OpenAPI.BASE = 'https://app.codacy.com/api/v3';
|
|
@@ -1,12 +1,39 @@
|
|
|
1
|
-
|
|
2
|
-
import { exec } from 'child_process';
|
|
1
|
+
import * as fs from 'fs';
|
|
3
2
|
import * as path from 'path';
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
import { analyze as runnerAnalyze, formatOutput, getRegisteredAdapters, getRegisteredDescriptors, initAutoConfig, initRemoteConfig, configureApiToken, writeCodacyConfig, readCodacyConfig, readBaselineConfig, writeBaselineConfig, updateConfigIncremental, mergeConfigs, createLogger, } from '@codacy/analysis-runner';
|
|
4
|
+
import { registerBuiltinAdapters, loadUnsupportedPatterns } from '@codacy/analysis-adapters';
|
|
5
|
+
import { processSarifResults } from './utils.js';
|
|
6
|
+
export const CODACY_FOLDER_NAME = '.codacy';
|
|
7
|
+
export const CODACY_CONFIG_FILE = 'codacy.config.json';
|
|
8
|
+
/**
|
|
9
|
+
* Strips the account token from an error message so it never leaks into a tool
|
|
10
|
+
* response, and always returns a printable string.
|
|
11
|
+
*/
|
|
12
|
+
const extractErrorMessage = (error) => {
|
|
13
|
+
if (typeof error === 'string')
|
|
14
|
+
return error;
|
|
15
|
+
if (error instanceof Error)
|
|
16
|
+
return error.message;
|
|
17
|
+
return String(error ?? '');
|
|
18
|
+
};
|
|
19
|
+
const cleanErrorMessage = (error, token) => {
|
|
20
|
+
const message = extractErrorMessage(error) || 'Unknown error';
|
|
21
|
+
return token ? message.replaceAll(token, '***') : message;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Drives Codacy local analysis in-process via `@codacy/analysis-runner`.
|
|
25
|
+
*
|
|
26
|
+
* This replaces the previous approach of downloading a `cli.sh` shell script and
|
|
27
|
+
* shelling out to it. Because the runner is a Node library, a single class works
|
|
28
|
+
* on every platform (including Windows without WSL) — there are no longer any
|
|
29
|
+
* platform-specific subclasses.
|
|
30
|
+
*
|
|
31
|
+
* Because the analyzer ships with the server, "ready" no longer means "a script
|
|
32
|
+
* was downloaded" — it means the repository has been initialized with a
|
|
33
|
+
* `.codacy/codacy.config.json`. `isInitialized()` exposes that state.
|
|
34
|
+
*/
|
|
6
35
|
export class CodacyCli {
|
|
7
|
-
_cliCommand = '';
|
|
8
36
|
_accountToken = process.env.CODACY_ACCOUNT_TOKEN;
|
|
9
|
-
_cliVersion = process.env.CODACY_CLI_VERSION;
|
|
10
37
|
rootPath;
|
|
11
38
|
provider;
|
|
12
39
|
organization;
|
|
@@ -16,73 +43,243 @@ export class CodacyCli {
|
|
|
16
43
|
this.provider = provider;
|
|
17
44
|
this.organization = organization;
|
|
18
45
|
this.repository = repository;
|
|
46
|
+
// Populate the runner's tool adapter registry (idempotent).
|
|
47
|
+
registerBuiltinAdapters();
|
|
48
|
+
}
|
|
49
|
+
// --- readiness -------------------------------------------------------------
|
|
50
|
+
/** Whether the repository has been initialized (a Codacy config file exists). */
|
|
51
|
+
isInitialized() {
|
|
52
|
+
return this.configExists();
|
|
53
|
+
}
|
|
54
|
+
// --- helpers ---------------------------------------------------------------
|
|
55
|
+
configPath() {
|
|
56
|
+
return path.join(this.rootPath, CODACY_FOLDER_NAME, CODACY_CONFIG_FILE);
|
|
57
|
+
}
|
|
58
|
+
configExists() {
|
|
59
|
+
return fs.existsSync(this.configPath());
|
|
19
60
|
}
|
|
20
|
-
|
|
21
|
-
|
|
61
|
+
/** True when we have everything needed to pull configuration from Codacy Cloud. */
|
|
62
|
+
hasIdentification() {
|
|
63
|
+
return !!(this._accountToken && this.provider && this.organization && this.repository);
|
|
22
64
|
}
|
|
23
|
-
|
|
24
|
-
|
|
65
|
+
/**
|
|
66
|
+
* Runner logger that forwards human-readable messages to stderr. The MCP
|
|
67
|
+
* protocol owns stdout, so all diagnostics must go to stderr.
|
|
68
|
+
*/
|
|
69
|
+
createRunnerLogger() {
|
|
70
|
+
return createLogger({
|
|
71
|
+
fileEnabled: false,
|
|
72
|
+
onStderrMessage: text => console.error(text),
|
|
73
|
+
});
|
|
25
74
|
}
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
75
|
+
/** Builds a fresh CodacyConfig using remote (if identified) or local auto-detection. */
|
|
76
|
+
async buildConfig() {
|
|
77
|
+
const adapters = await getRegisteredAdapters();
|
|
78
|
+
if (this.hasIdentification()) {
|
|
79
|
+
configureApiToken(this._accountToken);
|
|
80
|
+
const { config } = await initRemoteConfig(this.rootPath, this.provider, this.organization, this.repository, adapters, this._accountToken);
|
|
81
|
+
return config;
|
|
30
82
|
}
|
|
31
|
-
|
|
32
|
-
//
|
|
33
|
-
//
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
if (
|
|
61
|
-
|
|
83
|
+
const descriptors = getRegisteredDescriptors();
|
|
84
|
+
// `loadUnsupportedPatterns` (from the adapters preset) gates stack-specific
|
|
85
|
+
// patterns during auto-detection. The intermediate optional args (filters,
|
|
86
|
+
// onDiscoveryComplete, rawFilterString) are left at their defaults.
|
|
87
|
+
const { config } = await initAutoConfig(this.rootPath, adapters, descriptors, undefined, undefined, undefined, loadUnsupportedPatterns);
|
|
88
|
+
return config;
|
|
89
|
+
}
|
|
90
|
+
// --- public lifecycle ------------------------------------------------------
|
|
91
|
+
async preflightCodacyCli(autoInstall) {
|
|
92
|
+
if (this.configExists()) {
|
|
93
|
+
await this.initialize();
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (autoInstall)
|
|
97
|
+
await this.setup();
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* "Set up local analysis": generates the repository config and downloads any
|
|
101
|
+
* tool dependencies.
|
|
102
|
+
*
|
|
103
|
+
* On a repository that is already initialized with a matching identification
|
|
104
|
+
* state, this performs an incremental config update instead — picking up newly
|
|
105
|
+
* detected languages/frameworks while preserving local edits (disabled patterns,
|
|
106
|
+
* tuned parameters, custom excludes). This matters because the MCP server and the
|
|
107
|
+
* VS Code extension share the same `.codacy/` config: a destructive regenerate
|
|
108
|
+
* here would clobber edits the user made through the extension.
|
|
109
|
+
*/
|
|
110
|
+
async setup() {
|
|
111
|
+
try {
|
|
112
|
+
if (this.configExists() && !(await this.needsRegeneration())) {
|
|
113
|
+
await this.updateConfig();
|
|
114
|
+
await this.installDependencies();
|
|
62
115
|
}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
}
|
|
80
|
-
if (stderr && !stdout) {
|
|
81
|
-
reject(new Error(stderr));
|
|
82
|
-
return;
|
|
83
|
-
}
|
|
84
|
-
resolve({ stdout, stderr });
|
|
116
|
+
else {
|
|
117
|
+
await this.initialize();
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
const cleanedErrorMessage = cleanErrorMessage(error, this._accountToken);
|
|
122
|
+
throw new Error(`Failed to set up Codacy local analysis: ${cleanedErrorMessage}`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
async installDependencies() {
|
|
126
|
+
try {
|
|
127
|
+
// "auto-install" downloads any missing runtimes/tools before analysis.
|
|
128
|
+
await runnerAnalyze({
|
|
129
|
+
repositoryRoot: this.rootPath,
|
|
130
|
+
mode: 'auto-install',
|
|
131
|
+
logger: this.createRunnerLogger(),
|
|
85
132
|
});
|
|
86
|
-
}
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
const cleanedErrorMessage = cleanErrorMessage(error, this._accountToken);
|
|
136
|
+
throw new Error(`Failed to install dependencies: ${cleanedErrorMessage}`);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Whether the config must be rebuilt from scratch: either it doesn't exist yet,
|
|
141
|
+
* or the repo's identification state no longer matches it (e.g. it was created
|
|
142
|
+
* remotely but we now lack a token, or vice versa). A mismatch is a reset — the
|
|
143
|
+
* previous config no longer applies, so local edits are intentionally discarded.
|
|
144
|
+
*/
|
|
145
|
+
async needsRegeneration() {
|
|
146
|
+
if (!this.configExists())
|
|
147
|
+
return true;
|
|
148
|
+
const config = await readCodacyConfig(this.rootPath).catch(() => null);
|
|
149
|
+
const isRemote = config?.metadata?.source === 'remote';
|
|
150
|
+
return isRemote !== this.hasIdentification();
|
|
151
|
+
}
|
|
152
|
+
async initialize() {
|
|
153
|
+
if (!(await this.needsRegeneration())) {
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
try {
|
|
157
|
+
await this.regenerateConfig();
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
const cleanedErrorMessage = cleanErrorMessage(error, this._accountToken);
|
|
161
|
+
throw new Error(`Failed to initialize CLI: ${cleanedErrorMessage}`);
|
|
162
|
+
}
|
|
163
|
+
// Fetch any missing runtimes/tools for the freshly generated config.
|
|
164
|
+
await this.installDependencies();
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Writes the live config plus its baseline snapshot.
|
|
168
|
+
*
|
|
169
|
+
* The baseline (`codacy.config.baseline.json`, committed alongside the config) is
|
|
170
|
+
* always the *exact generator output* — never the merged/edited result — so the
|
|
171
|
+
* next {@link updateConfig} can tell a user-disabled pattern apart from a
|
|
172
|
+
* default-off one. On a full regenerate `config === baseline`; on an incremental
|
|
173
|
+
* update `config` is the merge result while `baseline` is the fresh generation.
|
|
174
|
+
*/
|
|
175
|
+
async writeConfigAndBaseline(config, baseline) {
|
|
176
|
+
// writeCodacyConfig writes the live config to `.codacy/codacy.config.json` and
|
|
177
|
+
// ensures `.codacy/.gitignore` so generated tool configs stay untracked.
|
|
178
|
+
await writeCodacyConfig(this.rootPath, config);
|
|
179
|
+
// writeBaselineConfig persists the generator-output snapshot to
|
|
180
|
+
// `.codacy/codacy.config.baseline.json` (a committed sibling of the config) with
|
|
181
|
+
// no `.codacy/` side effects, so the next updateConfig() can diff against it.
|
|
182
|
+
await writeBaselineConfig(this.rootPath, baseline);
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Rebuilds the Codacy config from scratch, discarding any local edits (the reset
|
|
186
|
+
* path). Used for first-time init and when the identification state changes
|
|
187
|
+
* (remote↔local), where the previous config no longer applies.
|
|
188
|
+
*/
|
|
189
|
+
async regenerateConfig() {
|
|
190
|
+
const config = await this.buildConfig();
|
|
191
|
+
await this.writeConfigAndBaseline(config, config);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Incrementally updates the config, preserving local edits. Re-runs the original
|
|
195
|
+
* init mode to produce `next`, then three-way merges it into the current config
|
|
196
|
+
* against the committed baseline: newly-detected languages/frameworks add
|
|
197
|
+
* tools/patterns, stack elements that disappeared are removed, and user edits
|
|
198
|
+
* (disabled patterns, tuned parameters, custom excludes) survive.
|
|
199
|
+
*
|
|
200
|
+
* - Remote configs are authoritative: they are re-synced wholesale from Codacy
|
|
201
|
+
* Cloud, with no local-edit preservation.
|
|
202
|
+
* - When no baseline snapshot exists (a config predating baselines), we cannot
|
|
203
|
+
* distinguish user-disabled patterns from default-off ones, so we fall back to
|
|
204
|
+
* an additive merge (edits kept, stale tools not pruned) and warn.
|
|
205
|
+
*/
|
|
206
|
+
async updateConfig() {
|
|
207
|
+
const next = await this.buildConfig();
|
|
208
|
+
if (next.metadata?.source === 'remote') {
|
|
209
|
+
await this.writeConfigAndBaseline(next, next);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
const [base, current] = await Promise.all([
|
|
213
|
+
readBaselineConfig(this.rootPath).catch(() => null),
|
|
214
|
+
readCodacyConfig(this.rootPath).catch(() => null),
|
|
215
|
+
]);
|
|
216
|
+
let result;
|
|
217
|
+
if (base && current) {
|
|
218
|
+
result = updateConfigIncremental(base, current, next);
|
|
219
|
+
}
|
|
220
|
+
else if (current) {
|
|
221
|
+
// The MCP protocol owns stdout, so diagnostics go to stderr.
|
|
222
|
+
console.error('No Codacy config baseline snapshot found; performing an additive merge ' +
|
|
223
|
+
'(local edits are kept, but tools for a removed language/framework are not pruned).');
|
|
224
|
+
// dest = current so the user's edits win; preferDestParameters keeps their
|
|
225
|
+
// tuned parameters over freshly-generated defaults.
|
|
226
|
+
result = mergeConfigs(next, current, { preferDestParameters: true });
|
|
227
|
+
}
|
|
228
|
+
else {
|
|
229
|
+
result = next;
|
|
230
|
+
}
|
|
231
|
+
await this.writeConfigAndBaseline(result, next);
|
|
232
|
+
}
|
|
233
|
+
async analyze(options) {
|
|
234
|
+
await this.preflightCodacyCli(true);
|
|
235
|
+
if (!this.isInitialized()) {
|
|
236
|
+
throw new Error('Codacy is not initialized. Please install the Codacy CLI first.');
|
|
237
|
+
}
|
|
238
|
+
const { file, tool } = options;
|
|
239
|
+
try {
|
|
240
|
+
const result = await runnerAnalyze({
|
|
241
|
+
repositoryRoot: this.rootPath,
|
|
242
|
+
files: file ? [this.toRepoRelativePath(file)] : undefined,
|
|
243
|
+
tools: tool ? [tool] : undefined,
|
|
244
|
+
outputFormat: 'sarif',
|
|
245
|
+
logger: this.createRunnerLogger(),
|
|
246
|
+
});
|
|
247
|
+
const sarifResult = JSON.parse(formatOutput(result, 'sarif'));
|
|
248
|
+
return sarifResult && 'runs' in sarifResult ? processSarifResults(sarifResult.runs) : [];
|
|
249
|
+
}
|
|
250
|
+
catch (error) {
|
|
251
|
+
const cleanedErrorMessage = cleanErrorMessage(error, this._accountToken);
|
|
252
|
+
throw new Error(`Failed to analyze code: ${cleanedErrorMessage}`);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
// --- path safety -----------------------------------------------------------
|
|
256
|
+
/**
|
|
257
|
+
* Validates a file path for security concerns and returns it relative to the
|
|
258
|
+
* repository root (the shape the runner expects for `files`).
|
|
259
|
+
*
|
|
260
|
+
* Rejects null bytes, control characters, and path-traversal attempts that would
|
|
261
|
+
* resolve outside the workspace.
|
|
262
|
+
*/
|
|
263
|
+
toRepoRelativePath(filePath) {
|
|
264
|
+
// Reject null bytes and all other control characters (including newline, tab,
|
|
265
|
+
// carriage return) — always a security risk.
|
|
266
|
+
// eslint-disable-next-line no-control-regex -- Intentionally checking for control chars to reject them for security
|
|
267
|
+
if (/[\x00-\x1F\x7F]/.test(filePath)) {
|
|
268
|
+
throw new Error(`Unsafe file path rejected: ${filePath}`);
|
|
269
|
+
}
|
|
270
|
+
const resolved = path.resolve(this.rootPath, filePath);
|
|
271
|
+
const relative = path.relative(this.rootPath, resolved);
|
|
272
|
+
// An empty result means the path is the root itself. A `..` segment prefix means it
|
|
273
|
+
// escaped the workspace. An absolute result means a different Windows drive.
|
|
274
|
+
// Comparing resolved path strings with `startsWith` would instead let sibling
|
|
275
|
+
// directories sharing a prefix with the root through (e.g. `<root>-secrets`).
|
|
276
|
+
const escapesRoot = relative === '' ||
|
|
277
|
+
relative === '..' ||
|
|
278
|
+
relative.startsWith(`..${path.sep}`) ||
|
|
279
|
+
path.isAbsolute(relative);
|
|
280
|
+
if (escapesRoot) {
|
|
281
|
+
throw new Error(`Unsafe file path rejected: ${filePath}`);
|
|
282
|
+
}
|
|
283
|
+
return relative;
|
|
87
284
|
}
|
|
88
285
|
}
|
package/dist/src/cli/index.js
CHANGED
|
@@ -1,32 +1,12 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { LinuxCodacyCli } from './LinuxCodacyCli.js';
|
|
3
|
-
import { WinWSLCodacyCli } from './WinWSLCodacyCli.js';
|
|
4
|
-
import { WinCodacyCli } from './WinCodacyCli.js';
|
|
5
|
-
import { exec } from 'child_process';
|
|
6
|
-
async function execWindowsCmdAsync(command) {
|
|
7
|
-
return new Promise((resolve, reject) => {
|
|
8
|
-
exec(command, {
|
|
9
|
-
encoding: 'buffer',
|
|
10
|
-
}, (error, stdout, stderr) => {
|
|
11
|
-
if (error) {
|
|
12
|
-
reject(error);
|
|
13
|
-
return;
|
|
14
|
-
}
|
|
15
|
-
if (stderr && !stdout) {
|
|
16
|
-
reject(new Error(stderr.toString('utf16le')));
|
|
17
|
-
return;
|
|
18
|
-
}
|
|
19
|
-
resolve({ stdout: stdout.toString('utf16le'), stderr: stderr.toString('utf16le') });
|
|
20
|
-
});
|
|
21
|
-
});
|
|
22
|
-
}
|
|
1
|
+
import { CodacyCli } from './CodacyCli.js';
|
|
23
2
|
export class Cli {
|
|
24
3
|
static cliInstance = null;
|
|
25
4
|
static async get(options) {
|
|
26
5
|
if (!Cli.cliInstance) {
|
|
27
6
|
return await Cli.createInstance(options);
|
|
28
7
|
}
|
|
29
|
-
else if (options.
|
|
8
|
+
else if (options.rootPath !== Cli.cliInstance.rootPath ||
|
|
9
|
+
options.provider !== Cli.cliInstance.provider ||
|
|
30
10
|
options.organization !== Cli.cliInstance.organization ||
|
|
31
11
|
options.repository !== Cli.cliInstance.repository) {
|
|
32
12
|
// If the options have changed, create a new instance
|
|
@@ -40,24 +20,12 @@ export class Cli {
|
|
|
40
20
|
}
|
|
41
21
|
static async createInstance(options) {
|
|
42
22
|
const { rootPath, provider, organization, repository } = options;
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
Cli.cliInstance = new LinuxCodacyCli(rootPath, provider, organization, repository);
|
|
49
|
-
}
|
|
50
|
-
else if (platform === 'win32') {
|
|
51
|
-
// is WSL installed?
|
|
52
|
-
const { stdout } = await execWindowsCmdAsync('wsl --status');
|
|
53
|
-
const hasWSL = stdout.includes('Default Distribution');
|
|
54
|
-
Cli.cliInstance = hasWSL
|
|
55
|
-
? new WinWSLCodacyCli(rootPath, provider, organization, repository)
|
|
56
|
-
: new WinCodacyCli(rootPath, provider, organization, repository);
|
|
57
|
-
}
|
|
58
|
-
if (!Cli.cliInstance) {
|
|
59
|
-
throw new Error(`Unsupported platform: ${platform}`);
|
|
60
|
-
}
|
|
23
|
+
// A single implementation now works on every platform (the analyzer ships with
|
|
24
|
+
// the server as a Node library — no shell script, no WSL).
|
|
25
|
+
Cli.cliInstance = new CodacyCli(rootPath, provider, organization, repository);
|
|
26
|
+
// Detect existing config / initialize if present (without auto-installing).
|
|
27
|
+
await Cli.cliInstance.preflightCodacyCli(false);
|
|
61
28
|
return Cli.cliInstance;
|
|
62
29
|
}
|
|
63
30
|
}
|
|
31
|
+
export { processSarifResults } from './utils.js';
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export const processSarifResults = (runs) => {
|
|
2
|
+
return (runs.flatMap(run => {
|
|
3
|
+
const tool = run.tool.driver.name;
|
|
4
|
+
const rules = Object.fromEntries(run.tool.driver.rules?.map(rule => [rule.id, rule]) || []);
|
|
5
|
+
return (run.results?.flatMap(result => {
|
|
6
|
+
const rule = result.ruleId ? rules[result.ruleId] : null;
|
|
7
|
+
const level = result.level || 'error';
|
|
8
|
+
const message = result.message?.text || 'No message provided.';
|
|
9
|
+
return (result.locations?.map(location => {
|
|
10
|
+
const filePath = location.physicalLocation?.artifactLocation?.uri;
|
|
11
|
+
return {
|
|
12
|
+
tool,
|
|
13
|
+
rule: rule
|
|
14
|
+
? {
|
|
15
|
+
id: rule.id,
|
|
16
|
+
name: rule.name,
|
|
17
|
+
helpUri: rule.helpUri,
|
|
18
|
+
shortDescription: rule.shortDescription?.text,
|
|
19
|
+
}
|
|
20
|
+
: result.ruleId
|
|
21
|
+
? { id: result.ruleId }
|
|
22
|
+
: undefined,
|
|
23
|
+
level,
|
|
24
|
+
message,
|
|
25
|
+
filePath,
|
|
26
|
+
region: location.physicalLocation?.region,
|
|
27
|
+
};
|
|
28
|
+
}) || []);
|
|
29
|
+
}) || []);
|
|
30
|
+
}) || []);
|
|
31
|
+
};
|
|
@@ -3,24 +3,12 @@ export const cliAnalyzeHandler = async (args) => {
|
|
|
3
3
|
const cli = await Cli.get(args);
|
|
4
4
|
try {
|
|
5
5
|
const results = await cli.analyze({
|
|
6
|
-
file:
|
|
7
|
-
tool: args.tool,
|
|
8
|
-
});
|
|
9
|
-
// clean up the results to remove superfluous information
|
|
10
|
-
const cleanedResults = (results?.runs ?? []).map(run => {
|
|
11
|
-
return {
|
|
12
|
-
tool: run.tool.driver,
|
|
13
|
-
results: (run.results ?? []).map(r => ({
|
|
14
|
-
level: r.level,
|
|
15
|
-
message: r.message.text,
|
|
16
|
-
locations: r.locations,
|
|
17
|
-
ruleId: r.ruleId,
|
|
18
|
-
})),
|
|
19
|
-
};
|
|
6
|
+
file: args.file || undefined,
|
|
7
|
+
tool: args.tool || undefined,
|
|
20
8
|
});
|
|
21
9
|
return {
|
|
22
10
|
success: true,
|
|
23
|
-
result:
|
|
11
|
+
result: results ?? [],
|
|
24
12
|
};
|
|
25
13
|
}
|
|
26
14
|
catch (error) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codacy/codacy-mcp",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.24",
|
|
4
4
|
"mcpName": "io.github.codacy/codacy-mcp-server",
|
|
5
5
|
"description": "Codacy MCP server",
|
|
6
6
|
"license": "MIT",
|
|
@@ -29,13 +29,16 @@
|
|
|
29
29
|
"lint:fix": "eslint . --ext .ts --fix",
|
|
30
30
|
"format": "prettier --write \"**/*.{ts,json,md}\"",
|
|
31
31
|
"format:check": "prettier --check \"**/*.{ts,json,md}\"",
|
|
32
|
-
"inspect": "npm run build && npx @modelcontextprotocol/inspector -e CODACY_ACCOUNT_TOKEN=$CODACY_ACCOUNT_TOKEN node dist/index.js"
|
|
32
|
+
"inspect": "npm run build && npx @modelcontextprotocol/inspector -e CODACY_ACCOUNT_TOKEN=$CODACY_ACCOUNT_TOKEN node dist/index.js",
|
|
33
|
+
"inspect-with-proxy": "export CODACY_ACCOUNT_TOKEN=$CODACY_ACCOUNT_TOKEN; export HTTP_PROXY=$HTTP_PROXY; export NODE_EXTRA_CA_CERTS=$NODE_EXTRA_CA_CERTS; npm run build && npx @modelcontextprotocol/inspector node dist/index.js"
|
|
33
34
|
},
|
|
34
35
|
"dependencies": {
|
|
36
|
+
"@codacy/analysis-adapters": "^0.16.0",
|
|
37
|
+
"@codacy/analysis-runner": "^0.16.0",
|
|
38
|
+
"@codacy/tooling": "^0.16.0",
|
|
35
39
|
"@modelcontextprotocol/sdk": "1.29.0",
|
|
36
40
|
"@types/node": "^22",
|
|
37
41
|
"@types/sarif": "2.1.7",
|
|
38
|
-
"undici": "^6.0.0",
|
|
39
42
|
"universal-user-agent": "^7.0.2"
|
|
40
43
|
},
|
|
41
44
|
"devDependencies": {
|
|
@@ -1,123 +0,0 @@
|
|
|
1
|
-
import fs from 'fs';
|
|
2
|
-
import path from 'path';
|
|
3
|
-
import { CODACY_FOLDER_NAME, CodacyCli } from './CodacyCli.js';
|
|
4
|
-
export class MacCodacyCli extends CodacyCli {
|
|
5
|
-
constructor(rootPath, provider, organization, repository) {
|
|
6
|
-
super(rootPath, provider, organization, repository);
|
|
7
|
-
}
|
|
8
|
-
async findCliCommand() {
|
|
9
|
-
this.setCliCommand('');
|
|
10
|
-
// check if .codacy/cli.sh exists
|
|
11
|
-
const localPath = path.join(CODACY_FOLDER_NAME, 'cli.sh');
|
|
12
|
-
const fullPath = path.join(this.rootPath, localPath);
|
|
13
|
-
if (fs.existsSync(fullPath)) {
|
|
14
|
-
this.setCliCommand(this._cliVersion ? `CODACY_CLI_V2_VERSION=${this._cliVersion} ${localPath}` : localPath);
|
|
15
|
-
return;
|
|
16
|
-
}
|
|
17
|
-
// CLI not found, throw error
|
|
18
|
-
throw new Error(`Codacy CLI not found. Please install it first.`);
|
|
19
|
-
}
|
|
20
|
-
async preflightCodacyCli() {
|
|
21
|
-
// is there a command?
|
|
22
|
-
if (!this.getCliCommand()) {
|
|
23
|
-
await this.findCliCommand();
|
|
24
|
-
}
|
|
25
|
-
else {
|
|
26
|
-
await this.initialize();
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
async install() {
|
|
30
|
-
try {
|
|
31
|
-
const codacyFolder = path.join(this.rootPath, CODACY_FOLDER_NAME);
|
|
32
|
-
if (!fs.existsSync(codacyFolder)) {
|
|
33
|
-
fs.mkdirSync(codacyFolder, { recursive: true });
|
|
34
|
-
}
|
|
35
|
-
// Download cli.sh if it doesn't exist
|
|
36
|
-
const codacyCliPath = path.join(CODACY_FOLDER_NAME, 'cli.sh');
|
|
37
|
-
if (!fs.existsSync(codacyCliPath)) {
|
|
38
|
-
const execPath = this.preparePathForExec(codacyCliPath);
|
|
39
|
-
await this.execAsync(`curl -Ls -o "${execPath}" https://raw.githubusercontent.com/codacy/codacy-cli-v2/main/codacy-cli.sh`);
|
|
40
|
-
await this.execAsync(`chmod +x "${execPath}"`);
|
|
41
|
-
this.setCliCommand(this._cliVersion
|
|
42
|
-
? `CODACY_CLI_V2_VERSION=${this._cliVersion} ${codacyCliPath}`
|
|
43
|
-
: codacyCliPath);
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
catch (error) {
|
|
47
|
-
throw new Error(`Failed to install CLI: ${error}`);
|
|
48
|
-
}
|
|
49
|
-
// Initialize codacy-cli after installation
|
|
50
|
-
await this.initialize();
|
|
51
|
-
}
|
|
52
|
-
async installDependencies() {
|
|
53
|
-
const command = `${this.getCliCommand()} install`;
|
|
54
|
-
try {
|
|
55
|
-
await this.execAsync(command);
|
|
56
|
-
}
|
|
57
|
-
catch (error) {
|
|
58
|
-
throw new Error(`Failed to install dependencies: ${error}`);
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
async update() {
|
|
62
|
-
const command = `${this.getCliCommand()} update`;
|
|
63
|
-
try {
|
|
64
|
-
await this.execAsync(command);
|
|
65
|
-
}
|
|
66
|
-
catch (error) {
|
|
67
|
-
throw new Error(`Failed to update CLI: ${error}`);
|
|
68
|
-
}
|
|
69
|
-
this.installDependencies();
|
|
70
|
-
}
|
|
71
|
-
async initialize() {
|
|
72
|
-
// Check if the configuration files exist
|
|
73
|
-
const configFilePath = path.join(this.rootPath, CODACY_FOLDER_NAME, 'codacy.yaml');
|
|
74
|
-
const cliConfigFilePath = path.join(this.rootPath, CODACY_FOLDER_NAME, 'cli-config.yaml');
|
|
75
|
-
const toolsFolderPath = path.join(this.rootPath, CODACY_FOLDER_NAME, 'tools-configs');
|
|
76
|
-
const initFilesOk = fs.existsSync(configFilePath) &&
|
|
77
|
-
fs.existsSync(cliConfigFilePath) &&
|
|
78
|
-
fs.existsSync(toolsFolderPath);
|
|
79
|
-
let needsInitialization = !initFilesOk;
|
|
80
|
-
if (initFilesOk) {
|
|
81
|
-
// Check if the mode matches the current properties
|
|
82
|
-
const cliConfig = fs.readFileSync(path.join(this.rootPath, CODACY_FOLDER_NAME, 'cli-config.yaml'), 'utf-8');
|
|
83
|
-
if ((cliConfig === 'mode: local' && this.repository) ||
|
|
84
|
-
(cliConfig === 'mode: remote' && !this.repository)) {
|
|
85
|
-
needsInitialization = true;
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
if (needsInitialization) {
|
|
89
|
-
const initParams = (this._accountToken && this.repository && this.provider && this.organization
|
|
90
|
-
? {
|
|
91
|
-
provider: this.provider,
|
|
92
|
-
organization: this.organization,
|
|
93
|
-
repository: this.repository,
|
|
94
|
-
'api-token': this._accountToken,
|
|
95
|
-
}
|
|
96
|
-
: {});
|
|
97
|
-
try {
|
|
98
|
-
// initialize codacy-cli
|
|
99
|
-
await this.execAsync(`${this.getCliCommand()} init`, initParams);
|
|
100
|
-
}
|
|
101
|
-
catch (error) {
|
|
102
|
-
throw new Error(`Failed to initialize CLI: ${error}`);
|
|
103
|
-
}
|
|
104
|
-
// install dependencies
|
|
105
|
-
await this.installDependencies();
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
async analyze(options) {
|
|
109
|
-
await this.preflightCodacyCli();
|
|
110
|
-
if (!this.getCliCommand()) {
|
|
111
|
-
throw new Error('CLI command not found. Please install the CLI first.');
|
|
112
|
-
}
|
|
113
|
-
const { file, tool } = options;
|
|
114
|
-
try {
|
|
115
|
-
const { stdout } = await this.execAsync(`${this.getCliCommand()} analyze ${file ? this.preparePathForExec(file) : ''} --format sarif`, tool ? { tool: tool } : {});
|
|
116
|
-
const jsonMatch = /(\{[\s\S]*\}|\[[\s\S]*\])/.exec(stdout);
|
|
117
|
-
return jsonMatch ? JSON.parse(jsonMatch[0]) : null;
|
|
118
|
-
}
|
|
119
|
-
catch (error) {
|
|
120
|
-
throw new Error(`Failed to analyze code: ${error}`);
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
}
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import { CodacyCli } from './CodacyCli.js';
|
|
2
|
-
const NOT_SUPPORTED = 'CLI on Windows is not supported without WSL.';
|
|
3
|
-
export class WinCodacyCli extends CodacyCli {
|
|
4
|
-
constructor(rootPath, provider, organization, repository) {
|
|
5
|
-
super(rootPath, provider, organization, repository);
|
|
6
|
-
}
|
|
7
|
-
install() {
|
|
8
|
-
throw new Error(NOT_SUPPORTED);
|
|
9
|
-
}
|
|
10
|
-
installDependencies() {
|
|
11
|
-
throw new Error(NOT_SUPPORTED);
|
|
12
|
-
}
|
|
13
|
-
update() {
|
|
14
|
-
throw new Error(NOT_SUPPORTED);
|
|
15
|
-
}
|
|
16
|
-
initialize() {
|
|
17
|
-
throw new Error(NOT_SUPPORTED);
|
|
18
|
-
}
|
|
19
|
-
analyze(_options) {
|
|
20
|
-
throw new Error(NOT_SUPPORTED);
|
|
21
|
-
}
|
|
22
|
-
}
|
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import { MacCodacyCli } from './MacCodacyCli.js';
|
|
2
|
-
export class WinWSLCodacyCli extends MacCodacyCli {
|
|
3
|
-
constructor(rootPath, provider, organization, repository) {
|
|
4
|
-
const winRootPath = rootPath.startsWith('/mnt/')
|
|
5
|
-
? WinWSLCodacyCli.fromWSLPath(rootPath)
|
|
6
|
-
: rootPath;
|
|
7
|
-
super(winRootPath, provider, organization, repository);
|
|
8
|
-
}
|
|
9
|
-
static toWSLPath(path) {
|
|
10
|
-
// First, remove outer quotes if present
|
|
11
|
-
const cleanPath = path.replace(/^["']|["']$/g, '');
|
|
12
|
-
// Convert backslashes to slashes and handle drive letter
|
|
13
|
-
const wslPath = cleanPath
|
|
14
|
-
.replace(/\\/g, '/')
|
|
15
|
-
.replace(/^([a-zA-Z]):/, (match, letter) => `/mnt/${letter.toLowerCase()}`);
|
|
16
|
-
return wslPath;
|
|
17
|
-
}
|
|
18
|
-
static fromWSLPath(path) {
|
|
19
|
-
// Convert WSL path to Windows path
|
|
20
|
-
// Example: /mnt/c/Users/user/project -> C:\Users\user\project
|
|
21
|
-
const windowsPath = path
|
|
22
|
-
.replace(/^'\/mnt\/([a-zA-Z])/, (match, letter) => `'${letter.toUpperCase()}:`)
|
|
23
|
-
.replace(/^\/mnt\/([a-zA-Z])/, (match, letter) => `${letter.toUpperCase()}:`)
|
|
24
|
-
.replace(/\//g, '\\');
|
|
25
|
-
return windowsPath;
|
|
26
|
-
}
|
|
27
|
-
preparePathForExec(path) {
|
|
28
|
-
// Convert WSL path to Windows format for validation
|
|
29
|
-
const winFilePath = path.startsWith('/mnt/') ? WinWSLCodacyCli.fromWSLPath(path) : path;
|
|
30
|
-
// Validate path security before escaping
|
|
31
|
-
if (!this.isPathSafe(winFilePath)) {
|
|
32
|
-
throw new Error(`Unsafe file path rejected: ${winFilePath}`);
|
|
33
|
-
}
|
|
34
|
-
// Convert to WSL format and escape special characters
|
|
35
|
-
const wslPath = WinWSLCodacyCli.toWSLPath(winFilePath);
|
|
36
|
-
const escapedPath = wslPath.replace(/([\s'"\\;&|`$()[\]{}*?~<>])/g, '\\$1');
|
|
37
|
-
return `'${escapedPath}'`;
|
|
38
|
-
}
|
|
39
|
-
async execAsync(command, args) {
|
|
40
|
-
return await super.execAsync(`wsl bash -c "${command}"`, args);
|
|
41
|
-
}
|
|
42
|
-
getCliCommand() {
|
|
43
|
-
return WinWSLCodacyCli.toWSLPath(super.getCliCommand());
|
|
44
|
-
}
|
|
45
|
-
}
|
package/dist/src/proxy.js
DELETED
|
@@ -1,74 +0,0 @@
|
|
|
1
|
-
import { Agent, ProxyAgent, setGlobalDispatcher } from 'undici';
|
|
2
|
-
// Matches a request hostname against the NO_PROXY / no_proxy list.
|
|
3
|
-
// Handles exact matches and suffix matches (e.g. "example.com" also covers "sub.example.com").
|
|
4
|
-
function matchesNoProxy(hostname) {
|
|
5
|
-
const noProxy = process.env.NO_PROXY ?? process.env.no_proxy;
|
|
6
|
-
if (!noProxy)
|
|
7
|
-
return false;
|
|
8
|
-
const lower = hostname.toLowerCase();
|
|
9
|
-
return noProxy
|
|
10
|
-
.split(',')
|
|
11
|
-
.map(h => h.trim().toLowerCase().replace(/^\./, ''))
|
|
12
|
-
.filter(Boolean)
|
|
13
|
-
.some(entry => entry === '*' || lower === entry || lower.endsWith('.' + entry));
|
|
14
|
-
}
|
|
15
|
-
// Ensures a proxy URL has a protocol prefix. A bare host:port (e.g. "localhost:8080")
|
|
16
|
-
// is treated as HTTP, matching the convention used by curl and most proxy tools.
|
|
17
|
-
function normalizeProxyUrl(url) {
|
|
18
|
-
return /^https?:\/\//i.test(url) ? url : `http://${url}`;
|
|
19
|
-
}
|
|
20
|
-
// Routes each fetch() call through HTTPS_PROXY or HTTP_PROXY based on the request
|
|
21
|
-
// protocol, bypassing the proxy for any host that matches NO_PROXY.
|
|
22
|
-
// Extends Agent so all Dispatcher methods are already implemented.
|
|
23
|
-
class ProxyRoutingDispatcher extends Agent {
|
|
24
|
-
_httpsProxy;
|
|
25
|
-
_httpProxy;
|
|
26
|
-
constructor(httpProxy, httpsProxy, disableSSL) {
|
|
27
|
-
super();
|
|
28
|
-
// requestTls — TLS to the target server through the CONNECT tunnel.
|
|
29
|
-
// proxyTls — TLS to the proxy itself (relevant when proxy URL is HTTPS).
|
|
30
|
-
const tlsOpts = disableSSL ? { rejectUnauthorized: false } : undefined;
|
|
31
|
-
const proxyOpts = tlsOpts ? { requestTls: tlsOpts, proxyTls: tlsOpts } : {};
|
|
32
|
-
this._httpsProxy = httpsProxy
|
|
33
|
-
? new ProxyAgent({ uri: normalizeProxyUrl(httpsProxy), ...proxyOpts })
|
|
34
|
-
: undefined;
|
|
35
|
-
this._httpProxy = httpProxy
|
|
36
|
-
? new ProxyAgent({ uri: normalizeProxyUrl(httpProxy), ...proxyOpts })
|
|
37
|
-
: undefined;
|
|
38
|
-
}
|
|
39
|
-
dispatch(options, handler) {
|
|
40
|
-
const origin = options.origin instanceof URL ? options.origin : new URL(String(options.origin));
|
|
41
|
-
if (!matchesNoProxy(origin.hostname)) {
|
|
42
|
-
const proxy = origin.protocol === 'https:'
|
|
43
|
-
? (this._httpsProxy ?? this._httpProxy)
|
|
44
|
-
: (this._httpProxy ?? this._httpsProxy);
|
|
45
|
-
if (proxy)
|
|
46
|
-
return proxy.dispatch(options, handler);
|
|
47
|
-
}
|
|
48
|
-
return super.dispatch(options, handler);
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
/**
|
|
52
|
-
* Reads proxy configuration from environment variables and patches the global
|
|
53
|
-
* fetch dispatcher used by Node.js native fetch.
|
|
54
|
-
*
|
|
55
|
-
* Supported env vars:
|
|
56
|
-
* HTTPS_PROXY / https_proxy — proxy for HTTPS requests
|
|
57
|
-
* HTTP_PROXY / http_proxy — proxy for HTTP requests
|
|
58
|
-
* NO_PROXY / no_proxy — comma-separated list of hosts to bypass
|
|
59
|
-
* NODE_TLS_REJECT_UNAUTHORIZED=0 — disable TLS certificate verification
|
|
60
|
-
*
|
|
61
|
-
* For corporate environments that use SSL inspection (MITM proxies), prefer adding the
|
|
62
|
-
* corporate CA certificate to Node's trust store rather than disabling verification:
|
|
63
|
-
* NODE_EXTRA_CA_CERTS=/path/to/corporate-ca.pem
|
|
64
|
-
* Node reads this at startup and it applies to all TLS connections, including
|
|
65
|
-
* the inner tunnel established through a CONNECT proxy.
|
|
66
|
-
*/
|
|
67
|
-
export function applyProxyConfig() {
|
|
68
|
-
const httpsProxy = process.env.HTTPS_PROXY ?? process.env.https_proxy;
|
|
69
|
-
const httpProxy = process.env.HTTP_PROXY ?? process.env.http_proxy;
|
|
70
|
-
if (!httpsProxy && !httpProxy)
|
|
71
|
-
return;
|
|
72
|
-
const disableSSL = process.env.NODE_TLS_REJECT_UNAUTHORIZED === '0';
|
|
73
|
-
setGlobalDispatcher(new ProxyRoutingDispatcher(httpProxy, httpsProxy, disableSSL));
|
|
74
|
-
}
|