Skip to main content
Glama
bswa006

AI Agent Template MCP Server

by bswa006

analyze_codebase_deeply

Analyze codebase structure, patterns, and tech stack to understand architecture and dependencies for informed development decisions.

Instructions

Perform comprehensive analysis of codebase to understand patterns, tech stack, and architecture

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
projectPathYesPath to the project directory to analyze
maxDepthNoMaximum directory depth to analyze (default: 5)
excludePatternsNoPatterns to exclude from analysis

Implementation Reference

  • The main handler function that performs comprehensive deep analysis of the codebase: reads package.json for deps/tech stack, traverses directories, parses source files with Babel to detect patterns, checks code quality tools, generates recommendations, and stores results globally.
    export async function analyzeCodebaseDeeply(
      config: AnalysisConfig
    ): Promise<DeepAnalysisResult> {
      const analysisId = `analysis_${Date.now()}`;
      const result: DeepAnalysisResult = {
        success: false,
        analysisId,
        timestamp: new Date().toISOString(),
        projectPath: config.projectPath,
        summary: {
          totalFiles: 0,
          totalLines: 0,
          techStack: [],
          primaryLanguage: 'TypeScript',
          frameworks: [],
          testingFrameworks: [],
        },
        structure: {
          directories: {},
          entryPoints: [],
        },
        patterns: {
          components: {
            style: 'function',
            propsPattern: 'interface',
            exportPattern: 'named',
            count: 0,
          },
          stateManagement: [],
          styling: 'css',
          imports: {
            style: 'named',
            common: [],
          },
          naming: {
            components: 'PascalCase',
            hooks: 'camelCase',
            services: 'camelCase',
            utils: 'camelCase',
          },
        },
        dependencies: {
          production: {},
          development: {},
        },
        codeQuality: {
          hasTypeScript: false,
          hasLinting: false,
          hasPrettier: false,
          hasPreCommitHooks: false,
        },
        evidenceFiles: [],
        recommendations: [],
      };
    
      try {
        // Read package.json
        const packageJsonPath = join(config.projectPath, 'package.json');
        const packageJson = JSON.parse(await readFile(packageJsonPath, 'utf-8'));
        
        // Extract dependencies
        result.dependencies.production = packageJson.dependencies || {};
        result.dependencies.development = packageJson.devDependencies || {};
        
        // Detect tech stack
        detectTechStack(result, packageJson);
        
        // Check code quality tools
        await checkCodeQuality(result, config.projectPath);
        
        // Analyze directory structure
        await analyzeDirectoryStructure(
          config.projectPath,
          config.projectPath,
          result,
          0,
          config.maxDepth || 5,
          config.excludePatterns || ['node_modules', '.git', 'dist', 'build', '.next', 'coverage']
        );
        
        // Analyze patterns from source files
        await analyzeCodePatterns(config.projectPath, result);
        
        // Generate recommendations
        generateRecommendations(result);
        
        // Store result globally
        result.success = true;
        global.codebaseAnalysis[analysisId] = result;
        global.latestAnalysisId = analysisId;
        
      } catch (error) {
        result.success = false;
        result.recommendations.push(`Analysis error: ${error}`);
      }
    
      return result;
    }
  • Tool registration in the main switch dispatcher: parses input args with Zod, calls analyzeCodebaseDeeply handler, and returns JSON stringified result as tool response.
    case 'analyze_codebase_deeply': {
      const params = z.object({
        projectPath: z.string(),
        maxDepth: z.number().optional(),
        excludePatterns: z.array(z.string()).optional(),
      }).parse(args);
      
      const result = await analyzeCodebaseDeeply(params);
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2),
          },
        ],
      };
    }
  • MCP tool definition including name, description, and input schema (Zod-like JSON schema) for validating tool call parameters.
    {
      name: 'analyze_codebase_deeply',
      description: 'Perform comprehensive analysis of codebase to understand patterns, tech stack, and architecture',
      inputSchema: {
        type: 'object',
        properties: {
          projectPath: {
            type: 'string',
            description: 'Path to the project directory to analyze',
          },
          maxDepth: {
            type: 'number',
            description: 'Maximum directory depth to analyze (default: 5)',
          },
          excludePatterns: {
            type: 'array',
            items: { type: 'string' },
            description: 'Patterns to exclude from analysis',
          },
        },
        required: ['projectPath'],
      },
    },
  • TypeScript interface defining the detailed output structure returned by the analyzeCodebaseDeeply function.
    export interface DeepAnalysisResult {
      success: boolean;
      analysisId: string;
      timestamp: string;
      projectPath: string;
      summary: {
        totalFiles: number;
        totalLines: number;
        techStack: string[];
        primaryLanguage: string;
        frameworks: string[];
        testingFrameworks: string[];
      };
      structure: {
        directories: Record<string, {
          fileCount: number;
          purpose: string;
          mainTypes: string[];
        }>;
        entryPoints: string[];
      };
      patterns: {
        components: {
          style: string;
          propsPattern: string;
          exportPattern: string;
          count: number;
        };
        stateManagement: string[];
        styling: string;
        imports: {
          style: string;
          common: string[];
        };
        naming: {
          components: string;
          hooks: string;
          services: string;
          utils: string;
        };
      };
      dependencies: {
        production: Record<string, string>;
        development: Record<string, string>;
      };
      codeQuality: {
        hasTypeScript: boolean;
        hasLinting: boolean;
        hasPrettier: boolean;
        hasPreCommitHooks: boolean;
      };
      evidenceFiles: Array<{
        path: string;
        purpose: string;
        patterns: string[];
      }>;
      recommendations: string[];
    }
  • Import statement registering the handler function into the main tools index module.
    import { analyzeCodebaseDeeply } from './workspace/analyze-codebase-deeply.js';

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/bswa006/mcp-context-manager'

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