Skip to main content
Glama
renjismzy

Smart Code Reviewer

by renjismzy

suggest_refactoring

Analyzes code to provide refactoring suggestions that improve structure, readability, and maintainability for cleaner, more efficient programming.

Instructions

提供代码重构建议,改善代码结构和可读性

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYes要重构的代码
languageYes编程语言
focusNo重构重点

Implementation Reference

  • Core handler function `suggestRefactoring` that orchestrates analysis for performance, readability, maintainability, and language-specific refactoring suggestions, generating prioritized suggestions.
    export async function suggestRefactoring(
      code: string,
      language: string,
      focus: 'performance' | 'readability' | 'maintainability' | 'all' = 'all'
    ): Promise<RefactoringResult> {
      const suggestions: RefactoringSuggestion[] = [];
      
      // 根据重构重点进行分析
      if (focus === 'all' || focus === 'performance') {
        await analyzePerformanceIssues(code, language, suggestions);
      }
      
      if (focus === 'all' || focus === 'readability') {
        await analyzeReadabilityIssues(code, language, suggestions);
      }
      
      if (focus === 'all' || focus === 'maintainability') {
        await analyzeMaintainabilityIssues(code, language, suggestions);
      }
      
      // 语言特定重构建议
      switch (language.toLowerCase()) {
        case 'javascript':
        case 'typescript':
          await analyzeJavaScriptRefactoring(code, suggestions);
          break;
        case 'python':
          await analyzePythonRefactoring(code, suggestions);
          break;
        case 'java':
          await analyzeJavaRefactoring(code, suggestions);
          break;
      }
      
      // 按优先级排序
      suggestions.sort((a, b) => {
        const priorityOrder = { 'high': 3, 'medium': 2, 'low': 1 };
        return priorityOrder[b.priority] - priorityOrder[a.priority];
      });
      
      return {
        language,
        focus,
        totalSuggestions: suggestions.length,
        highPriority: suggestions.filter(s => s.priority === 'high').length,
        mediumPriority: suggestions.filter(s => s.priority === 'medium').length,
        lowPriority: suggestions.filter(s => s.priority === 'low').length,
        suggestions,
        summary: generateRefactoringSummary(suggestions, focus)
      };
    }
  • TypeScript interfaces defining the input/output structure for refactoring results: RefactoringResult and RefactoringSuggestion.
    export interface RefactoringResult {
      language: string;
      focus: 'performance' | 'readability' | 'maintainability' | 'all';
      totalSuggestions: number;
      highPriority: number;
      mediumPriority: number;
      lowPriority: number;
      suggestions: RefactoringSuggestion[];
      summary: string;
    }
    
    export interface RefactoringSuggestion {
      type: 'performance' | 'readability' | 'maintainability' | 'modernization' | 'pythonic';
      priority: 'high' | 'medium' | 'low';
      title: string;
      description: string;
      line: number;
      originalCode: string;
      suggestedCode: string;
      impact: string;
      effort: 'low' | 'medium' | 'high';
    }
  • src/index.ts:107-129 (registration)
    MCP tool registration in the server's listTools handler, specifying name, description, and JSON schema for input parameters.
    {
      name: 'suggest_refactoring',
      description: '提供代码重构建议,改善代码结构和可读性',
      inputSchema: {
        type: 'object',
        properties: {
          code: {
            type: 'string',
            description: '要重构的代码'
          },
          language: {
            type: 'string',
            description: '编程语言'
          },
          focus: {
            type: 'string',
            enum: ['performance', 'readability', 'maintainability', 'all'],
            description: '重构重点'
          }
        },
        required: ['code', 'language']
      }
    },
  • Server-side wrapper handler that validates tool arguments with Zod schema and invokes the core suggestRefactoring function, formatting response for MCP protocol.
    private async handleSuggestRefactoring(args: any) {
      const schema = z.object({
        code: z.string(),
        language: z.string(),
        focus: z.enum(['performance', 'readability', 'maintainability', 'all']).default('all')
      });
    
      const { code, language, focus } = schema.parse(args);
      const result = await suggestRefactoring(code, language, focus);
    
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2)
          }
        ]
      };
    }
  • Helper function for performance analysis, one of several specialized analyzers called by the main handler.
    async function analyzePerformanceIssues(
      code: string,
      language: string,
      suggestions: RefactoringSuggestion[]
    ): Promise<void> {
      const lines = code.split('\n');
      
      lines.forEach((line, index) => {
        const lineNumber = index + 1;
        const trimmedLine = line.trim();
        
        // 检测循环中的重复计算
        if (isInLoop(lines, index) && hasExpensiveOperation(trimmedLine)) {
          suggestions.push({
            type: 'performance',
            priority: 'high',
            title: '循环中的重复计算',
            description: '在循环中发现可能的重复计算,建议提取到循环外部',
            line: lineNumber,
            originalCode: line,
            suggestedCode: optimizeLoopCalculation(line, language),
            impact: '可显著提升性能,特别是在大数据集处理时',
            effort: 'low'
          });
        }
        
        // 检测字符串拼接性能问题
        if (hasInefficiientStringConcatenation(trimmedLine, language)) {
          suggestions.push({
            type: 'performance',
            priority: 'medium',
            title: '低效的字符串拼接',
            description: '使用更高效的字符串拼接方法',
            line: lineNumber,
            originalCode: line,
            suggestedCode: optimizeStringConcatenation(line, language),
            impact: '在大量字符串操作时可提升性能',
            effort: 'low'
          });
        }
        
        // 检测不必要的对象创建
        if (hasUnnecessaryObjectCreation(trimmedLine, language)) {
          suggestions.push({
            type: 'performance',
            priority: 'medium',
            title: '不必要的对象创建',
            description: '减少不必要的对象创建以降低内存压力',
            line: lineNumber,
            originalCode: line,
            suggestedCode: optimizeObjectCreation(line, language),
            impact: '减少内存使用和垃圾回收压力',
            effort: 'medium'
          });
        }
        
        // 检测低效的数组操作
        if (hasInefficientArrayOperation(trimmedLine, language)) {
          suggestions.push({
            type: 'performance',
            priority: 'medium',
            title: '低效的数组操作',
            description: '使用更高效的数组操作方法',
            line: lineNumber,
            originalCode: line,
            suggestedCode: optimizeArrayOperation(line, language),
            impact: '在处理大数组时可显著提升性能',
            effort: 'low'
          });
        }
      });
    }
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 the tool provides suggestions to improve code structure and readability, implying a read-only, advisory function. However, it lacks details on critical behaviors: whether it modifies code, requires specific permissions, has rate limits, returns structured advice or examples, or handles errors. For a tool with no annotations, 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.

Conciseness5/5

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

The description is extremely concise and front-loaded: a single sentence in Chinese that directly states the tool's purpose. There's no wasted language or redundancy, making it easy for an agent to parse quickly. Every word earns its place by defining the core function without unnecessary elaboration.

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 a code refactoring tool with no annotations and no output schema, the description is incomplete. It doesn't explain what the output looks like (e.g., suggestions, examples, scores), behavioral traits like safety or limitations, or how it differs from siblings. For a tool that likely provides nuanced advice, more context is needed to help the agent use it 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?

The schema description coverage is 100%, with clear descriptions for all parameters ('code', 'language', 'focus'), including an enum for 'focus'. The description adds no additional semantic information beyond what's in the schema—it doesn't explain parameter interactions, default behaviors, or examples. Given the high schema coverage, the baseline score of 3 is appropriate, as the description doesn't compensate but also doesn't detract.

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: '提供代码重构建议,改善代码结构和可读性' (Provide code refactoring suggestions to improve code structure and readability). It specifies the verb '提供建议' (provide suggestions) and the resource '代码' (code), with the goal of improving structure and readability. However, it doesn't explicitly distinguish this from sibling tools like 'analyze_code_quality' or 'generate_documentation', which might have overlapping purposes.

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 like 'analyze_code_quality' (which might analyze without suggesting refactoring) or 'generate_documentation' (which focuses on documentation). There's no context on prerequisites, limitations, or specific scenarios where this tool is preferred over others, leaving the agent to infer usage from the purpose alone.

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