@codacy/codacy-mcp 0.6.4 → 0.6.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,54 @@
1
+ export const CODACY_FOLDER_NAME = '.codacy';
2
+ import { exec } from 'child_process';
3
+ // Set a larger buffer size (10MB)
4
+ const MAX_BUFFER_SIZE = 1024 * 1024 * 10;
5
+ export class CodacyCli {
6
+ _cliCommand = '';
7
+ _accountToken = process.env.CODACY_ACCOUNT_TOKEN;
8
+ _cliVersion = process.env.CODACY_CLI_VERSION;
9
+ rootPath;
10
+ provider;
11
+ organization;
12
+ repository;
13
+ constructor(rootPath, provider, organization, repository) {
14
+ this.rootPath = rootPath;
15
+ this.provider = provider;
16
+ this.organization = organization;
17
+ this.repository = repository;
18
+ }
19
+ getCliCommand() {
20
+ return this._cliCommand;
21
+ }
22
+ setCliCommand(command) {
23
+ this._cliCommand = command;
24
+ }
25
+ preparePathForExec(path) {
26
+ return path;
27
+ }
28
+ execAsync(command, args) {
29
+ // stringyfy the args
30
+ const argsString = Object.entries(args || {})
31
+ .map(([key, value]) => `--${key} ${value}`)
32
+ .join(' ');
33
+ // Add the args to the command and remove any shell metacharacters
34
+ const cmd = `${command} ${argsString}`.trim().replace(/[;&|`$]/g, '');
35
+ // Add the CODACY_CLI_VERSION to the command
36
+ return new Promise((resolve, reject) => {
37
+ exec(cmd, {
38
+ cwd: this.rootPath,
39
+ maxBuffer: MAX_BUFFER_SIZE, // To solve: stdout maxBuffer exceeded
40
+ encoding: 'utf-8',
41
+ }, (error, stdout, stderr) => {
42
+ if (error) {
43
+ reject(error);
44
+ return;
45
+ }
46
+ if (stderr && !stdout) {
47
+ reject(new Error(stderr));
48
+ return;
49
+ }
50
+ resolve({ stdout, stderr });
51
+ });
52
+ });
53
+ }
54
+ }
@@ -0,0 +1,3 @@
1
+ import { MacCodacyCli } from './MacCodacyCli.js';
2
+ export class LinuxCodacyCli extends MacCodacyCli {
3
+ }
@@ -0,0 +1,132 @@
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_VERSION=${this._cliVersion} ${localPath}` : localPath);
15
+ return;
16
+ }
17
+ // check if codacy-cli is installed globally
18
+ try {
19
+ // first set the command for the getCliCommand to do the right thing when called
20
+ this.setCliCommand(this._cliVersion ? `CODACY_CLI_VERSION=${this._cliVersion} codacy-cli` : 'codacy-cli');
21
+ await this.execAsync(`${this.getCliCommand()} --help`);
22
+ return;
23
+ }
24
+ catch {
25
+ // CLI not found, clear it, and attempt to install it
26
+ this.setCliCommand('');
27
+ await this.install();
28
+ return undefined;
29
+ }
30
+ }
31
+ async preflightCodacyCli() {
32
+ // is there a command?
33
+ if (!this.getCliCommand()) {
34
+ await this.findCliCommand();
35
+ }
36
+ else {
37
+ await this.initialize();
38
+ }
39
+ }
40
+ async install() {
41
+ try {
42
+ const codacyFolder = path.join(this.rootPath, CODACY_FOLDER_NAME);
43
+ if (!fs.existsSync(codacyFolder)) {
44
+ fs.mkdirSync(codacyFolder, { recursive: true });
45
+ }
46
+ // Download cli.sh if it doesn't exist
47
+ const codacyCliPath = path.join(CODACY_FOLDER_NAME, 'cli.sh');
48
+ if (!fs.existsSync(codacyCliPath)) {
49
+ const execPath = this.preparePathForExec(codacyCliPath);
50
+ await this.execAsync(`curl -Ls -o "${execPath}" https://raw.githubusercontent.com/codacy/codacy-cli-v2/main/codacy-cli.sh`);
51
+ await this.execAsync(`chmod +x "${execPath}"`);
52
+ this.setCliCommand(this._cliVersion
53
+ ? `CODACY_CLI_VERSION=${this._cliVersion} ${codacyCliPath}`
54
+ : codacyCliPath);
55
+ }
56
+ }
57
+ catch (error) {
58
+ throw new Error(`Failed to install CLI: ${error}`);
59
+ }
60
+ // Initialize codacy-cli after installation
61
+ await this.initialize();
62
+ }
63
+ async installDependencies() {
64
+ const command = `${this.getCliCommand()} install`;
65
+ try {
66
+ await this.execAsync(command);
67
+ }
68
+ catch (error) {
69
+ throw new Error(`Failed to install dependencies: ${error}`);
70
+ }
71
+ }
72
+ async update() {
73
+ const command = `${this.getCliCommand()} update`;
74
+ try {
75
+ await this.execAsync(command);
76
+ }
77
+ catch (error) {
78
+ throw new Error(`Failed to update CLI: ${error}`);
79
+ }
80
+ this.installDependencies();
81
+ }
82
+ async initialize() {
83
+ // Check if the configuration files exist
84
+ const configFilePath = path.join(this.rootPath, CODACY_FOLDER_NAME, 'codacy.yaml');
85
+ const toolsFolderPath = path.join(this.rootPath, CODACY_FOLDER_NAME, 'tools-configs');
86
+ let needsInitialization = !fs.existsSync(configFilePath) || !fs.existsSync(toolsFolderPath);
87
+ if (!needsInitialization) {
88
+ // Check if the mode matches the current properties
89
+ const cliConfig = fs.readFileSync(path.join(this.rootPath, CODACY_FOLDER_NAME, 'cli-config.yaml'), 'utf-8');
90
+ if ((cliConfig === 'mode: local' && this.repository) ||
91
+ (cliConfig === 'mode: remote' && !this.repository)) {
92
+ needsInitialization = true;
93
+ }
94
+ }
95
+ if (needsInitialization) {
96
+ const apiToken = this._accountToken
97
+ ? { 'api-token': this._accountToken }
98
+ : {};
99
+ const repositoryAccess = this.repository && this.provider && this.organization
100
+ ? {
101
+ provider: this.provider,
102
+ organization: this.organization,
103
+ repository: this.repository,
104
+ }
105
+ : {};
106
+ try {
107
+ // initialize codacy-cli
108
+ await this.execAsync(`${this.getCliCommand()} init`, { ...apiToken, ...repositoryAccess });
109
+ }
110
+ catch (error) {
111
+ throw new Error(`Failed to initialize CLI: ${error}`);
112
+ }
113
+ // install dependencies
114
+ await this.installDependencies();
115
+ }
116
+ }
117
+ async analyze(options) {
118
+ await this.preflightCodacyCli();
119
+ if (!this.getCliCommand()) {
120
+ throw new Error('CLI command not found. Please install the CLI first.');
121
+ }
122
+ const { file, tool } = options;
123
+ try {
124
+ const { stdout } = await this.execAsync(`${this.getCliCommand()} analyze ${file ? this.preparePathForExec(file) : ''} --format sarif`, tool ? { tool: tool } : {});
125
+ const jsonMatch = /(\{[\s\S]*\}|\[[\s\S]*\])/.exec(stdout);
126
+ return jsonMatch ? JSON.parse(jsonMatch[0]) : null;
127
+ }
128
+ catch (error) {
129
+ throw new Error(`Failed to analyze code: ${error}`);
130
+ }
131
+ }
132
+ }
@@ -0,0 +1,22 @@
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
+ }
@@ -0,0 +1,31 @@
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
+ // Convert Windows path to WSL path
11
+ // Example: C:\Users\user\project -> /mnt/c/Users/user/project
12
+ const wslPath = path.replace(/\\/g, '/').replace(/^([a-zA-Z]):/, '/mnt/$1');
13
+ return wslPath;
14
+ }
15
+ static fromWSLPath(path) {
16
+ // Convert WSL path to Windows path
17
+ // Example: /mnt/c/Users/user/project -> C:\Users\user\project
18
+ const windowsPath = path.replace(/^\/mnt\/([a-zA-Z])/, '$1:').replace(/\//g, '\\');
19
+ return windowsPath;
20
+ }
21
+ preparePathForExec(path) {
22
+ // Convert the path to WSL format
23
+ return WinWSLCodacyCli.toWSLPath(path);
24
+ }
25
+ async execAsync(command, args) {
26
+ return await super.execAsync(`wsl ${command}`, args);
27
+ }
28
+ getCliCommand() {
29
+ return WinWSLCodacyCli.toWSLPath(super.getCliCommand());
30
+ }
31
+ }
@@ -0,0 +1,63 @@
1
+ import { MacCodacyCli } from './MacCodacyCli.js';
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
+ }
23
+ export class Cli {
24
+ static cliInstance = null;
25
+ static async get(options) {
26
+ if (!Cli.cliInstance) {
27
+ return await Cli.createInstance(options);
28
+ }
29
+ else if (options.provider !== Cli.cliInstance.provider ||
30
+ options.organization !== Cli.cliInstance.organization ||
31
+ options.repository !== Cli.cliInstance.repository) {
32
+ // If the options have changed, create a new instance
33
+ Cli.cliInstance = null;
34
+ return await Cli.createInstance(options);
35
+ }
36
+ else {
37
+ // If the options are the same, return the existing instance
38
+ return Cli.cliInstance;
39
+ }
40
+ }
41
+ static async createInstance(options) {
42
+ const { rootPath, provider, organization, repository } = options;
43
+ const platform = process.platform;
44
+ if (platform === 'darwin') {
45
+ Cli.cliInstance = new MacCodacyCli(rootPath, provider, organization, repository);
46
+ }
47
+ else if (platform === 'linux') {
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
+ }
61
+ return Cli.cliInstance;
62
+ }
63
+ }
@@ -1,127 +1,19 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import { exec } from 'child_process';
4
- const CODACY_ACCOUNT_TOKEN = process.env.CODACY_ACCOUNT_TOKEN;
5
- const CODACY_CLI_VERSION = process.env.CODACY_CLI_VERSION;
6
- const CLI_FILE_NAME = 'cli.sh';
7
- const CLI_FOLDER_NAME = '.codacy';
8
- const CLI_LOCAL_COMMAND = `${CLI_FOLDER_NAME}/${CLI_FILE_NAME}`;
9
- const CLI_GLOBAL_COMMAND = 'codacy-cli';
10
- // Set a larger buffer size (10MB)
11
- const MAX_BUFFER_SIZE = 1024 * 1024 * 10;
12
- const execAsync = (command, options) => {
13
- return new Promise((resolve, reject) => {
14
- exec(`${CODACY_CLI_VERSION ? `CODACY_CLI_V2_VERSION=${CODACY_CLI_VERSION} ` : ''}${command}`, {
15
- cwd: options.rootPath,
16
- maxBuffer: MAX_BUFFER_SIZE, // To solve: stdout maxBuffer exceeded
17
- }, (error, stdout, stderr) => {
18
- if (error) {
19
- reject(error);
20
- return;
21
- }
22
- if (stderr && !stdout) {
23
- reject(new Error(stderr));
24
- return;
25
- }
26
- resolve({ stdout, stderr });
27
- });
28
- });
29
- };
30
- // Safeguard: Validate and sanitize command inputs
31
- const sanitizeCommand = (command) => {
32
- // Remove any shell metacharacters
33
- return command?.replace(/[;&|`$]/g, '') || '';
34
- };
35
- // Run analysis with potential retry after installation
36
- const runAnalysis = async (cliCommand, args) => {
37
- const safeFile = sanitizeCommand(args.file);
38
- const tool = args.tool ? `--tool ${args.tool}` : '';
39
- const command = `${cliCommand} analyze ${tool} --format sarif ${safeFile}`;
40
- const options = {
41
- rootPath: args.rootPath,
42
- };
43
- return await execAsync(command, options);
44
- };
45
- const ensureCodacyConfig = async (cliCommand, rootPath, provider, organization, repository) => {
46
- const codacyConfigPath = path.join(rootPath, CLI_FOLDER_NAME, 'codacy.yaml');
47
- if (!fs.existsSync(codacyConfigPath)) {
48
- const apiToken = CODACY_ACCOUNT_TOKEN ? `--api-token ${CODACY_ACCOUNT_TOKEN}` : '';
49
- const repositoryAccess = repository && provider && organization
50
- ? `--provider ${provider} --organization ${organization} --repository ${repository}`
51
- : '';
52
- // initialize codacy-cli
53
- await execAsync(`${cliCommand} init ${apiToken} ${repositoryAccess}`, { rootPath });
54
- // install dependencies
55
- await execAsync(`${cliCommand} install`, { rootPath });
56
- }
57
- return true;
58
- };
59
- const ensureCodacyCLIExists = async (rootPath, provider, organization, repository) => {
60
- let isCLIAvailable = false;
61
- try {
62
- await execAsync(`${CLI_LOCAL_COMMAND} --help`, { rootPath });
63
- return CLI_LOCAL_COMMAND;
64
- }
65
- catch {
66
- isCLIAvailable = false;
67
- }
68
- if (!isCLIAvailable) {
69
- try {
70
- await execAsync(`${CLI_GLOBAL_COMMAND} --help`, { rootPath });
71
- return CLI_GLOBAL_COMMAND;
72
- }
73
- catch {
74
- isCLIAvailable = false;
75
- }
76
- }
77
- // install locally if not available
78
- const codacyFolder = path.join(rootPath, CLI_FOLDER_NAME);
79
- if (!fs.existsSync(codacyFolder)) {
80
- fs.mkdirSync(codacyFolder, { recursive: true });
81
- }
82
- // Download cli.sh if it doesn't exist
83
- const codacyCliPath = path.join(codacyFolder, CLI_FILE_NAME);
84
- if (!fs.existsSync(codacyCliPath)) {
85
- await execAsync(`curl -Ls -o "${CLI_LOCAL_COMMAND}" https://raw.githubusercontent.com/codacy/codacy-cli-v2/main/codacy-cli.sh`, { rootPath });
86
- await execAsync(`chmod +x "${CLI_LOCAL_COMMAND}"`, { rootPath });
87
- }
88
- // initialize codacy-cli
89
- await ensureCodacyConfig(CLI_LOCAL_COMMAND, rootPath, provider, organization, repository);
90
- return CLI_LOCAL_COMMAND;
91
- };
1
+ import { Cli } from '../cli/index.js';
92
2
  export const cliAnalyzeHandler = async (args) => {
3
+ const cli = await Cli.get(args);
93
4
  try {
94
- // Ensure codacy-cli is installed
95
- const cliCommand = await ensureCodacyCLIExists(args.rootPath, args.provider, args.organization, args.repository);
96
- if (!cliCommand) {
97
- return {
98
- success: false,
99
- errorType: 'cli-missing',
100
- output: 'Failed to install codacy-cli. Please install it manually.',
101
- };
102
- }
103
- // Check for mandatory configuration file and initialize if needed
104
- const configExists = await ensureCodacyConfig(cliCommand, args.rootPath, args.provider, args.organization, args.repository);
105
- if (!configExists) {
106
- return {
107
- success: false,
108
- errorType: 'cli-config-missing',
109
- output: 'Failed to find Codacy CLI configuration.',
110
- };
111
- }
112
- const { stdout, stderr } = await runAnalysis(cliCommand, args);
113
- // Try to extract JSON from the output if it's embedded in other text
114
- const jsonMatch = /(\{[\s\S]*\}|\[[\s\S]*\])/.exec(stdout);
5
+ const results = await cli.analyze({
6
+ file: args.file,
7
+ tool: args.tool,
8
+ });
115
9
  return {
116
10
  success: true,
117
- result: jsonMatch ? JSON.parse(jsonMatch[0]) : null,
118
- warnings: stderr,
11
+ result: results,
119
12
  };
120
13
  }
121
14
  catch (error) {
122
15
  return {
123
16
  success: false,
124
- errorType: 'try-catch',
125
17
  output: error instanceof Error ? error.message : 'Unknown error',
126
18
  };
127
19
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codacy/codacy-mcp",
3
- "version": "0.6.4",
3
+ "version": "0.6.6",
4
4
  "description": "Codacy MCP server",
5
5
  "license": "MIT",
6
6
  "author": "Codacy",
@@ -34,6 +34,7 @@
34
34
  "@modelcontextprotocol/sdk": "1.0.1",
35
35
  "@types/node": "^22",
36
36
  "@types/node-fetch": "^2.6.12",
37
+ "@types/sarif": "2.1.7",
37
38
  "node-fetch": "^3.3.2",
38
39
  "universal-user-agent": "^7.0.2"
39
40
  },