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';
Behavior2/5

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

No annotations are provided, so the description carries full burden. It mentions 'comprehensive analysis' but doesn't disclose behavioral traits like computational intensity, time requirements, output format, or side effects. For a tool with no annotations and potentially heavy processing, 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.

Conciseness4/5

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

Single sentence that efficiently conveys the core purpose without waste. It's front-loaded with the main action and goals, though it could be slightly more structured by separating scope from objectives.

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 no annotations, no output schema, and a tool that performs complex analysis, the description is incomplete. It lacks details on what the analysis entails, how results are returned, or any limitations. For a 'deep' analysis tool with 3 parameters, this leaves too much unspecified for effective agent use.

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 already documents all parameters. The description adds no additional meaning beyond what's in the schema—it doesn't explain how parameters affect the analysis or provide examples. Baseline 3 is appropriate when schema does the heavy lifting.

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 verb 'perform comprehensive analysis' and the resource 'codebase', with specific goals to 'understand patterns, tech stack, and architecture'. It distinguishes from some siblings like 'check_security_compliance' or 'generate_tests_for_coverage' by focusing on holistic understanding rather than specific tasks, though it doesn't explicitly differentiate from 'detect_existing_patterns' which might overlap.

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 explicit guidance on when to use this tool versus alternatives. It doesn't mention when-not scenarios, prerequisites, or compare to siblings like 'detect_existing_patterns' for pattern analysis or 'check_before_suggesting' for pre-analysis checks. The description implies usage for deep codebase understanding but lacks context 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/bswa006/mcp-context-manager'

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