Skip to main content
Glama

analyze_complexity

Read-onlyIdempotent

Analyze code complexity by calculating cyclomatic, cognitive, and Halstead metrics to identify maintainability issues and optimization opportunities.

Instructions

복잡도|복잡한지|complexity|how complex|난이도 - Analyze code complexity

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYesCode to analyze
metricsNoMetrics to calculate

Implementation Reference

  • Main handler function implementing the analyze_complexity tool. Handles JS/TS complexity analysis (cyclomatic, cognitive, Halstead) and delegates Python to PythonParser.
    export async function analyzeComplexity(args: { code: string; metrics?: string }): Promise<ToolResult> {
      const { code: complexityCode, metrics: complexityMetrics = 'all' } = args;
    
      // Check if this is Python code
      if (PythonParser.isPythonCode(complexityCode)) {
        return analyzePythonComplexity(complexityCode);
      }
    
      const complexityAnalysis = {
        action: 'analyze_complexity',
        metrics: complexityMetrics,
        results: {} as any,
        overallScore: 0,
        issues: [] as string[],
        recommendations: [] as string[],
        status: 'pending' as string
      };
    
      // AST 기반 cyclomatic complexity 분석
      complexityAnalysis.results.astCyclomaticComplexity = calculateAstComplexity(complexityCode);
      
      if (complexityMetrics === 'cyclomatic' || complexityMetrics === 'all') {
        const cyclomaticComplexityScore = (complexityCode.match(/\bif\b|\bfor\b|\bwhile\b|\bcase\b|\b&&\b|\b\|\|\b/g) || []).length + 1;
        complexityAnalysis.results.cyclomaticComplexity = {
          value: cyclomaticComplexityScore,
          threshold: CODE_QUALITY_METRICS.COMPLEXITY.maxCyclomaticComplexity,
          status: cyclomaticComplexityScore <= CODE_QUALITY_METRICS.COMPLEXITY.maxCyclomaticComplexity ? 'pass' : 'fail',
          description: 'Number of linearly independent paths through the code'
        };
      }
      
      if (complexityMetrics === 'cognitive' || complexityMetrics === 'all') {
        complexityAnalysis.results.cognitiveComplexity = calculateCognitiveComplexity(complexityCode);
      }
      
      if (complexityMetrics === 'halstead' || complexityMetrics === 'all') {
        // Halstead metrics calculation (simplified version)
        const operators = (complexityCode.match(/[+\-*/=<>!&|%^~?:]/g) || []).length;
        const operands = (complexityCode.match(/\b[a-zA-Z_]\w*\b/g) || []).length;
        const uniqueOperators = new Set(complexityCode.match(/[+\-*/=<>!&|%^~?:]/g) || []).size;
        const uniqueOperands = new Set(complexityCode.match(/\b[a-zA-Z_]\w*\b/g) || []).size;
        
        const vocabulary = uniqueOperators + uniqueOperands;
        const length = operators + operands;
        const calculatedLength = vocabulary > 0 ? uniqueOperators * Math.log2(uniqueOperators) + uniqueOperands * Math.log2(uniqueOperands) : 0;
        const volume = length * Math.log2(vocabulary);
        const difficulty = vocabulary > 0 ? (uniqueOperators / 2) * (operands / uniqueOperands) : 0;
        const effort = difficulty * volume;
        
        complexityAnalysis.results.halsteadMetrics = {
          vocabulary: vocabulary,
          length: length,
          calculatedLength: Math.round(calculatedLength),
          volume: Math.round(volume),
          difficulty: Math.round(difficulty * 100) / 100,
          effort: Math.round(effort),
          timeToProgram: Math.round(effort / 18), // Halstead's formula: effort / 18 seconds
          bugsDelivered: Math.round(volume / 3000 * 100) / 100, // Halstead's formula: volume / 3000
          description: 'Software science metrics measuring program complexity'
        };
      }
      
      // Additional complexity metrics
      if (complexityMetrics === 'all') {
        const lines = complexityCode.split('\n');
        const nonEmptyLines = lines.filter(line => line.trim().length > 0).length;
        const comments = (complexityCode.match(/\/\*[\s\S]*?\*\/|\/\/.*$/gm) || []).length;
        const functions = (complexityCode.match(/function\s+\w+|\w+\s*=\s*\(/g) || []).length;
        const classes = (complexityCode.match(/class\s+\w+/g) || []).length;
        
        complexityAnalysis.results.additionalMetrics = {
          linesOfCode: nonEmptyLines,
          comments: comments,
          commentRatio: nonEmptyLines > 0 ? Math.round((comments / nonEmptyLines) * 100) / 100 : 0,
          functions: functions,
          classes: classes,
          averageFunctionLength: functions > 0 ? Math.round(nonEmptyLines / functions) : 0
        };
      }
      
      // Overall assessment
      const issues = [];
      let overallScore = 100;
      
      if (complexityAnalysis.results.cyclomaticComplexity && complexityAnalysis.results.cyclomaticComplexity.status === 'fail') {
        issues.push('High cyclomatic complexity detected');
        overallScore -= 20;
      }
      
      if (complexityAnalysis.results.cognitiveComplexity && complexityAnalysis.results.cognitiveComplexity.status === 'fail') {
        issues.push('High cognitive complexity detected');
        overallScore -= 25;
      }
      
      if (complexityAnalysis.results.halsteadMetrics && complexityAnalysis.results.halsteadMetrics.difficulty > 10) {
        issues.push('High Halstead difficulty detected');
        overallScore -= 15;
      }
      
      complexityAnalysis.overallScore = Math.max(0, overallScore);
      complexityAnalysis.issues = issues;
    
      return {
        content: [{
          type: 'text',
          text: `Complexity: ${complexityAnalysis.results.astCyclomaticComplexity?.value ?? 'N/A'}\nScore: ${complexityAnalysis.overallScore}${issues.length ? '\nIssues: ' + issues.join(', ') : ''}`
        }]
      };
    }
  • Input schema and ToolDefinition for the analyze_complexity tool.
    export const analyzeComplexityDefinition: ToolDefinition = {
      name: 'analyze_complexity',
      description: '복잡도|복잡한지|complexity|how complex|난이도 - Analyze code complexity',
      inputSchema: {
        type: 'object',
        properties: {
          code: { type: 'string', description: 'Code to analyze' },
          metrics: { type: 'string', description: 'Metrics to calculate', enum: ['cyclomatic', 'cognitive', 'halstead', 'all'] }
        },
        required: ['code']
      },
      annotations: {
        title: 'Analyze Complexity',
        audience: ['user', 'assistant'],
        readOnlyHint: true,
        destructiveHint: false,
        idempotentHint: true,
        openWorldHint: false
      }
    };
  • src/index.ts:183-188 (registration)
    Registration of the analyze_complexity handler in the toolHandlers dispatch map.
    'get_coding_guide': getCodingGuide,
    'apply_quality_rules': applyQualityRules,
    'validate_code_quality': validateCodeQuality,
    'analyze_complexity': analyzeComplexity,
    'check_coupling_cohesion': checkCouplingCohesion,
    'suggest_improvements': suggestImprovements,
  • src/index.ts:119-124 (registration)
    Registration of the analyzeComplexityDefinition in the tools list for MCP listTools endpoint.
    applyQualityRulesDefinition,
    validateCodeQualityDefinition,
    analyzeComplexityDefinition,
    checkCouplingCohesionDefinition,
    suggestImprovementsDefinition,
  • Helper method in PythonParser used for Python code complexity analysis, called from the main handler.
    public static async analyzeComplexity(code: string): Promise<PythonComplexity> {
      const result = await this.executePython(code, 'complexity');
      return {
        cyclomaticComplexity: result.cyclomaticComplexity || 1,
        functions: result.functions || [],
        classes: result.classes || []
      };
    }
Behavior4/5

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

Annotations provide readOnlyHint=true, destructiveHint=false, idempotentHint=true, and openWorldHint=false, indicating a safe, non-destructive, repeatable operation with closed-world behavior. The description adds no behavioral traits beyond this, but since annotations are comprehensive, the bar is lower. There's no contradiction with annotations, and the description doesn't mislead, so it earns a baseline score for not detracting from the structured data.

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 brief but inefficiently structured with redundant terms ('복잡도|복잡한지|complexity|how complex|난이도'), which adds noise without clarity. It's front-loaded but could be more concise by eliminating repetition. The single sentence earns some points for brevity but loses for wastefulness.

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 (2 parameters, 1 required), rich annotations (covering safety and behavior), and no output schema, the description is minimally complete. It states the purpose but lacks details on output format or usage context. With annotations handling behavioral aspects, it's adequate but could better address gaps like result interpretation.

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%, with clear descriptions for both parameters ('code' and 'metrics' with enum values). The description adds no meaning beyond the schema, as it doesn't explain parameter usage or semantics. With high schema coverage, the baseline is 3, reflecting adequate but no extra value from the description.

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

Purpose3/5

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

The description states the tool analyzes code complexity, which is a clear purpose, but it's somewhat vague with repetitive phrasing ('복잡도|복잡한지|complexity|how complex|난이도'). It doesn't explicitly differentiate from sibling tools like 'analyze_problem' or 'validate_code_quality', though the title 'Analyze Complexity' helps. The verb 'analyze' is specific, but the resource 'code complexity' could be more precise.

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?

No guidance is provided on when to use this tool versus alternatives. The description does not mention sibling tools like 'analyze_problem' or 'validate_code_quality', nor does it specify contexts or exclusions for its use. Usage is implied by the name and description but not explicitly stated.

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/su-record/hi-ai'

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