Skip to main content
Glama
JJJHoons

Python Code Review MCP Agent

by JJJHoons

review_python_code

Analyze Python code for quality and security issues, generating detailed reports with actionable recommendations to improve your codebase.

Instructions

Comprehensive Python code analysis focusing on quality and security. Provides detailed reports with actionable recommendations.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYesPython code to analyze
filenameNoName of the file (optional, defaults to unknown.py)unknown.py
reportTypeNoType of report to generatedetailed

Implementation Reference

  • src/index.ts:81-105 (registration)
    MCP tool registration for 'review_python_code' including name, description, and input schema.
    {
      name: 'review_python_code',
      description: 'Comprehensive Python code analysis focusing on quality and security. Provides detailed reports with actionable recommendations.',
      inputSchema: {
        type: 'object',
        properties: {
          code: {
            type: 'string',
            description: 'Python code to analyze'
          },
          filename: {
            type: 'string',
            description: 'Name of the file (optional, defaults to unknown.py)',
            default: 'unknown.py'
          },
          reportType: {
            type: 'string',
            enum: ['detailed', 'summary', 'security'],
            description: 'Type of report to generate',
            default: 'detailed'
          }
        },
        required: ['code']
      }
    },
  • Zod input validation schema for review_python_code tool.
    const ReviewCodeSchema = z.object({
      code: z.string().min(1, "Code cannot be empty"),
      filename: z.string().optional().default("unknown.py"),
      reportType: z.enum(["detailed", "summary", "security"]).optional().default("detailed")
    });
  • Core handler function for 'review_python_code' tool: validates input, performs analysis, generates and returns formatted report.
    private async handleReviewCode(args: unknown) {
      const { code, filename, reportType } = ReviewCodeSchema.parse(args);
      
      const result = this.analyzer.analyzePythonCode(code, filename);
      let report: string;
      
      switch (reportType) {
        case 'summary':
          report = this.formatter.generateSummaryReport(result);
          break;
        case 'security':
          report = this.formatter.generateSecurityReport(result);
          break;
        default:
          report = this.formatter.generateDetailedReport(result);
      }
    
      return {
        content: [
          {
            type: 'text',
            text: report
          }
        ]
      };
    }
  • PythonAnalyzer.analyzePythonCode: Performs the core static analysis detecting issues via regex patterns for security, quality, maintainability; calculates scores and generates issues list.
    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
      };
    }
  • ReportFormatter.generateDetailedReport: Formats analysis results into comprehensive Markdown report used by the tool.
    public generateDetailedReport(result: AnalysisResult): string {
      const sections = [
        this.generateHeader(result),
        this.generateExecutiveSummary(result),
        this.generateScorecard(result),
        this.generateIssuesBreakdown(result),
        this.generateDetailedIssues(result),
        this.generateRecommendations(result),
        this.generateFooter()
      ];
      
      return sections.join('\n\n');
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions 'detailed reports with actionable recommendations,' which hints at output format, but lacks critical details like whether this is a read-only analysis, potential performance impacts, error handling, or authentication needs. For a tool with no annotation coverage, this is a significant gap in transparency.

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

Conciseness4/5

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

The description is a single, efficient sentence that front-loads the core purpose ('Comprehensive Python code analysis focusing on quality and security') and adds a secondary detail ('Provides detailed reports with actionable recommendations'). It avoids redundancy and wastes no words, though it could be slightly more structured for clarity.

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

Completeness3/5

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

Given the tool's moderate complexity (3 parameters, no output schema, no annotations), the description is minimally adequate. It covers the purpose and output type but lacks details on behavioral traits, usage guidelines, and differentiation from siblings. Without annotations or output schema, more context on what the reports contain or how to interpret results would improve completeness.

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 documents all parameters (code, filename, reportType) with descriptions and defaults. The description adds no additional meaning beyond what the schema provides, such as explaining how 'reportType' affects the analysis or providing examples. Baseline 3 is appropriate when the schema handles parameter documentation adequately.

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's purpose as 'Comprehensive Python code analysis focusing on quality and security' with 'detailed reports with actionable recommendations.' This specifies the verb (analyze), resource (Python code), and scope (quality and security). However, it doesn't explicitly differentiate from sibling tools like 'analyze_code_quality' or 'security_audit,' which likely have overlapping functionality.

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 like 'analyze_code_quality' or 'security_audit.' It mentions 'quality and security' but doesn't specify contexts, exclusions, or prerequisites. Usage is implied through the purpose statement, but explicit alternatives or conditions are missing.

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