Skip to main content
Glama
JJJHoons

Python Code Review MCP Agent

by JJJHoons

analyze_code_quality

Analyze Python code for quality issues including style, maintainability, performance, and best practices compliance to improve code reliability and developer productivity.

Instructions

Deep code quality analysis including style, maintainability, performance, and best practices compliance.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYesPython code to analyze for quality issues
filenameNoName of the file (optional)unknown.py
includeStyleNoInclude style and naming convention checks
includeMaintainabilityNoInclude maintainability and documentation checks

Implementation Reference

  • The handleQualityAnalysis method is the primary handler for the 'analyze_code_quality' tool. It validates input, performs code analysis using PythonAnalyzer, applies user-specified filters for style and maintainability checks, generates a custom quality report, and returns the result as MCP content.
    private async handleQualityAnalysis(args: unknown) {
      const { code, filename, includeStyle, includeMaintainability } = QualityAnalysisSchema.parse(args);
      
      const result = this.analyzer.analyzePythonCode(code, filename);
      
      // Filter issues based on options
      let filteredIssues = result.issues;
      
      if (!includeStyle) {
        filteredIssues = filteredIssues.filter(issue => 
          issue.type !== 'style' && !issue.rule.includes('naming-convention')
        );
      }
      
      if (!includeMaintainability) {
        filteredIssues = filteredIssues.filter(issue => issue.type !== 'maintainability');
      }
      
      const filteredResult = { ...result, issues: filteredIssues, totalIssues: filteredIssues.length };
      const qualityReport = this.generateQualityReport(filteredResult);
      
      return {
        content: [
          {
            type: 'text',
            text: qualityReport
          }
        ]
      };
  • Zod validation schema for the analyze_code_quality tool input parameters, defining code, filename, includeStyle, and includeMaintainability fields.
    const QualityAnalysisSchema = z.object({
      code: z.string().min(1, "Code cannot be empty"),
      filename: z.string().optional().default("unknown.py"),
      includeStyle: z.boolean().optional().default(true),
      includeMaintainability: z.boolean().optional().default(true)
    });
  • src/index.ts:125-153 (registration)
    Tool registration in the ListTools response, defining the name, description, and JSON schema for input validation of analyze_code_quality.
    {
      name: 'analyze_code_quality',
      description: 'Deep code quality analysis including style, maintainability, performance, and best practices compliance.',
      inputSchema: {
        type: 'object',
        properties: {
          code: {
            type: 'string',
            description: 'Python code to analyze for quality issues'
          },
          filename: {
            type: 'string',
            description: 'Name of the file (optional)',
            default: 'unknown.py'
          },
          includeStyle: {
            type: 'boolean',
            description: 'Include style and naming convention checks',
            default: true
          },
          includeMaintainability: {
            type: 'boolean',
            description: 'Include maintainability and documentation checks',
            default: true
          }
        },
        required: ['code']
      }
    },
  • Core analysis engine called by the tool handler. Uses regex patterns to detect security vulnerabilities, quality issues, style violations, and maintainability problems in Python code, computes quality and security scores, and produces structured AnalysisResult.
    public analyzePythonCode(code: string, fileName: string = 'unknown.py'): AnalysisResult {
      const lines = code.split('\n');
      const issues: CodeIssue[] = [];
      
      // Analyze each line
      lines.forEach((line, index) => {
        const lineNumber = index + 1;
        
        // Check security patterns
        this.securityPatterns.forEach(pattern => {
          if (pattern.pattern.test(line)) {
            issues.push({
              type: 'security',
              severity: pattern.severity,
              line: lineNumber,
              message: pattern.message,
              rule: pattern.rule,
              codeSnippet: line.trim(),
              suggestion: this.getSuggestion(pattern.rule, line)
            });
          }
        });
        
        // Check quality patterns
        this.qualityPatterns.forEach(pattern => {
          if (pattern.pattern.test(line)) {
            issues.push({
              type: 'quality',
              severity: pattern.severity,
              line: lineNumber,
              message: pattern.message,
              rule: pattern.rule,
              codeSnippet: line.trim(),
              suggestion: this.getSuggestion(pattern.rule, line)
            });
          }
        });
        
        // Check maintainability patterns
        this.maintainabilityPatterns.forEach(pattern => {
          if (pattern.pattern.test(line)) {
            issues.push({
              type: 'maintainability',
              severity: pattern.severity,
              line: lineNumber,
              message: pattern.message,
              rule: pattern.rule,
              codeSnippet: line.trim(),
              suggestion: this.getSuggestion(pattern.rule, line)
            });
          }
        });
      });
    
      // Multi-line analysis
      this.analyzeMultilinePatterns(code, issues);
      
      // Calculate metrics
      const criticalIssues = issues.filter(i => i.severity === 'critical').length;
      const highIssues = issues.filter(i => i.severity === 'high').length;
      const mediumIssues = issues.filter(i => i.severity === 'medium').length;
      const lowIssues = issues.filter(i => i.severity === 'low').length;
      
      const codeQualityScore = this.calculateCodeQualityScore(issues, lines.length);
      const securityScore = this.calculateSecurityScore(issues);
      
      return {
        fileName,
        totalLines: lines.length,
        totalIssues: issues.length,
        criticalIssues,
        highIssues,
        mediumIssues,
        lowIssues,
        issues: issues.sort((a, b) => {
          const severityOrder = { critical: 4, high: 3, medium: 2, low: 1 };
          return severityOrder[b.severity] - severityOrder[a.severity] || a.line - b.line;
        }),
        summary: this.generateSummary(issues, lines.length),
        recommendations: this.generateRecommendations(issues),
        codeQualityScore,
        securityScore
      };
    }
  • Helper method that formats the quality analysis report specific to the analyze_code_quality tool, including header, quality score, breakdown, and recommendations.
    private generateQualityReport(result: AnalysisResult): string {
      const sections = [
        '📊 **CODE QUALITY ANALYSIS REPORT**',
        '=' + '='.repeat(50),
        `**File:** ${result.fileName}`,
        `**Quality Score:** ${result.codeQualityScore}/100 ${this.getQualityRating(result.codeQualityScore)}`,
        '',
        this.generateQualityBreakdown(result),
        '',
        this.generateQualityRecommendations(result)
      ];
    
      return sections.join('\n');
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries full burden for behavioral disclosure. While it mentions what aspects are analyzed, it doesn't describe important behavioral traits like whether this is a read-only operation, what the output format looks like, whether there are rate limits, computational costs, or specific authentication requirements. For a tool with 4 parameters and no annotations, this is a significant gap.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that communicates the core purpose without unnecessary words. It's appropriately sized and front-loaded with the main action and scope, making it easy for an agent to quickly understand what the tool does.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with 4 parameters, no annotations, and no output schema, the description is insufficient. It doesn't explain what the analysis returns, how results are structured, what happens with the optional parameters, or how this differs from similar sibling tools. The description should provide more context given the complexity and lack of structured metadata.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already fully documents all 4 parameters. The description doesn't add any parameter-specific information beyond what's in the schema. The baseline score of 3 is appropriate when the schema does all the parameter documentation work.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool performs 'Deep code quality analysis' and specifies the aspects covered: style, maintainability, performance, and best practices compliance. This provides a specific verb (analyze) and resource (code quality) with scope details, though it doesn't explicitly differentiate from sibling tools like 'review_python_code' or 'security_audit'.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. With sibling tools like 'review_python_code', 'security_audit', and 'get_improvement_suggestions' available, there's no indication of when this comprehensive analysis is preferred over more specialized tools or what prerequisites might exist.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/JJJHoons/python_code_review_mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server