Skip to main content
Glama

validate_code_quality

Validate code quality by analyzing complexity, coupling, cohesion, maintainability, and performance metrics to ensure robust and efficient code.

Instructions

quality|review|check|quality|review code|check quality|validate|code review - Validate code quality

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYesCode to validate
typeNoCode type
strictNoApply strict validation rules
metricsNoSpecific metrics to check

Implementation Reference

  • Main handler function that performs comprehensive code quality validation including complexity metrics, anti-pattern detection, scoring, and issue reporting.
    export async function validateCodeQuality(args: { code: string; type?: string; strict?: boolean; metrics?: string }): Promise<ToolResult> {
      const { code: validateCode, type: validateType = 'general', strict = false, metrics = 'all' } = args;
      
      const qualityIssues = [];
      const qualityScore = { total: 100, deductions: [] as Array<{reason: string, points: number}> };
      
      // Basic complexity checks
      const lines = validateCode.split('\n');
      const functionLineCount = lines.length;
      
      if (functionLineCount > CODE_QUALITY_METRICS.COMPLEXITY.maxFunctionLines) {
        qualityIssues.push({
          type: 'complexity',
          severity: 'high',
          message: `Function exceeds maximum lines (${functionLineCount}/${CODE_QUALITY_METRICS.COMPLEXITY.maxFunctionLines})`
        });
        qualityScore.deductions.push({ reason: 'Function too long', points: 15 });
      }
      
      // Nesting depth check
      let maxNesting = 0;
      let currentNesting = 0;
      for (const line of lines) {
        const braceCount = (line.match(/\{/g) || []).length - (line.match(/\}/g) || []).length;
        currentNesting += braceCount;
        maxNesting = Math.max(maxNesting, currentNesting);
      }
      
      if (maxNesting > CODE_QUALITY_METRICS.COMPLEXITY.maxNestingDepth) {
        qualityIssues.push({
          type: 'complexity',
          severity: 'medium',
          message: `Nesting depth exceeds maximum (${maxNesting}/${CODE_QUALITY_METRICS.COMPLEXITY.maxNestingDepth})`
        });
        qualityScore.deductions.push({ reason: 'Deep nesting', points: 10 });
      }
      
      // Cyclomatic complexity estimation
      const cyclomaticComplexity = (validateCode.match(/\bif\b|\bfor\b|\bwhile\b|\bcase\b|\b&&\b|\b\|\|\b/g) || []).length + 1;
      if (cyclomaticComplexity > CODE_QUALITY_METRICS.COMPLEXITY.maxCyclomaticComplexity) {
        qualityIssues.push({
          type: 'complexity',
          severity: 'high',
          message: `Cyclomatic complexity too high (${cyclomaticComplexity}/${CODE_QUALITY_METRICS.COMPLEXITY.maxCyclomaticComplexity})`
        });
        qualityScore.deductions.push({ reason: 'High cyclomatic complexity', points: 20 });
      }
      
      // Anti-pattern checks
      if (validateCode.includes('any')) {
        qualityIssues.push({
          type: 'type-safety',
          severity: 'medium',
          message: 'Using "any" type - consider more specific types'
        });
        qualityScore.deductions.push({ reason: 'Any type usage', points: 10 });
      }
      
      if (validateCode.includes('== ')) {
        qualityIssues.push({
          type: 'best-practices',
          severity: 'low',
          message: 'Use strict equality (===) instead of loose equality (==)'
        });
        qualityScore.deductions.push({ reason: 'Loose equality', points: 5 });
      }
      
      if (validateCode.includes('var ')) {
        qualityIssues.push({
          type: 'best-practices',
          severity: 'medium',
          message: 'Use const/let instead of var'
        });
        qualityScore.deductions.push({ reason: 'Var usage', points: 8 });
      }
      
      // Magic numbers check
      const magicNumbers = validateCode.match(/\b\d{2,}\b/g) || [];
      if (magicNumbers.length > 0) {
        qualityIssues.push({
          type: 'maintainability',
          severity: 'low',
          message: `Found potential magic numbers: ${magicNumbers.join(', ')}`
        });
        qualityScore.deductions.push({ reason: 'Magic numbers', points: 5 });
      }
      
      // Error handling check
      const hasErrorHandling = validateCode.includes('try') || validateCode.includes('catch') || validateCode.includes('throw');
      if (!hasErrorHandling && validateCode.includes('async')) {
        qualityIssues.push({
          type: 'error-handling',
          severity: 'medium',
          message: 'Async functions should include error handling'
        });
        qualityScore.deductions.push({ reason: 'Missing error handling', points: 10 });
      }
      
      // Performance checks for React components
      if (validateType === 'component' && validateCode.includes('React') && (!validateCode.includes('memo') && !validateCode.includes('useMemo') && !validateCode.includes('useCallback'))) {
            qualityIssues.push({
              type: 'performance',
              severity: 'low',
              message: 'Consider using React.memo, useMemo, or useCallback for performance optimization'
            });
            qualityScore.deductions.push({ reason: 'Missing performance optimization', points: 5 });
      }
      
      const finalScore = Math.max(0, qualityScore.total - qualityScore.deductions.reduce((sum, d) => sum + d.points, 0));
      
      const validationResult = {
        action: 'validate_code_quality',
        type: validateType,
        strict,
        metricsRequested: metrics,
        score: finalScore,
        grade: finalScore >= 90 ? 'A' : finalScore >= 80 ? 'B' : finalScore >= 70 ? 'C' : finalScore >= 60 ? 'D' : 'F',
        issues: qualityIssues,
        deductions: qualityScore.deductions,
        recommendations: qualityIssues.length > 0 ? [
          'Consider breaking down complex functions',
          'Reduce nesting depth with early returns',
          'Use more specific types instead of "any"',
          'Apply consistent coding standards',
          'Add proper error handling',
          'Consider performance optimizations'
        ] : ['Code quality is excellent!'],
        metrics: {
          complexity: cyclomaticComplexity,
          lines: functionLineCount,
          nesting: maxNesting,
          issues: qualityIssues.length
        },
        status: 'success'
      };
      
      const topIssues = qualityIssues.slice(0, 8);
      return {
        content: [{ type: 'text', text: `Type: ${validateType}\nScore: ${finalScore}/100 (Grade: ${validationResult.grade})\nMetrics: Lines=${validationResult.metrics.lines}, Complexity=${validationResult.metrics.complexity}, Nesting=${validationResult.metrics.nesting}\n\nIssues (${qualityIssues.length}):\n${topIssues.map(i => `[${i.severity.toUpperCase()}] ${i.type}: ${i.message}`).join('\n')}${qualityIssues.length > 8 ? `\n... ${qualityIssues.length - 8} more issues` : ''}\n\nDeductions: -${qualityScore.deductions.reduce((sum, d) => sum + d.points, 0)} pts (${qualityScore.deductions.map(d => `${d.reason}: -${d.points}`).join(', ')})` }]
      };
    }
  • Tool definition including name, description, input schema with parameters for code, type, strict mode, and metrics.
    export const validateCodeQualityDefinition: ToolDefinition = {
      name: 'validate_code_quality',
      description: 'quality|review|check|quality|review code|check quality|validate|code review - Validate code quality',
      inputSchema: {
        type: 'object',
        properties: {
          code: { type: 'string', description: 'Code to validate' },
          type: { type: 'string', description: 'Code type', enum: ['component', 'function', 'hook', 'utility', 'general'] },
          strict: { type: 'boolean', description: 'Apply strict validation rules' },
          metrics: { type: 'string', description: 'Specific metrics to check', enum: ['complexity', 'coupling', 'cohesion', 'maintainability', 'performance', 'all'] }
        },
        required: ['code']
      },
      annotations: {
        title: 'Validate Code Quality',
        audience: ['user', 'assistant']
      }
    };
  • src/index.ts:662-663 (registration)
    Registration in the tool execution switch statement that maps 'validate_code_quality' calls to the validateCodeQuality handler.
    case 'validate_code_quality':
      return await validateCodeQuality(args as any) as CallToolResult;
  • src/index.ts:139-139 (registration)
    Inclusion of the tool definition in the tools array for listTools endpoint.
    validateCodeQualityDefinition,
  • Configuration object defining quality metrics thresholds used in validation checks.
    const CODE_QUALITY_METRICS = {
      COMPLEXITY: {
        maxCyclomaticComplexity: 10,
        maxCognitiveComplexity: 15,
        maxFunctionLines: 20,
        maxNestingDepth: 3,
        maxParameters: 5
      },
      COUPLING: {
        maxDependencies: 7,
        maxFanOut: 5,
        preventCircularDeps: true
      },
      COHESION: {
        singleResponsibility: true,
        relatedFunctionsOnly: true
      },
      MAINTAINABILITY: {
        noMagicNumbers: true,
        consistentNaming: true,
        properErrorHandling: true,
        typesSafety: true
      },
      PERFORMANCE: {
        memoizeExpensiveCalc: true,
        lazyLoading: true,
        batchOperations: true
      }
    };
Behavior2/5

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

Annotations only provide a title ('Validate Code Quality'), which doesn't add behavioral information. The description doesn't disclose any behavioral traits beyond the vague action of validation. It doesn't mention what the tool actually does (e.g., returns a score, generates a report, flags issues), whether it's read-only or has side effects, performance characteristics, or error handling. For a tool with no informative annotations, this leaves the agent with minimal operational context.

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

Conciseness2/5

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

The description is a single run-on string of synonyms ('quality|review|check|quality|review code|check quality|validate|code review - Validate code quality') that is repetitive and poorly structured. It's not front-loaded with clear information; instead, it wastes space on redundant terms. While brief, this isn't effective conciseness—it's under-specification masked as brevity.

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?

Given the complexity of code quality validation (which could involve various analyses and outputs), the description is inadequate. There's no output schema, and the description doesn't explain what the tool returns (e.g., a report, scores, recommendations). With annotations providing only a title and no behavioral details, the description fails to compensate, leaving significant gaps in understanding how to use the tool effectively.

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 fully documents all parameters (code, type, strict, metrics) with descriptions and enums. The description adds no additional meaning about parameters beyond what's in the schema. According to scoring rules, when schema coverage is high (>80%), the baseline score is 3 even with no param info in the description, which applies here.

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

Purpose2/5

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

The description is a tautology that essentially restates the tool name 'validate_code_quality' with synonyms like 'review', 'check', and 'validate'. It doesn't specify what validation actually entails (e.g., static analysis, linting, metrics calculation) or what constitutes 'quality'. While it mentions 'code review', this is vague and doesn't clearly differentiate from sibling tools like 'suggest_improvements' or 'apply_quality_rules'.

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

Usage Guidelines1/5

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

There is no guidance on when to use this tool versus alternatives. The description doesn't mention any context, prerequisites, or exclusions. With many sibling tools related to code analysis (e.g., 'analyze_complexity', 'check_coupling_cohesion', 'suggest_improvements'), the lack of differentiation makes it unclear when this specific validation tool is appropriate.

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/ssdeanx/ssd-ai'

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