@codacy/codacy-mcp 0.6.18 → 0.6.20

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 CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
2
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
3
  import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
5
4
  import { OpenAPI } from './src/api/client/index.js';
6
5
  import * as Tools from './src/tools/index.js';
7
6
  import * as Handlers from './src/handlers/index.js';
7
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
8
8
  // Check for API key
9
9
  const CODACY_ACCOUNT_TOKEN = process.env.CODACY_ACCOUNT_TOKEN;
10
10
  OpenAPI.BASE = 'https://app.codacy.com/api/v3';
@@ -12,40 +12,13 @@ OpenAPI.HEADERS = {
12
12
  'api-token': CODACY_ACCOUNT_TOKEN || '',
13
13
  'X-Codacy-Origin': 'mcp-server',
14
14
  };
15
- const server = new Server({
15
+ const mcpServer = new McpServer({
16
16
  name: 'codacy-mcp-server',
17
17
  version: '0.1.0',
18
18
  }, {
19
19
  capabilities: {
20
20
  tools: {},
21
21
  resources: {},
22
- triggers: {
23
- patterns: [
24
- 'codacy',
25
- 'code quality',
26
- 'code analysis',
27
- 'security vulnerabilities',
28
- 'repository issues',
29
- 'pull request analysis',
30
- 'code coverage',
31
- 'issues',
32
- 'security',
33
- 'srm',
34
- 'analysis',
35
- 'tool',
36
- 'pattern',
37
- 'pull request',
38
- 'repository',
39
- 'file',
40
- 'coverage',
41
- 'git',
42
- 'diff',
43
- 'branch',
44
- 'commit',
45
- 'severity',
46
- 'organization',
47
- ],
48
- },
49
22
  },
50
23
  });
51
24
  const toolDefinitions = {
@@ -140,19 +113,24 @@ const toolDefinitions = {
140
113
  handler: Handlers.cliAnalyzeHandler,
141
114
  noAuth: true,
142
115
  },
116
+ codacy_cli_install: {
117
+ tool: Tools.cliInstallTool,
118
+ handler: Handlers.cliInstallHandler,
119
+ noAuth: true,
120
+ },
143
121
  codacy_setup_repository: {
144
122
  tool: Tools.setupRepositoryTool,
145
123
  handler: Handlers.setupRepositoryHandler,
146
124
  },
147
125
  };
148
126
  // Register tools
149
- server.setRequestHandler(ListToolsRequestSchema, async () => ({
127
+ mcpServer.server.setRequestHandler(ListToolsRequestSchema, async () => ({
150
128
  tools: Object.values(toolDefinitions)
151
129
  .filter(({ noAuth }) => CODACY_ACCOUNT_TOKEN || noAuth)
152
130
  .map(({ tool }) => tool),
153
131
  }));
154
132
  // Register request handlers
155
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
133
+ mcpServer.server.setRequestHandler(CallToolRequestSchema, async (request) => {
156
134
  try {
157
135
  if (!request.params.arguments) {
158
136
  throw new Error('Arguments are required');
@@ -179,7 +157,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
179
157
  });
180
158
  async function runServer() {
181
159
  const transport = new StdioServerTransport();
182
- await server.connect(transport);
160
+ await mcpServer.connect(transport);
183
161
  console.error('Codacy MCP Server running on stdio');
184
162
  }
185
163
  runServer().catch(error => {
@@ -1,5 +1,6 @@
1
1
  export const CODACY_FOLDER_NAME = '.codacy';
2
2
  import { exec } from 'child_process';
3
+ import * as path from 'path';
3
4
  // Set a larger buffer size (10MB)
4
5
  const MAX_BUFFER_SIZE = 1024 * 1024 * 10;
5
6
  export class CodacyCli {
@@ -22,16 +23,50 @@ export class CodacyCli {
22
23
  setCliCommand(command) {
23
24
  this._cliCommand = command;
24
25
  }
26
+ isPathSafe(filePath) {
27
+ // Reject null bytes (always a security risk)
28
+ if (filePath.includes('\0')) {
29
+ return false;
30
+ }
31
+ // Reject all control characters (including newline, tab, carriage return)
32
+ // as they are very unusual for file names
33
+ // eslint-disable-next-line no-control-regex -- Intentionally checking for control chars to reject them for security
34
+ const hasUnsafeControlChars = /[\x00-\x1F\x7F]/.test(filePath);
35
+ if (hasUnsafeControlChars) {
36
+ return false;
37
+ }
38
+ // Resolve the path to check for path traversal attempts
39
+ const resolvedPath = path.resolve(this.rootPath, filePath);
40
+ const normalizedRoot = path.normalize(this.rootPath);
41
+ // Check if the resolved path is within the workspace
42
+ if (!resolvedPath.startsWith(normalizedRoot)) {
43
+ return false;
44
+ }
45
+ return true;
46
+ }
25
47
  preparePathForExec(path) {
26
- return path;
48
+ // Validate path security before escaping
49
+ if (!this.isPathSafe(path)) {
50
+ throw new Error(`Unsafe file path rejected: ${path}`);
51
+ }
52
+ // Escape special characters for shell execution
53
+ return path.replace(/([\s'"\\;&|`$()[\]{}*?~<>])/g, '\\$1');
27
54
  }
28
55
  execAsync(command, args) {
29
56
  // stringyfy the args
30
57
  const argsString = Object.entries(args || {})
31
- .map(([key, value]) => `--${key} ${value}`)
58
+ .map(([key, value]) => {
59
+ // Validate argument key (should be alphanumeric and hyphens only)
60
+ if (!/^[a-zA-Z0-9-]+$/.test(key)) {
61
+ throw new Error(`Invalid argument key: ${key}`);
62
+ }
63
+ // Escape the value to prevent injection
64
+ const escapedValue = value.replace(/([\s'"\\;&|`$()[\]{}*?~<>])/g, '\\$1');
65
+ return `--${key} ${escapedValue}`;
66
+ })
32
67
  .join(' ');
33
- // Add the args to the command and remove any shell metacharacters
34
- const cmd = `${command} ${argsString}`.trim().replace(/[;&|`$]/g, '');
68
+ // Build the command - no need to strip characters since we've already escaped them properly
69
+ const cmd = `${command} ${argsString}`.trim();
35
70
  return new Promise((resolve, reject) => {
36
71
  exec(cmd, {
37
72
  cwd: this.rootPath,
@@ -14,9 +14,8 @@ export class MacCodacyCli extends CodacyCli {
14
14
  this.setCliCommand(this._cliVersion ? `CODACY_CLI_V2_VERSION=${this._cliVersion} ${localPath}` : localPath);
15
15
  return;
16
16
  }
17
- // CLI not found, attempt to install it
18
- await this.install();
19
- return;
17
+ // CLI not found, throw error
18
+ throw new Error(`Codacy CLI not found. Please install it first.`);
20
19
  }
21
20
  async preflightCodacyCli() {
22
21
  // is there a command?
@@ -7,23 +7,37 @@ export class WinWSLCodacyCli extends MacCodacyCli {
7
7
  super(winRootPath, provider, organization, repository);
8
8
  }
9
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');
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()}`);
13
16
  return wslPath;
14
17
  }
15
18
  static fromWSLPath(path) {
16
19
  // Convert WSL path to Windows path
17
20
  // Example: /mnt/c/Users/user/project -> C:\Users\user\project
18
- const windowsPath = path.replace(/^\/mnt\/([a-zA-Z])/, '$1:').replace(/\//g, '\\');
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, '\\');
19
25
  return windowsPath;
20
26
  }
21
27
  preparePathForExec(path) {
22
- // Convert the path to WSL format
23
- return WinWSLCodacyCli.toWSLPath(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}'`;
24
38
  }
25
39
  async execAsync(command, args) {
26
- return await super.execAsync(`wsl ${command}`, args);
40
+ return await super.execAsync(`wsl bash -c "${command}"`, args);
27
41
  }
28
42
  getCliCommand() {
29
43
  return WinWSLCodacyCli.toWSLPath(super.getCliCommand());
@@ -3,7 +3,7 @@ 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: args.file,
6
+ file: `'${args.file}'`,
7
7
  tool: args.tool,
8
8
  });
9
9
  // clean up the results to remove superfluous information
@@ -0,0 +1,17 @@
1
+ import { Cli } from '../cli/index.js';
2
+ export const cliInstallHandler = async (args) => {
3
+ const cli = await Cli.get(args);
4
+ try {
5
+ await cli.install();
6
+ return {
7
+ success: true,
8
+ result: 'CLI installed successfully',
9
+ };
10
+ }
11
+ catch (error) {
12
+ return {
13
+ success: false,
14
+ output: error instanceof Error ? error.message : 'Unknown error',
15
+ };
16
+ }
17
+ };
@@ -7,3 +7,4 @@ export * from './tools.js';
7
7
  export * from './account.js';
8
8
  export * from './cliAnalyze.js';
9
9
  export * from './setupRepository.js';
10
+ export * from './cliInstall.js';
@@ -20,6 +20,7 @@ export const toolNames = {
20
20
  CODACY_GET_ISSUE: 'codacy_get_issue',
21
21
  CODACY_GET_PATTERN: 'codacy_get_pattern',
22
22
  CODACY_CLI_ANALYZE: 'codacy_cli_analyze',
23
+ CODACY_CLI_INSTALL: 'codacy_cli_install',
23
24
  CODACY_GET_FILE_CLONES: 'codacy_get_file_clones',
24
25
  CODACY_SETUP_REPOSITORY: 'codacy_setup_repository',
25
26
  };
@@ -0,0 +1,24 @@
1
+ import { generalOrganizationMistakes, generalRepositoryMistakes } from '../rules.js';
2
+ import { repositorySchema, toolNames } from '../schemas.js';
3
+ const rules = `
4
+ Common use cases:
5
+ - When the user tried to use Codacy CLI and it is not installed
6
+
7
+ Common mistakes:
8
+ ${generalOrganizationMistakes}
9
+ ${generalRepositoryMistakes}
10
+ `;
11
+ const optionalRepositorySchema = JSON.parse(JSON.stringify(repositorySchema));
12
+ optionalRepositorySchema.provider.description = `Optional. ${repositorySchema.provider.description}`;
13
+ optionalRepositorySchema.organization.description = `Optional. ${repositorySchema.organization.description}`;
14
+ optionalRepositorySchema.repository.description = `Optional. ${repositorySchema.repository.description}`;
15
+ export const cliInstallTool = {
16
+ name: toolNames.CODACY_CLI_INSTALL,
17
+ description: `Install the Codacy CLI used for local analysis. \n ${rules}`,
18
+ inputSchema: {
19
+ type: 'object',
20
+ properties: {
21
+ ...optionalRepositorySchema,
22
+ },
23
+ },
24
+ };
@@ -20,3 +20,4 @@ export * from './listOrganizationsTool.js';
20
20
  export * from './cliAnalyzeTool.js';
21
21
  export * from './getFileClonesTool.js';
22
22
  export * from './setupRepositoryTool.js';
23
+ export * from './cliInstallTool.js';
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "@codacy/codacy-mcp",
3
- "version": "0.6.18",
3
+ "version": "0.6.20",
4
+ "mcpName": "io.github.codacy/codacy-mcp-server",
4
5
  "description": "Codacy MCP server",
5
6
  "license": "MIT",
6
7
  "author": "Codacy",
@@ -31,7 +32,7 @@
31
32
  "inspect": "npm run build && npx @modelcontextprotocol/inspector -e CODACY_ACCOUNT_TOKEN=$CODACY_ACCOUNT_TOKEN node dist/index.js"
32
33
  },
33
34
  "dependencies": {
34
- "@modelcontextprotocol/sdk": "1.0.1",
35
+ "@modelcontextprotocol/sdk": "1.25.2",
35
36
  "@types/node": "^22",
36
37
  "@types/node-fetch": "^2.6.12",
37
38
  "@types/sarif": "2.1.7",