Skip to main content
Glama

suggest_improvements

Analyze code to suggest improvements for performance, readability, maintainability, accessibility, or type-safety based on specified priority levels.

Instructions

improve|make better|refactoring|improve|make better|refactor|optimize|enhance code - Suggest improvements

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYesCode to analyze
focusNoFocus area
priorityNoPriority level

Implementation Reference

  • The core handler function that performs static code analysis across multiple categories (performance, readability, maintainability, type-safety, accessibility) and generates prioritized improvement suggestions.
    export async function suggestImprovements(args: { code: string; focus?: string; priority?: string }): Promise<ToolResult> {
      const { code, focus = 'maintainability', priority = 'medium' } = args;
      
      const suggestions = [];
      const codeLines = code.split('\n');
      const codeLength = codeLines.length;
      
      // Performance improvements
      if (focus === 'performance' || focus === 'all') {
        // Check for inefficient loops
        if (code.includes('for') && code.includes('length')) {
          suggestions.push({
            category: 'performance',
            priority: 'high',
            issue: 'Potential inefficient loop accessing .length property',
            suggestion: 'Cache array length in a variable before the loop',
            example: 'const len = array.length; for (let i = 0; i < len; i++)'
          });
        }
        
        // Check for React performance issues
        if (code.includes('React') || code.includes('jsx') || code.includes('tsx')) {
          if (!code.includes('memo') && !code.includes('useMemo') && !code.includes('useCallback')) {
            suggestions.push({
              category: 'performance',
              priority: 'medium',
              issue: 'Missing React performance optimizations',
              suggestion: 'Consider using React.memo, useMemo, or useCallback',
              example: 'const Component = React.memo(() => { ... })'
            });
          }
          
          if (code.includes('map') && code.includes('return')) {
            suggestions.push({
              category: 'performance',
              priority: 'medium',
              issue: 'Ensure unique keys in map functions',
              suggestion: 'Use unique and stable keys for list items',
              example: 'items.map(item => <div key={item.id}>{item.name}</div>)'
            });
          }
        }
        
        // Check for expensive operations
        if (code.includes('JSON.parse') || code.includes('JSON.stringify')) {
          suggestions.push({
            category: 'performance',
            priority: 'medium',
            issue: 'JSON operations can be expensive',
            suggestion: 'Consider memoizing JSON operations or using alternatives',
            example: 'const memoizedParse = useMemo(() => JSON.parse(data), [data])'
          });
        }
      }
      
      // Readability improvements
      if (focus === 'readability' || focus === 'all') {
        // Check for long functions
        if (codeLength > 20) {
          suggestions.push({
            category: 'readability',
            priority: 'high',
            issue: `Function is too long (${codeLength} lines)`,
            suggestion: 'Break down into smaller, focused functions',
            example: 'Extract logical groups into separate functions'
          });
        }
        
        // Check for deep nesting
        let maxNesting = 0;
        let currentNesting = 0;
        for (const line of codeLines) {
          const braceCount = (line.match(/\{/g) || []).length - (line.match(/\}/g) || []).length;
          currentNesting += braceCount;
          maxNesting = Math.max(maxNesting, currentNesting);
        }
        
        if (maxNesting > 3) {
          suggestions.push({
            category: 'readability',
            priority: 'high',
            issue: `Deep nesting detected (${maxNesting} levels)`,
            suggestion: 'Use early returns or guard clauses to reduce nesting',
            example: 'if (!condition) return; // instead of wrapping in else'
          });
        }
        
        // Check for magic numbers
        const magicNumbers = code.match(/\b\d{2,}\b/g) || [];
        if (magicNumbers.length > 0) {
          suggestions.push({
            category: 'readability',
            priority: 'medium',
            issue: 'Magic numbers found in code',
            suggestion: 'Extract numbers into named constants',
            example: 'const MAX_RETRY_COUNT = 3; // instead of using 3 directly'
          });
        }
        
        // Check for unclear variable names
        const shortVars = code.match(/\b[a-z]\b/g) || [];
        if (shortVars.length > 2) {
          suggestions.push({
            category: 'readability',
            priority: 'medium',
            issue: 'Single letter variable names detected',
            suggestion: 'Use descriptive variable names',
            example: 'const userIndex = 0; // instead of i = 0'
          });
        }
      }
      
      // Maintainability improvements
      if (focus === 'maintainability' || focus === 'all') {
        // Check for error handling
        const hasAsyncCode = code.includes('async') || code.includes('await') || code.includes('Promise');
        const hasErrorHandling = code.includes('try') || code.includes('catch') || code.includes('throw');
        
        if (hasAsyncCode && !hasErrorHandling) {
          suggestions.push({
            category: 'maintainability',
            priority: 'high',
            issue: 'Async code without error handling',
            suggestion: 'Add try-catch blocks for async operations',
            example: 'try { await asyncOperation(); } catch (error) { handleError(error); }'
          });
        }
        
        // Check for code duplication
        const lines = codeLines.map(line => line.trim()).filter(line => line.length > 5);
        const duplicateLines = lines.filter((line, index) => lines.indexOf(line) !== index);
        if (duplicateLines.length > 0) {
          suggestions.push({
            category: 'maintainability',
            priority: 'medium',
            issue: 'Potential code duplication detected',
            suggestion: 'Extract common code into reusable functions',
            example: 'Create utility functions for repeated logic'
          });
        }
        
        // Check for comments
        const commentLines = code.match(/\/\*[\s\S]*?\*\/|\/\/.*$/gm) || [];
        const commentRatio = commentLines.length / codeLines.length;
        if (commentRatio < 0.1 && codeLength > 10) {
          suggestions.push({
            category: 'maintainability',
            priority: 'low',
            issue: 'Low comment-to-code ratio',
            suggestion: 'Add comments explaining complex logic',
            example: '// Validate user input before processing'
          });
        }
      }
      
      // Type safety improvements
      if (focus === 'type-safety' || focus === 'all') {
        // Check for any types
        if (code.includes('any')) {
          suggestions.push({
            category: 'type-safety',
            priority: 'high',
            issue: 'Using "any" type reduces type safety',
            suggestion: 'Use specific types or interfaces',
            example: 'interface User { id: string; name: string; }'
          });
        }
        
        // Check for loose equality
        if (code.includes('== ') || code.includes('!= ')) {
          suggestions.push({
            category: 'type-safety',
            priority: 'medium',
            issue: 'Loose equality operators found',
            suggestion: 'Use strict equality operators',
            example: 'Use === and !== instead of == and !='
          });
        }
        
        // Check for missing return types
        const functions = code.match(/function\s+\w+\([^)]*\)/g) || [];
        const functionsWithReturnType = code.match(/function\s+\w+\([^)]*\):\s*\w+/g) || [];
        if (functions.length > functionsWithReturnType.length) {
          suggestions.push({
            category: 'type-safety',
            priority: 'medium',
            issue: 'Functions missing explicit return types',
            suggestion: 'Add return type annotations',
            example: 'function getName(): string { return "name"; }'
          });
        }
      }
      
      // Accessibility improvements
      if (focus === 'accessibility' || focus === 'all') {
        // Check for missing alt text
        if (code.includes('<img') && !code.includes('alt=')) {
          suggestions.push({
            category: 'accessibility',
            priority: 'high',
            issue: 'Images without alt text',
            suggestion: 'Add descriptive alt text to images',
            example: '<img src="..." alt="Description of image" />'
          });
        }
        
        // Check for missing ARIA labels
        if (code.includes('button') && !code.includes('aria-label') && !code.includes('aria-describedby')) {
          suggestions.push({
            category: 'accessibility',
            priority: 'medium',
            issue: 'Interactive elements may need ARIA labels',
            suggestion: 'Add ARIA labels for screen readers',
            example: '<button aria-label="Close dialog">×</button>'
          });
        }
        
        // Check for form labels
        if (code.includes('<input') && !code.includes('label')) {
          suggestions.push({
            category: 'accessibility',
            priority: 'high',
            issue: 'Form inputs without labels',
            suggestion: 'Associate labels with form controls',
            example: '<label htmlFor="name">Name:</label><input id="name" />'
          });
        }
      }
      
      // Filter suggestions by priority if specified
      const filteredSuggestions = priority === 'all' ? suggestions : 
        suggestions.filter(s => s.priority === priority || s.priority === 'critical');
      
      // Sort by priority
      const priorityOrder = { 'critical': 4, 'high': 3, 'medium': 2, 'low': 1 };
      filteredSuggestions.sort((a, b) => (priorityOrder[b.priority as keyof typeof priorityOrder] || 0) - (priorityOrder[a.priority as keyof typeof priorityOrder] || 0));
      
      const improvementResult = {
        action: 'suggest_improvements',
        focus,
        priority,
        codeStats: {
          lines: codeLength,
          functions: (code.match(/function\s+\w+|\w+\s*=\s*\(/g) || []).length,
          comments: (code.match(/\/\*[\s\S]*?\*\/|\/\/.*$/gm) || []).length
        },
        suggestions: filteredSuggestions,
        summary: {
          total: filteredSuggestions.length,
          critical: filteredSuggestions.filter(s => s.priority === 'critical').length,
          high: filteredSuggestions.filter(s => s.priority === 'high').length,
          medium: filteredSuggestions.filter(s => s.priority === 'medium').length,
          low: filteredSuggestions.filter(s => s.priority === 'low').length
        },
        overallScore: Math.max(0, 100 - (filteredSuggestions.length * 10)),
        status: 'success'
      };
      
      const topSuggestions = filteredSuggestions.slice(0, 8);
      return {
        content: [{ type: 'text', text: `Focus: ${focus}\nScore: ${improvementResult.overallScore}/100\nSuggestions: ${improvementResult.summary.total} (${improvementResult.summary.critical}C ${improvementResult.summary.high}H ${improvementResult.summary.medium}M ${improvementResult.summary.low}L)\n\n${topSuggestions.map(s => `[${s.priority.toUpperCase()}] ${s.category}\n  Issue: ${s.issue}\n  Fix: ${s.suggestion}`).join('\n\n')}${filteredSuggestions.length > 8 ? `\n\n... ${filteredSuggestions.length - 8} more suggestions` : ''}` }]
      };
    }
  • The ToolDefinition object defining the tool's name, description, input schema (code required, optional focus and priority), and annotations.
    export const suggestImprovementsDefinition: ToolDefinition = {
      name: 'suggest_improvements',
      description: 'improve|make better|refactoring|improve|make better|refactor|optimize|enhance code - Suggest improvements',
      inputSchema: {
        type: 'object',
        properties: {
          code: { type: 'string', description: 'Code to analyze' },
          focus: { type: 'string', description: 'Focus area', enum: ['performance', 'readability', 'maintainability', 'accessibility', 'type-safety'] },
          priority: { type: 'string', description: 'Priority level', enum: ['critical', 'high', 'medium', 'low'] }
        },
        required: ['code']
      },
      annotations: {
        title: 'Suggest Improvements',
        audience: ['user', 'assistant']
      }
    };
  • src/index.ts:57-669 (registration)
    Registration in src/index.ts: import of handler and definition, inclusion in tools array for listing, and dispatch case in executeToolCall function.
    import { suggestImprovements, suggestImprovementsDefinition } from './tools/convention/suggestImprovements.js';
    import { validateCodeQuality, validateCodeQualityDefinition } from './tools/convention/validateCodeQuality.js';
    import { autoSaveContext, autoSaveContextDefinition } from './tools/memory/autoSaveContext.js';
    import { deleteMemory, deleteMemoryDefinition } from './tools/memory/deleteMemory.js';
    import { listMemories, listMemoriesDefinition } from './tools/memory/listMemories.js';
    import { prioritizeMemory, prioritizeMemoryDefinition } from './tools/memory/prioritizeMemory.js';
    import { recallMemory, recallMemoryDefinition } from './tools/memory/recallMemory.js';
    import { restoreSessionContext, restoreSessionContextDefinition } from './tools/memory/restoreSessionContext.js';
    import { saveMemory, saveMemoryDefinition } from './tools/memory/saveMemory.js';
    import { searchMemoriesDefinition, searchMemoriesHandler } from './tools/memory/searchMemories.js';
    import { startSession, startSessionDefinition } from './tools/memory/startSession.js';
    import { updateMemory, updateMemoryDefinition } from './tools/memory/updateMemory.js';
    import { analyzeRequirements, analyzeRequirementsDefinition } from './tools/planning/analyzeRequirements.js';
    import { createUserStories, createUserStoriesDefinition } from './tools/planning/createUserStories.js';
    import { featureRoadmap, featureRoadmapDefinition } from './tools/planning/featureRoadmap.js';
    import { generatePrd, generatePrdDefinition } from './tools/planning/generatePrd.js';
    import { analyzePrompt, analyzePromptDefinition } from './tools/prompt/analyzePrompt.js';
    import { enhancePrompt, enhancePromptDefinition } from './tools/prompt/enhancePrompt.js';
    import { enhancePromptGemini, enhancePromptGeminiDefinition } from './tools/prompt/enhancePromptGemini.js';
    import { applyReasoningFramework, applyReasoningFrameworkDefinition } from './tools/reasoning/applyReasoningFramework.js';
    import { findReferences, findReferencesDefinition } from './tools/semantic/findReferences.js';
    import { findSymbol, findSymbolDefinition } from './tools/semantic/findSymbol.js';
    import { analyzeProblem, analyzeProblemDefinition } from './tools/thinking/analyzeProblem.js';
    import { breakDownProblem, breakDownProblemDefinition } from './tools/thinking/breakDownProblem.js';
    import { createThinkingChain, createThinkingChainDefinition } from './tools/thinking/createThinkingChain.js';
    import { formatAsPlan, formatAsPlanDefinition } from './tools/thinking/formatAsPlan.js';
    import { stepByStepAnalysis, stepByStepAnalysisDefinition } from './tools/thinking/stepByStepAnalysis.js';
    import { thinkAloudProcess, thinkAloudProcessDefinition } from './tools/thinking/thinkAloudProcess.js';
    import { previewUiAscii, previewUiAsciiDefinition } from './tools/ui/previewUiAscii.js';
    
    // Import pagination utilities
    import { paginateItems } from './types/pagination.js';
    
    // Import task manager
    
    // Tool definition interface with optional task support
    interface ToolDefinition {
      name?: string;
      description?: string;
      execution?: {
        taskSupport?: 'required' | 'optional' | 'forbidden';
      };
      // allow any additional properties from tool definition objects
      [key: string]: any;
    }
    
    // Collect all tool definitions
    const tools: ToolDefinition[] = [
      // Time Utility Tools
      getCurrentTimeDefinition,
    
      // Semantic Code Analysis Tools (Serena-inspired)
      findSymbolDefinition,
      findReferencesDefinition,
    
      // Sequential Thinking Tools
      createThinkingChainDefinition,
      analyzeProblemDefinition,
      stepByStepAnalysisDefinition,
      breakDownProblemDefinition,
      thinkAloudProcessDefinition,
      formatAsPlanDefinition,
    
      // Browser Development Tools
      monitorConsoleLogsDefinition,
      inspectNetworkRequestsDefinition,
    
      // Memory Management Tools
      saveMemoryDefinition,
      recallMemoryDefinition,
      listMemoriesDefinition,
      deleteMemoryDefinition,
      searchMemoriesDefinition,
      updateMemoryDefinition,
      autoSaveContextDefinition,
      restoreSessionContextDefinition,
      prioritizeMemoryDefinition,
      startSessionDefinition,
    
      // Convention Tools
      getCodingGuideDefinition,
      applyQualityRulesDefinition,
      validateCodeQualityDefinition,
      analyzeComplexityDefinition,
      checkCouplingCohesionDefinition,
      suggestImprovementsDefinition,
    
      // Planning Tools
      generatePrdDefinition,
      createUserStoriesDefinition,
      analyzeRequirementsDefinition,
      featureRoadmapDefinition,
    
      // Prompt Enhancement Tools
      enhancePromptDefinition,
      analyzePromptDefinition,
      enhancePromptGeminiDefinition,
    
      // Reasoning Tools
      applyReasoningFrameworkDefinition,
    
      // UI Preview Tools
      previewUiAsciiDefinition
    ];
    
    // Task support temporarily disabled
    
    function buildServer(config?: unknown): McpServer {
      const server: McpServer = new McpServer(
        {
          name: 'Hi-AI',
          version: '1.6.0',
        },
        {
          capabilities: {
            logging: {},
            prompts: {
              listChanged: true
            },
            resources: {
              listChanged: true
            },
            tools: {
              listChanged: true
            },
            completions: {},
          },
        }
      );
    
      // Define resources from imported definitions
      const resources = [
        toolDocumentationDefinition,
        capabilitiesDefinition
      ];
    
      // Define prompts from imported definitions
      const prompts = [
        codeReviewDefinition,
        debugAssistantDefinition,
        projectPlanningDefinition,
        memoryManagementDefinition,
        timeUtilitiesDefinition,
        semanticAnalysisDefinition,
        sequentialThinkingDefinition,
        browserDevelopmentDefinition,
        codeConventionsDefinition,
        promptEnhancementDefinition,
        reasoningFrameworkDefinition,
        specGenerationDefinition,
        documentationDefinition,
        testingDefinition,
        uiPreviewDefinition
      ];
    
      // Task notifications disabled - experimental feature temporarily removed
    
      // ========================================
      // TOOLS - with pagination support
      // ========================================
      interface ListToolsRequestParams {
        cursor?: string;
      }
    
      server.server.setRequestHandler(ListToolsRequestSchema, async (request: { params?: ListToolsRequestParams }): Promise<{ tools: ToolDefinition[]; nextCursor?: string }> => {
        const cursor = request.params?.cursor;
        const paginated = paginateItems(tools, cursor, 50);
    
        return {
          tools: paginated.items,
          nextCursor: paginated.nextCursor
        };
      });
    
      // ========================================
      // RESOURCES - with pagination support
      // ========================================
      interface ListResourcesRequestParams {
        cursor?: string;
      }
    
      server.server.setRequestHandler(ListResourcesRequestSchema, async (request: { params?: ListResourcesRequestParams }): Promise<ListResourcesResult & { nextCursor?: string }> => {
        const cursor = request.params?.cursor;
        const paginated = paginateItems(resources, cursor, 50);
    
        return {
          resources: paginated.items,
          nextCursor: paginated.nextCursor
        };
      });
    
      server.server.setRequestHandler(ReadResourceRequestSchema, async (request): Promise<ReadResourceResult> => {
        const { uri } = request.params;
    
        try {
          if (uri === toolDocumentationDefinition.uri) {
            const content = getToolDocumentationContent();
            return {
              contents: [{
                uri,
                mimeType: toolDocumentationDefinition.mimeType,
                text: content
              }]
            };
          } else if (uri === capabilitiesDefinition.uri) {
            const content = getCapabilitiesContent(tools.length, resources.length, prompts.length);
            return {
              contents: [{
                uri,
                mimeType: capabilitiesDefinition.mimeType,
                text: content
              }]
            };
          } else {
            throw new McpError(ErrorCode.InvalidRequest, `Unknown resource: ${uri}`);
          }
        } catch (error) {
          throw new McpError(ErrorCode.InternalError, `Error reading resource: ${error instanceof Error ? error.message : 'Unknown error'}`);
        }
      });
    
      // ========================================
      // PROMPTS - with pagination support
      // ========================================
      interface ListPromptsRequestParams {
        cursor?: string;
      }
    
      server.server.setRequestHandler(ListPromptsRequestSchema, async (request: { params?: ListPromptsRequestParams }): Promise<ListPromptsResult & { nextCursor?: string }> => {
        const cursor = request.params?.cursor;
        const paginated = paginateItems(prompts, cursor, 50);
    
        return {
          prompts: paginated.items,
          nextCursor: paginated.nextCursor
        };
      });
    
      // ========================================
      // COMPLETION - argument suggestions
      // ========================================
      server.server.setRequestHandler(CompleteRequestSchema, async (request): Promise<CompleteResult> => {
        const { ref, argument } = request.params;
    
        try {
          if (ref.type === 'ref/prompt') {
            const promptName = ref.name;
            if (promptName === codeReviewDefinition.name && argument.name === 'language') {
              return {
                completion: {
                  values: ['javascript', 'typescript', 'python', 'java', 'cpp', 'go', 'rust', 'csharp', 'php', 'ruby'],
                  hasMore: false,
                  total: 10
                }
              };
            } else if (promptName === debugAssistantDefinition.name && argument.name === 'environment') {
              return {
                completion: {
                  values: ['browser', 'node.js', 'electron', 'react-native', 'server', 'desktop'],
                  hasMore: false,
                  total: 6
                }
              };
            } else if (promptName === projectPlanningDefinition.name && argument.name === 'target_audience') {
              return {
                completion: {
                  values: ['developers', 'business-users', 'consumers', 'enterprise', 'students', 'general-public'],
                  hasMore: false,
                  total: 6
                }
              };
            } else if (promptName === memoryManagementDefinition.name && argument.name === 'importance_level') {
              return {
                completion: {
                  values: ['critical', 'high', 'medium', 'low'],
                  hasMore: false,
                  total: 4
                }
              };
            } else if (promptName === timeUtilitiesDefinition.name && argument.name === 'task_type') {
              return {
                completion: {
                  values: ['scheduling', 'conversion', 'calculation', 'planning'],
                  hasMore: false,
                  total: 4
                }
              };
            } else if (promptName === semanticAnalysisDefinition.name && argument.name === 'analysis_type') {
              return {
                completion: {
                  values: ['navigation', 'refactoring', 'impact-analysis', 'code-understanding'],
                  hasMore: false,
                  total: 4
                }
              };
            } else if (promptName === sequentialThinkingDefinition.name && argument.name === 'thinking_task') {
              return {
                completion: {
                  values: ['problem-solving', 'decision-making', 'analysis', 'planning'],
                  hasMore: false,
                  total: 4
                }
              };
            } else if (promptName === browserDevelopmentDefinition.name && argument.name === 'debugging_task') {
              return {
                completion: {
                  values: ['console-analysis', 'network-inspection', 'performance-monitoring', 'error-tracking'],
                  hasMore: false,
                  total: 4
                }
              };
            } else if (promptName === codeConventionsDefinition.name && argument.name === 'code_quality_task') {
              return {
                completion: {
                  values: ['validation', 'analysis', 'improvement', 'standards-check'],
                  hasMore: false,
                  total: 4
                }
              };
            } else if (promptName === promptEnhancementDefinition.name && argument.name === 'enhancement_task') {
              return {
                completion: {
                  values: ['optimization', 'analysis', 'gemini-enhancement', 'effectiveness-review'],
                  hasMore: false,
                  total: 4
                }
              };
            } else if (promptName === reasoningFrameworkDefinition.name && argument.name === 'reasoning_task') {
              return {
                completion: {
                  values: ['problem-analysis', 'decision-making', 'evaluation', 'strategy-development'],
                  hasMore: false,
                  total: 4
                }
              };
            } else if (promptName === specGenerationDefinition.name && argument.name === 'spec_type') {
              return {
                completion: {
                  values: ['api', 'feature', 'system', 'ui', 'data', 'security', 'architecture', 'integration'],
                  hasMore: false,
                  total: 8
                }
              };
            } else if (promptName === specGenerationDefinition.name && argument.name === 'stakeholders') {
              return {
                completion: {
                  values: ['development-team', 'product-owner', 'end-users', 'business-analysts', 'qa-engineers', 'devops-team', 'security-team'],
                  hasMore: false,
                  total: 7
                }
              };
            } else if (promptName === documentationDefinition.name && argument.name === 'doc_type') {
              return {
                completion: {
                  values: ['api', 'readme', 'user-guide', 'technical', 'deployment', 'troubleshooting', 'architecture', 'integration'],
                  hasMore: false,
                  total: 8
                }
              };
            } else if (promptName === documentationDefinition.name && argument.name === 'audience') {
              return {
                completion: {
                  values: ['developers', 'users', 'administrators', 'stakeholders', 'testers', 'devops', 'security-team'],
                  hasMore: false,
                  total: 7
                }
              };
            } else if (promptName === documentationDefinition.name && argument.name === 'format') {
              return {
                completion: {
                  values: ['markdown', 'html', 'pdf', 'structured', 'wiki', 'api-docs', 'interactive'],
                  hasMore: false,
                  total: 7
                }
              };
            } else if (promptName === testingDefinition.name && argument.name === 'test_type') {
              return {
                completion: {
                  values: ['unit', 'integration', 'e2e', 'performance', 'security', 'api', 'ui', 'mobile', 'accessibility', 'compatibility'],
                  hasMore: false,
                  total: 10
                }
              };
            } else if (promptName === testingDefinition.name && argument.name === 'quality_requirements') {
              return {
                completion: {
                  values: ['high-reliability', 'gdpr-compliant', 'wcag-accessible', 'performance-critical', 'security-first', 'user-centric'],
                  hasMore: false,
                  total: 6
                }
              };
            }
          }
          // Default empty completion
          return {
            completion: {
              values: [],
              hasMore: false,
              total: 0
            }
          };
        } catch (error) {
          throw new McpError(ErrorCode.InternalError, `Error completing: ${error instanceof Error ? error.message : 'Unknown error'}`);
        }
      });
    
      // ========================================
      // LOGGING
      // ========================================
      let currentLogLevel: string = 'info';
    
      server.server.setRequestHandler(SetLevelRequestSchema, async (request): Promise<{}> => {
        const { level } = request.params;
        currentLogLevel = level;
        // Optionally send a notification
        await server.server.notification({
          method: 'notifications/message',
          params: {
            level: 'info',
            logger: 'hi-ai',
            data: `Log level set to ${level}`
          }
        });
        return {};
      });
    
      // ========================================
      // PROMPTS - get prompt handler
      // ========================================
      server.server.setRequestHandler(GetPromptRequestSchema, async (request): Promise<GetPromptResult> => {
        const { name, arguments: args = {} } = request.params;
    
        try {
          if (name === codeReviewDefinition.name) {
            const language = args.language as string;
            const code = args.code as string;
            const projectPath = args.project_path as string;
            return getCodeReviewPrompt(language, code, projectPath);
          } else if (name === debugAssistantDefinition.name) {
            const errorMessage = args.error_message as string;
            const codeContext = args.code_context as string;
            const environment = args.environment as string;
            const reproductionSteps = args.reproduction_steps as string;
            return getDebugAssistantPrompt(errorMessage, codeContext, environment, reproductionSteps);
          } else if (name === projectPlanningDefinition.name) {
            const projectIdea = args.project_idea as string;
            const targetAudience = args.target_audience as string;
            const constraints = args.constraints as string;
            const existingContext = args.existing_context as string;
            return getProjectPlanningPrompt(projectIdea, targetAudience, constraints, existingContext);
          } else if (name === memoryManagementDefinition.name) {
            const taskContext = args.task_context as string;
            const memoryOperation = args.memory_operation as string;
            const importanceLevel = args.importance_level as string;
            const relatedTopics = args.related_topics as string;
            return getMemoryManagementPrompt(taskContext, memoryOperation, importanceLevel, relatedTopics);
          } else if (name === timeUtilitiesDefinition.name) {
            const taskType = args.task_type as string;
            const context = args.context as string;
            const timezones = args.timezones as string;
            const constraints = args.constraints as string;
            return getTimeUtilitiesPrompt(taskType, context, timezones, constraints);
          } else if (name === semanticAnalysisDefinition.name) {
            const analysisType = args.analysis_type as string;
            const targetSymbol = args.target_symbol as string;
            const projectPath = args.project_path as string;
            const analysisScope = args.analysis_scope as string;
            const specificRequirements = args.specific_requirements as string;
            return getSemanticAnalysisPrompt(analysisType, targetSymbol, projectPath, analysisScope, specificRequirements);
          } else if (name === sequentialThinkingDefinition.name) {
            const thinkingTask = args.thinking_task as string;
            const domainContext = args.domain_context as string;
            const complexityLevel = args.complexity_level as string;
            const outputFormat = args.output_format as string;
            const constraints = args.constraints as string;
            return getSequentialThinkingPrompt(thinkingTask, domainContext, complexityLevel, outputFormat, constraints);
          } else if (name === browserDevelopmentDefinition.name) {
            const debuggingTask = args.debugging_task as string;
            const targetUrl = args.target_url as string;
            const issueDescription = args.issue_description as string;
            const monitoringDuration = args.monitoring_duration as string;
            const focusAreas = args.focus_areas as string;
            return getBrowserDevelopmentPrompt(debuggingTask, targetUrl, issueDescription, monitoringDuration, focusAreas);
          } else if (name === codeConventionsDefinition.name) {
            const codeQualityTask = args.code_quality_task as string;
            const codeToAnalyze = args.code_to_analyze as string;
            const programmingLanguage = args.programming_language as string;
            const qualityFocus = args.quality_focus as string;
            const standardsLevel = args.standards_level as string;
            return getCodeConventionsPrompt(codeQualityTask, codeToAnalyze, programmingLanguage, qualityFocus, standardsLevel);
          } else if (name === promptEnhancementDefinition.name) {
            const enhancementTask = args.enhancement_task as string;
            const originalPrompt = args.original_prompt as string;
            const targetUseCase = args.target_use_case as string;
            const enhancementFocus = args.enhancement_focus as string;
            const aiModelContext = args.ai_model_context as string;
            return getPromptEnhancementPrompt(enhancementTask, originalPrompt, targetUseCase, enhancementFocus, aiModelContext);
          } else if (name === reasoningFrameworkDefinition.name) {
            const reasoningTask = args.reasoning_task as string;
            const problemContext = args.problem_context as string;
            const reasoningApproach = args.reasoning_approach as string;
            const complexityLevel = args.complexity_level as string;
            const decisionCriteria = args.decision_criteria as string;
            return getReasoningFrameworkPrompt(reasoningTask, problemContext, reasoningApproach, complexityLevel, decisionCriteria);
          } else if (name === specGenerationDefinition.name) {
            const specType = args.spec_type as string;
            const specSubject = args.spec_subject as string;
            const context = args.context as string;
            const stakeholders = args.stakeholders as string;
            const constraints = args.constraints as string;
            return getSpecGenerationPrompt(specType, specSubject, context, stakeholders, constraints);
          } else if (name === documentationDefinition.name) {
            const docType = args.doc_type as string;
            const docSubject = args.doc_subject as string;
            const audience = args.audience as string;
            const context = args.context as string;
            const format = args.format as string;
            return getDocumentationPrompt(docType, docSubject, audience, context, format);
          } else if (name === testingDefinition.name) {
            const testType = args.test_type as string;
            const systemUnderTest = args.system_under_test as string;
            const testingContext = args.testing_context as string;
            const qualityRequirements = args.quality_requirements as string;
            const constraints = args.constraints as string;
            return getTestingPrompt(testType, systemUnderTest, testingContext, qualityRequirements, constraints);
          } else if (name === uiPreviewDefinition.name) {
            const uiDescription = args.ui_description as string;
            const designContext = args.design_context as string;
            const previewStyle = args.preview_style as string;
            const keyElements = args.key_elements as string;
            const layoutFocus = args.layout_focus as string;
            return getUiPreviewPrompt(uiDescription, designContext, previewStyle, keyElements, layoutFocus);
          } else {
            throw new McpError(ErrorCode.InvalidRequest, `Unknown prompt: ${name}`);
          }
        } catch (error) {
          if (error instanceof McpError) throw error;
          throw new McpError(ErrorCode.InternalError, `Error getting prompt: ${error instanceof Error ? error.message : 'Unknown error'}`);
        }
      });
    
      // ========================================
      // TOOLS - call tool handler
      // ========================================
    
      // Tool execution function
      async function executeToolCall(name: string, args: unknown): Promise<CallToolResult> {
        switch (name) {
          // Time Utility Tools
          case 'get_current_time':
            return await getCurrentTime(args as any) as CallToolResult;
    
          // Semantic Code Analysis Tools
          case 'find_symbol':
            return await findSymbol(args as any) as CallToolResult;
          case 'find_references':
            return await findReferences(args as any) as CallToolResult;
    
          // Sequential Thinking Tools
          case 'create_thinking_chain':
            return await createThinkingChain(args as any) as CallToolResult;
          case 'analyze_problem':
            return await analyzeProblem(args as any) as CallToolResult;
          case 'step_by_step_analysis':
            return await stepByStepAnalysis(args as any) as CallToolResult;
          case 'break_down_problem':
            return await breakDownProblem(args as any) as CallToolResult;
          case 'think_aloud_process':
            return await thinkAloudProcess(args as any) as CallToolResult;
          case 'format_as_plan':
            return await formatAsPlan(args as any) as CallToolResult;
    
          // Browser Development Tools
          case 'monitor_console_logs':
            return await monitorConsoleLogs(args as any) as CallToolResult;
          case 'inspect_network_requests':
            return await inspectNetworkRequests(args as any) as CallToolResult;
    
          // Memory Management Tools
          case 'save_memory':
            return await saveMemory(args as any) as CallToolResult;
          case 'recall_memory':
            return await recallMemory(args as any) as CallToolResult;
          case 'list_memories':
            return await listMemories(args as any) as CallToolResult;
          case 'delete_memory':
            return await deleteMemory(args as any) as CallToolResult;
          case 'search_memories':
            return await searchMemoriesHandler(args as any) as CallToolResult;
          case 'update_memory':
            return await updateMemory(args as any) as CallToolResult;
          case 'auto_save_context':
            return await autoSaveContext(args as any) as CallToolResult;
          case 'restore_session_context':
            return await restoreSessionContext(args as any) as CallToolResult;
          case 'prioritize_memory':
            return await prioritizeMemory(args as any) as CallToolResult;
          case 'start_session':
            return await startSession(args as any) as CallToolResult;
    
          // Convention Tools
          case 'get_coding_guide':
            return await getCodingGuide(args as any) as CallToolResult;
          case 'apply_quality_rules':
            return await applyQualityRules(args as any) as CallToolResult;
          case 'validate_code_quality':
            return await validateCodeQuality(args as any) as CallToolResult;
          case 'analyze_complexity':
            return await analyzeComplexity(args as any) as CallToolResult;
          case 'check_coupling_cohesion':
            return await checkCouplingCohesion(args as any) as CallToolResult;
          case 'suggest_improvements':
            return await suggestImprovements(args as any) as CallToolResult;
Behavior3/5

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

Annotations only provide a title ('Suggest Improvements'), which doesn't cover behavioral traits like read-only vs. destructive operations, authentication needs, or rate limits. The description adds minimal context by implying the tool analyzes code for improvements, but it doesn't disclose specific behaviors such as whether it modifies code, requires specific permissions, or has limitations. Since annotations are sparse, the description carries more burden but still falls short of rich behavioral disclosure, earning a baseline score.

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 poorly structured and repetitive, with phrases like 'improve|make better' duplicated and a disorganized list ('refactoring|improve|make better|refactor|optimize|enhance code - Suggest improvements'). It lacks front-loading of key information and includes redundant terms, making it inefficient and hard to parse. While brief, the repetition undermines conciseness, resulting in wasted space.

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 tool's complexity (3 parameters, no output schema, sparse annotations), the description is incomplete. It doesn't explain what the tool returns, how improvements are suggested, or any constraints (e.g., code language support, analysis depth). With no output schema and minimal annotations, the description should provide more context about the tool's operation and results, but it fails to do so, 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?

The input schema has 100% description coverage, with clear documentation for 'code', 'focus' (with enum values), and 'priority' (with enum values). The description doesn't add any meaningful semantics beyond the schema—it doesn't explain parameter interactions, default behaviors, or usage 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.

Purpose2/5

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

The description 'improve|make better|refactoring|improve|make better|refactor|optimize|enhance code - Suggest improvements' is tautological, essentially restating the tool name 'suggest_improvements' with synonyms. It doesn't specify what kind of improvements (e.g., code quality, performance) beyond the generic 'improve code', nor does it clearly distinguish from siblings like 'validate_code_quality' or 'apply_quality_rules'. The repetition of phrases ('improve|make better' appears twice) adds noise without clarity.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines1/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 any context, prerequisites, or exclusions, and fails to differentiate from sibling tools such as 'validate_code_quality' or 'apply_quality_rules', which might overlap in purpose. Without explicit or implied usage instructions, the agent lacks direction for tool selection.

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/ssdeanx/ssd-ai'

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