Skip to main content
Glama
emmron
by emmron

mcp__gemini__refactor_genius

Refactor code intelligently with automated testing, safety validation, and rollback capabilities. Enhance code readability, maintainability, and performance while ensuring high safety standards.

Instructions

Intelligent code refactoring with automated testing, rollback capabilities, and safety validation

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYesCode to refactor
generate_testsNoGenerate test cases
languageNoProgramming languagejavascript
refactor_goalsNoRefactoring goals
rollback_planNoCreate rollback plan
safety_levelNoSafety levelhigh

Implementation Reference

  • The async handler function implementing the core logic of the 'mcp__gemini__refactor_genius' tool. It destructures input args, performs safety analysis via AI, generates refactoring plan and code, optionally creates tests and rollback strategy using multiple AI client calls, and returns a formatted result with all sections.
        handler: async (args) => {
          const { code, language = 'javascript', refactor_goals = ['readability', 'maintainability', 'performance'], safety_level = 'high', generate_tests = true, rollback_plan = true } = args;
          validateString(code, 'code', 15000);
          
          const timer = performanceMonitor.startTimer('refactor_genius');
          
          const goals = Array.isArray(refactor_goals) ? refactor_goals : [refactor_goals];
          
          // Safety analysis first
          const safetyPrompt = `Analyze this ${language} code for refactoring safety:
    
    \`\`\`${language}
    ${code}
    \`\`\`
    
    Assess:
    1. **Refactoring Safety Score** (1-10, where 10 is safest)
    2. **Risk Factors** that could break functionality
    3. **Critical Dependencies** that must be preserved
    4. **External Interfaces** that cannot change
    5. **Hidden Coupling** that might be affected
    6. **Complexity Hotspots** requiring careful handling
    
    Safety Level Required: ${safety_level}
    
    Provide safety assessment and recommendations.`;
    
          const safetyAnalysis = await aiClient.call(safetyPrompt, 'review');
          
          // Main refactoring analysis
          const refactorPrompt = `Perform intelligent refactoring for this ${language} code:
    
    \`\`\`${language}
    ${code}
    \`\`\`
    
    **Goals**: ${goals.join(', ')}
    **Safety Level**: ${safety_level}
    
    Provide:
    1. **Refactoring Plan**
       - Step-by-step refactoring approach
       - Order of operations for safety
       - Risk mitigation at each step
    
    2. **Refactored Code**
       - Complete refactored implementation
       - Preserve all functionality
       - Maintain external interfaces
    
    3. **Improvement Analysis**
       - Before/after comparison
       - Quantified improvements
       - Goal achievement assessment
    
    4. **Change Summary**
       - What was changed and why
       - Performance implications
       - Maintainability improvements
    
    ${safety_level === 'high' ? 'Apply conservative refactoring with maximum safety guarantees.' : ''}`;
    
          const refactorAnalysis = await aiClient.call(refactorPrompt, 'coding', { 
            complexity: 'complex',
            maxTokens: 4000 
          });
          
          let result = `โ™ป๏ธ **Refactor Genius** (${language})
    
    **Goals**: ${goals.join(', ')}
    **Safety Level**: ${safety_level}
    
    ---
    
    ๐Ÿ›ก๏ธ **Safety Analysis**
    
    ${safetyAnalysis}
    
    ---
    
    ๐Ÿ”ง **Refactoring Implementation**
    
    ${refactorAnalysis}`;
    
          // Generate test cases if requested
          if (generate_tests) {
            const testPrompt = `Generate comprehensive test cases for this refactoring:
    
    **Original Code:**
    \`\`\`${language}
    ${code}
    \`\`\`
    
    **Refactored Code:** (from analysis above)
    
    Create:
    1. **Unit Tests** for individual functions/methods
    2. **Integration Tests** for component interactions
    3. **Regression Tests** to ensure no functionality breaks
    4. **Performance Tests** to validate improvements
    5. **Edge Case Tests** for boundary conditions
    
    Use appropriate testing framework for ${language}.
    Focus on verifying that refactored code behaves identically to original.`;
    
            const testCases = await aiClient.call(testPrompt, 'testing');
            
            result += `
    
    ---
    
    ๐Ÿงช **Test Suite**
    
    ${testCases}`;
          }
    
          // Create rollback plan if requested
          if (rollback_plan) {
            const rollbackPrompt = `Create a rollback plan for this refactoring:
    
    **Original Code:**
    \`\`\`${language}
    ${code}
    \`\`\`
    
    Provide:
    1. **Rollback Strategy**
       - Step-by-step rollback process
       - Recovery checkpoints
       - Validation steps
    
    2. **Risk Mitigation**
       - What could go wrong
       - Early warning signs
       - Emergency procedures
    
    3. **Monitoring Plan**
       - Key metrics to watch
       - Performance indicators
       - Alert thresholds
    
    4. **Backup Recommendations**
       - What to backup before refactoring
       - Version control strategy
       - Documentation requirements`;
    
            const rollbackStrategy = await aiClient.call(rollbackPrompt, 'analysis');
            
            result += `
    
    ---
    
    ๐Ÿ”„ **Rollback Plan**
    
    ${rollbackStrategy}`;
          }
          
          timer.end();
          return result;
        }
  • Input schema defining the parameters for the tool, including required 'code' string, optional language, array of refactor_goals, safety_level, and booleans for generating tests and rollback plan.
    parameters: {
      code: { type: 'string', description: 'Code to refactor', required: true },
      language: { type: 'string', description: 'Programming language', default: 'javascript' },
      refactor_goals: { type: 'array', description: 'Refactoring goals', default: ['readability', 'maintainability', 'performance'] },
      safety_level: { type: 'string', description: 'Safety level', default: 'high' },
      generate_tests: { type: 'boolean', description: 'Generate test cases', default: true },
      rollback_plan: { type: 'boolean', description: 'Create rollback plan', default: true }
    },
  • Registration block in ToolRegistry where the enhancedTools module (containing 'mcp__gemini__refactor_genius') is registered via registerToolsFromModule(enhancedTools), which iterates over all tools in the module and calls registerTool for each.
    this.registerToolsFromModule(codeTools);
    this.registerToolsFromModule(analysisTools);
    this.registerToolsFromModule(enhancedTools);
    this.registerToolsFromModule(businessTools);
    this.registerToolsFromModule(licenseTools);
Behavior2/5

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

With no annotations, the description carries full burden but only lists capabilities without detailing behavioral traits. It mentions 'automated testing, rollback capabilities, and safety validation' but doesn't explain how these work, what 'safety validation' entails, or any limitations like computational cost or error handling.

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?

Extremely concise single sentence with no wasted words, front-loading the core purpose ('Intelligent code refactoring') followed by key features. Every phrase adds value.

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?

For a complex refactoring tool with 6 parameters, no annotations, and no output schema, the description is insufficient. It lacks details on behavioral traits, output format, error conditions, and how the listed capabilities interact, leaving significant gaps for agent understanding.

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 6 parameters. The description adds no parameter-specific information beyond the tool's general purpose, maintaining the baseline score of 3.

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 'Intelligent code refactoring' with specific capabilities (automated testing, rollback, safety validation). It distinguishes from sibling tools like 'refactor_suggestions' by implying more comprehensive functionality, though not explicitly contrasting them.

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 on when to use this tool versus alternatives like 'refactor_suggestions' or 'code_analyze'. The description implies it's for refactoring with safety features but doesn't specify scenarios, prerequisites, or exclusions.

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

Related 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/emmron/gemini-mcp'

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