Skip to main content
Glama

suggest_refactoring

Analyze code to suggest refactoring improvements for readability, performance, and maintainability using project-specific patterns for single or multiple files.

Instructions

Analyze code and suggest refactoring improvements with project-specific patterns (handles both single and multi-file)

WORKFLOW: Ideal for creating production-ready code, tests, and documentation TIP: Generate unlimited iterations locally, then review with Claude SAVES: Claude context for strategic decisions

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
analysisDepthNoLevel of analysis detaildetailed
analysisTypeNoType of refactoring to focus oncomprehensive
codeNoThe code to analyze for refactoring (for single-file analysis)
contextNoOptional context for project-specific refactoring
filePathNoPath to single file to refactor
filesNoArray of specific file paths (for multi-file analysis)
focusAreasNoAreas to focus on for refactoring
languageNoProgramming languagejavascript
maxDepthNoMaximum directory depth for multi-file discovery (1-5)
projectPathNoPath to project root (for multi-file refactoring analysis)

Implementation Reference

  • Primary handler function that orchestrates the suggest_refactoring tool execution: detects analysis mode (single/multi-file), validates inputs, sets up LLM model, routes to specialized analysis, and handles errors.
    async execute(params: any, llmClient: any) {
      return await withSecurity(this, params, llmClient, async (secureParams) => {
        try {
          // 1. Auto-detect analysis mode based on parameters
          const analysisMode = this.detectAnalysisMode(secureParams);
          
          // 2. Validate parameters based on detected mode
          this.validateParameters(secureParams, analysisMode);
          
          // 3. Setup model
          const { model, contextLength } = await ModelSetup.getReadyModel(llmClient);
          
          // 4. Route to appropriate analysis method
          if (analysisMode === 'single-file') {
            return await this.executeSingleFileAnalysis(secureParams, model, contextLength);
          } else {
            return await this.executeMultiFileAnalysis(secureParams, model, contextLength);
          }
          
        } catch (error: any) {
          return ErrorHandler.createExecutionError('suggest_refactoring', error);
        }
      });
    }
  • Input schema definition for the suggest_refactoring tool, supporting both single-file and multi-file analysis modes with parameters like code, filePath, projectPath, focusAreas, etc.
    parameters = {
      // Single-file parameters
      code: {
        type: 'string' as const,
        description: 'The code to analyze for refactoring (for single-file analysis)',
        required: false
      },
      filePath: {
        type: 'string' as const,
        description: 'Path to single file to refactor',
        required: false
      },
      
      // Multi-file parameters  
      projectPath: {
        type: 'string' as const,
        description: 'Path to project root (for multi-file refactoring analysis)',
        required: false
      },
      files: {
        type: 'array' as const,
        description: 'Array of specific file paths (for multi-file analysis)',
        required: false,
        items: { type: 'string' as const }
      },
      maxDepth: {
        type: 'number' as const,
        description: 'Maximum directory depth for multi-file discovery (1-5)',
        required: false,
        default: 3
      },
      
      // Universal parameters
      language: {
        type: 'string' as const,
        description: 'Programming language',
        required: false,
        default: 'javascript'
      },
      analysisDepth: {
        type: 'string' as const,
        description: 'Level of analysis detail',
        enum: ['basic', 'detailed', 'comprehensive'],
        default: 'detailed',
        required: false
      },
      analysisType: {
        type: 'string' as const,
        description: 'Type of refactoring to focus on',
        enum: ['readability', 'performance', 'comprehensive'],
        default: 'comprehensive',
        required: false
      },
      
      // Refactoring-specific parameters
      focusAreas: {
        type: 'array' as const,
        description: 'Areas to focus on for refactoring',
        required: false,
        items: {
          type: 'string' as const,
          enum: ['readability', 'performance', 'maintainability', 'testability', 'security', 'type-safety', 'error-handling', 'logging', 'documentation']
        },
        default: ['readability', 'maintainability']
      },
      context: {
        type: 'object' as const,
        description: 'Optional context for project-specific refactoring',
        required: false,
        properties: {
          projectType: {
            type: 'string' as const,
            enum: ['wordpress-plugin', 'wordpress-theme', 'react-app', 'react-component', 'node-api', 'n8n-node', 'n8n-workflow', 'html-component', 'browser-extension', 'cli-tool', 'generic'],
            description: 'Project type for appropriate patterns'
          },
          preserveApi: {
            type: 'boolean' as const,
            description: 'Maintain backward compatibility',
            default: true
          },
          modernizationLevel: {
            type: 'string' as const,
            enum: ['conservative', 'moderate', 'aggressive'],
            description: 'How aggressively to modernize code',
            default: 'moderate'
          },
          targetComplexity: {
            type: 'number' as const,
            description: 'Target cyclomatic complexity',
            default: 10
          },
          standards: {
            type: 'array' as const,
            items: { type: 'string' as const },
            description: 'Coding standards to follow'
          }
        }
      }
    };
  • Output schema (SuggestRefactoringResponse) defining the structured response format for the tool.
    export interface SuggestRefactoringResponse extends BaseResponse {
      data: {
        suggestions: Array<{
          type: string;
          priority: "high" | "medium" | "low";
          location: { start: number; end: number };
          description: string;
          before: string;
          after: string;
          benefits: string[];
          risks?: string[];
        }>;
        metrics: {
          currentComplexity: number;
          targetComplexity: number;
          improvementScore: number;
        };
        refactoredCode?: string;
      };
    }
  • Tool registration via the 'name' property in the plugin class, used by the dynamic plugin loader.
    export class RefactoringAnalyzer extends BasePlugin implements IPromptPlugin {
      name = 'suggest_refactoring';
  • Dynamic registration logic in PluginLoader.registerPlugin(), which registers plugins by their 'name' in maps for lookup and execution.
    registerPlugin(plugin: IPromptPlugin): void {
      // Validate plugin has required properties
      if (!plugin.name || !plugin.category || !plugin.execute) {
        throw new Error('Invalid plugin: missing required properties');
      }
      
      // Register in main map
      this.plugins.set(plugin.name, plugin);
      
      // Register in category map
      const categoryPlugins = this.categories.get(plugin.category) || [];
      categoryPlugins.push(plugin);
      this.categories.set(plugin.category, categoryPlugins);
    }

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/houtini-ai/lm'

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