@codacy/codacy-mcp 0.6.5 → 0.6.7

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,140 +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
- // Function to detect if user is on Windows
13
- const isWindows = () => {
14
- const isWindows = process.platform === 'win32';
15
- return isWindows;
16
- };
17
- const execAsync = (command, options) => {
18
- return new Promise((resolve, reject) => {
19
- exec(`${CODACY_CLI_VERSION ? `CODACY_CLI_V2_VERSION=${CODACY_CLI_VERSION} ` : ''}${command}`, {
20
- cwd: options.rootPath,
21
- maxBuffer: MAX_BUFFER_SIZE, // To solve: stdout maxBuffer exceeded
22
- }, (error, stdout, stderr) => {
23
- if (error) {
24
- reject(error);
25
- return;
26
- }
27
- if (stderr && !stdout) {
28
- reject(new Error(stderr));
29
- return;
30
- }
31
- resolve({ stdout, stderr });
32
- });
33
- });
34
- };
35
- // Safeguard: Validate and sanitize command inputs
36
- const sanitizeCommand = (command) => {
37
- // Remove any shell metacharacters
38
- return command?.replace(/[;&|`$]/g, '') || '';
39
- };
40
- // Run analysis with potential retry after installation
41
- const runAnalysis = async (cliCommand, args) => {
42
- const safeFile = sanitizeCommand(args.file);
43
- const tool = args.tool ? `--tool ${args.tool}` : '';
44
- const command = `${cliCommand} analyze ${tool} --format sarif ${safeFile}`;
45
- const options = {
46
- rootPath: args.rootPath,
47
- };
48
- return await execAsync(command, options);
49
- };
50
- const ensureCodacyConfig = async (cliCommand, rootPath, provider, organization, repository) => {
51
- const codacyConfigPath = path.join(rootPath, CLI_FOLDER_NAME, 'codacy.yaml');
52
- if (!fs.existsSync(codacyConfigPath)) {
53
- const apiToken = CODACY_ACCOUNT_TOKEN ? `--api-token ${CODACY_ACCOUNT_TOKEN}` : '';
54
- const repositoryAccess = repository && provider && organization
55
- ? `--provider ${provider} --organization ${organization} --repository ${repository}`
56
- : '';
57
- // initialize codacy-cli
58
- await execAsync(`${cliCommand} init ${apiToken} ${repositoryAccess}`, { rootPath });
59
- // install dependencies
60
- await execAsync(`${cliCommand} install`, { rootPath });
61
- }
62
- return true;
63
- };
64
- const ensureCodacyCLIExists = async (rootPath, provider, organization, repository) => {
65
- let isCLIAvailable = false;
66
- try {
67
- await execAsync(`${CLI_LOCAL_COMMAND} --help`, { rootPath });
68
- return CLI_LOCAL_COMMAND;
69
- }
70
- catch {
71
- isCLIAvailable = false;
72
- }
73
- if (!isCLIAvailable) {
74
- try {
75
- await execAsync(`${CLI_GLOBAL_COMMAND} --help`, { rootPath });
76
- return CLI_GLOBAL_COMMAND;
77
- }
78
- catch {
79
- isCLIAvailable = false;
80
- }
81
- }
82
- // install locally if not available
83
- const codacyFolder = path.join(rootPath, CLI_FOLDER_NAME);
84
- if (!fs.existsSync(codacyFolder)) {
85
- fs.mkdirSync(codacyFolder, { recursive: true });
86
- }
87
- // Download cli.sh if it doesn't exist
88
- const codacyCliPath = path.join(codacyFolder, CLI_FILE_NAME);
89
- if (!fs.existsSync(codacyCliPath)) {
90
- await execAsync(`curl -Ls -o "${CLI_LOCAL_COMMAND}" https://raw.githubusercontent.com/codacy/codacy-cli-v2/main/codacy-cli.sh`, { rootPath });
91
- await execAsync(`chmod +x "${CLI_LOCAL_COMMAND}"`, { rootPath });
92
- }
93
- // initialize codacy-cli
94
- await ensureCodacyConfig(CLI_LOCAL_COMMAND, rootPath, provider, organization, repository);
95
- return CLI_LOCAL_COMMAND;
96
- };
1
+ import { Cli } from '../cli/index.js';
97
2
  export const cliAnalyzeHandler = async (args) => {
98
- if (isWindows()) {
99
- // If the user is on Windows return an error message
100
- return {
101
- success: false,
102
- errorType: 'cli-unsupported-os',
103
- output: 'Codacy CLI is only available on Windows via WSL (Windows Subsystem for Linux).',
104
- };
105
- }
3
+ const cli = await Cli.get(args);
106
4
  try {
107
- // Ensure codacy-cli is installed
108
- const cliCommand = await ensureCodacyCLIExists(args.rootPath, args.provider, args.organization, args.repository);
109
- if (!cliCommand) {
110
- return {
111
- success: false,
112
- errorType: 'cli-missing',
113
- output: 'Failed to install codacy-cli. Please install it manually.',
114
- };
115
- }
116
- // Check for mandatory configuration file and initialize if needed
117
- const configExists = await ensureCodacyConfig(cliCommand, args.rootPath, args.provider, args.organization, args.repository);
118
- if (!configExists) {
119
- return {
120
- success: false,
121
- errorType: 'cli-config-missing',
122
- output: 'Failed to find Codacy CLI configuration.',
123
- };
124
- }
125
- const { stdout, stderr } = await runAnalysis(cliCommand, args);
126
- // Try to extract JSON from the output if it's embedded in other text
127
- const jsonMatch = /(\{[\s\S]*\}|\[[\s\S]*\])/.exec(stdout);
5
+ const results = await cli.analyze({
6
+ file: args.file,
7
+ tool: args.tool,
8
+ });
128
9
  return {
129
10
  success: true,
130
- result: jsonMatch ? JSON.parse(jsonMatch[0]) : null,
131
- warnings: stderr,
11
+ result: results,
132
12
  };
133
13
  }
134
14
  catch (error) {
135
15
  return {
136
16
  success: false,
137
- errorType: 'try-catch',
138
17
  output: error instanceof Error ? error.message : 'Unknown error',
139
18
  };
140
19
  }
@@ -42,7 +42,7 @@ export const repositorySchema = {
42
42
  ...organizationSchema,
43
43
  repository: {
44
44
  type: 'string',
45
- description: "Repository name on the Git provider. Try to extract it from the repository's git remote URL using 'git remote -v', it should be something like this for gh:'https://github.com/<owner>/<repository>.git' for gl:'https://gitlab.com/<owner>/<repository>.git' for bb:'https://bitbucket.org/<owner>/<repository>.git'.",
45
+ description: "Repository name on the Git provider. Try to extract it from the repository's git remote URL using 'git remote -v', it should be something like this for gh:'https://github.com/<owner>/<repository>.git' for gl:'https://gitlab.com/<owner>/<repository>.git' for bb:'https://bitbucket.org/<owner>/<repository>.git'.",
46
46
  },
47
47
  };
48
48
  export const defaultPagination = {
@@ -41,6 +41,6 @@ export const cliAnalyzeTool = {
41
41
  default: '',
42
42
  },
43
43
  },
44
- required: ['provider', 'organization', 'repository', 'rootPath'],
44
+ required: ['rootPath'],
45
45
  },
46
46
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codacy/codacy-mcp",
3
- "version": "0.6.5",
3
+ "version": "0.6.7",
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
  },