Skip to main content
Glama
renjismzy

Smart Code Reviewer

by renjismzy

calculate_complexity

Analyze code complexity metrics like cyclomatic and cognitive complexity to identify maintainability issues and refactoring opportunities in multiple programming languages.

Instructions

计算代码复杂度指标(圈复杂度、认知复杂度等)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYes要分析的代码
languageYes编程语言

Implementation Reference

  • Core implementation of the calculate_complexity tool: computes cyclomatic complexity, cognitive complexity, Halstead metrics, maintainability index, and provides analysis, recommendations, and risk level.
    export async function calculateComplexity(
      code: string,
      language: string
    ): Promise<ComplexityResult> {
      const metrics: ComplexityMetrics = {
        cyclomaticComplexity: 0,
        cognitiveComplexity: 0,
        halsteadComplexity: {
          vocabulary: 0,
          length: 0,
          difficulty: 0,
          effort: 0,
          volume: 0,
          bugs: 0,
          time: 0
        },
        maintainabilityIndex: 0,
        linesOfCode: 0,
        logicalLinesOfCode: 0,
        commentLines: 0,
        blankLines: 0
      };
    
      // 基础指标计算
      calculateBasicMetrics(code, metrics);
      
      // 圈复杂度计算
      metrics.cyclomaticComplexity = calculateCyclomaticComplexity(code, language);
      
      // 认知复杂度计算
      metrics.cognitiveComplexity = calculateCognitiveComplexity(code, language);
      
      // Halstead复杂度计算
      metrics.halsteadComplexity = calculateHalsteadComplexity(code, language);
      
      // 可维护性指数计算
      metrics.maintainabilityIndex = calculateMaintainabilityIndex(metrics);
      
      return {
        language,
        metrics,
        analysis: analyzeComplexity(metrics),
        recommendations: generateComplexityRecommendations(metrics),
        riskLevel: assessRiskLevel(metrics)
      };
    }
  • MCP tool handler wrapper: validates input arguments using Zod and delegates to the core calculateComplexity function, formats result as MCP content.
    private async handleCalculateComplexity(args: any) {
      const schema = z.object({
        code: z.string(),
        language: z.string()
      });
    
      const { code, language } = schema.parse(args);
      const result = await calculateComplexity(code, language);
    
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2)
          }
        ]
      };
    }
  • src/index.ts:130-147 (registration)
    Tool registration in MCP server's listTools handler: defines name, description, and JSON input schema for calculate_complexity.
    {
      name: 'calculate_complexity',
      description: '计算代码复杂度指标(圈复杂度、认知复杂度等)',
      inputSchema: {
        type: 'object',
        properties: {
          code: {
            type: 'string',
            description: '要分析的代码'
          },
          language: {
            type: 'string',
            description: '编程语言'
          }
        },
        required: ['code', 'language']
      }
    }
  • TypeScript interfaces defining the output structure (ComplexityResult, ComplexityMetrics, HalsteadMetrics) used by the tool.
    export interface ComplexityResult {
      language: string;
      metrics: ComplexityMetrics;
      analysis: string;
      recommendations: string[];
      riskLevel: 'low' | 'medium' | 'high' | 'critical';
    }
    
    export interface ComplexityMetrics {
      cyclomaticComplexity: number;
      cognitiveComplexity: number;
      halsteadComplexity: HalsteadMetrics;
      maintainabilityIndex: number;
      linesOfCode: number;
      logicalLinesOfCode: number;
      commentLines: number;
      blankLines: number;
    }
    
    export interface HalsteadMetrics {
      vocabulary: number;
      length: number;
      difficulty: number;
      volume: number;
      effort: number;
      bugs: number;
      time: number;
    }
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 states what the tool does but lacks details on behavioral traits: it doesn't specify if this is a read-only analysis, what the output format might be (since no output schema exists), potential performance implications, or error handling. For a tool with no annotations, this leaves significant gaps in understanding its operation.

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 extremely concise—a single sentence in Chinese that directly states the tool's purpose without any fluff. It's front-loaded with the core action and resource, making it efficient and easy to parse. Every word earns its place by specifying the metrics involved.

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 calculating code complexity metrics, the description is incomplete. There are no annotations to clarify behavior, no output schema to explain return values, and the description doesn't address what the tool outputs or how it handles different languages or code structures. For a tool with 2 parameters and no structured support, more context is needed to guide effective use.

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?

The input schema has 100% description coverage, with clear documentation for both parameters ('code' and 'language'). The description doesn't add any semantic details beyond what the schema provides (e.g., it doesn't explain what '圈复杂度' or '认知复杂度' entail in terms of input requirements). With high schema coverage, the baseline score of 3 is appropriate as the description doesn't compensate or enhance parameter understanding.

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: '计算代码复杂度指标(圈复杂度、认知复杂度等)' (calculate code complexity metrics like cyclomatic complexity, cognitive complexity, etc.). It specifies the verb '计算' (calculate) and the resource '代码复杂度指标' (code complexity metrics). However, it doesn't explicitly differentiate from sibling tools like 'analyze_code_quality' or 'suggest_refactoring', which might also involve complexity analysis.

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. It doesn't mention sibling tools or contexts where this tool is preferred over others (e.g., 'analyze_code_quality' might include complexity as part of broader analysis). There's no indication of prerequisites, exclusions, or specific scenarios for usage.

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/renjismzy/mcp-code'

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