Skip to main content
Glama
bswa006

AI Agent Template MCP Server

by bswa006

detect_existing_patterns

Analyze codebases to identify existing patterns in naming, structure, imports, testing, and styling for consistent development.

Instructions

Analyze existing codebase to detect patterns and conventions

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
directoryYesDirectory to analyze
patternTypesNoTypes of patterns to detect

Implementation Reference

  • The core handler function that executes the tool logic: scans a directory for files of a given type, detects patterns across imports, components, hooks, state management, error handling, and styling, computes frequencies/confidence, and generates recommendations.
    export async function detectExistingPatterns(
      directory: string,
      fileType: string
    ): Promise<PatternAnalysis> {
      const analysis: PatternAnalysis = {
        directory,
        fileType,
        patterns: {
          imports: [],
          components: [],
          hooks: [],
          stateManagement: [],
          errorHandling: [],
          styling: [],
        },
        recommendations: [],
      };
    
      try {
        // Find all relevant files
        const files = findFiles(directory, fileType);
        
        if (files.length === 0) {
          analysis.recommendations.push(`No ${fileType} files found in ${directory}`);
          return analysis;
        }
    
        // Analyze each file
        const fileContents = files.map(file => ({
          path: file,
          content: readFileSync(file, 'utf-8'),
        }));
    
        // Detect patterns
        analysis.patterns.imports = detectImportPatterns(fileContents);
        analysis.patterns.components = detectComponentPatterns(fileContents, fileType);
        analysis.patterns.hooks = detectHookPatterns(fileContents);
        analysis.patterns.stateManagement = detectStatePatterns(fileContents);
        analysis.patterns.errorHandling = detectErrorPatterns(fileContents);
        analysis.patterns.styling = detectStylingPatterns(fileContents);
    
        // Generate recommendations
        generateRecommendations(analysis);
    
      } catch (error) {
        analysis.recommendations.push(`Error analyzing directory: ${error}`);
      }
    
      return analysis;
    }
  • The switch case in the main tool dispatcher that handles calls to 'detect_existing_patterns', parses arguments, invokes the handler, and formats the MCP response.
    case 'detect_existing_patterns': {
      const params = z.object({
        directory: z.string(),
        fileType: z.string(),
      }).parse(args);
      
      const patterns = await detectExistingPatterns(
        params.directory,
        params.fileType
      );
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(patterns, null, 2),
          },
        ],
      };
    }
  • The tool definition including name, description, and input schema for 'detect_existing_patterns', used for listing tools and validation.
    {
      name: 'detect_existing_patterns',
      description: 'Analyze existing codebase to detect patterns and conventions',
      inputSchema: {
        type: 'object',
        properties: {
          directory: {
            type: 'string',
            description: 'Directory to analyze',
          },
          patternTypes: {
            type: 'array',
            items: {
              type: 'string',
              enum: ['naming', 'structure', 'imports', 'testing', 'styling'],
            },
            description: 'Types of patterns to detect',
          },
        },
        required: ['directory'],
      },
    },
  • Registration of the tools/list handler that returns the toolDefinitions array including detect_existing_patterns.
    server.setRequestHandler(ListToolsRequestSchema, async () => {
      console.error(`Handling tools/list request, returning ${toolDefinitions.length} tools`);
      return { tools: toolDefinitions };
    });
  • Calls to helper functions that perform specific pattern detection (imports, components, etc.) and generate recommendations.
        analysis.patterns.imports = detectImportPatterns(fileContents);
        analysis.patterns.components = detectComponentPatterns(fileContents, fileType);
        analysis.patterns.hooks = detectHookPatterns(fileContents);
        analysis.patterns.stateManagement = detectStatePatterns(fileContents);
        analysis.patterns.errorHandling = detectErrorPatterns(fileContents);
        analysis.patterns.styling = detectStylingPatterns(fileContents);
    
        // Generate recommendations
        generateRecommendations(analysis);
    
      } catch (error) {
        analysis.recommendations.push(`Error analyzing directory: ${error}`);
      }
    
      return analysis;
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions analysis and detection but doesn't describe what the tool returns (e.g., a report, list of patterns), whether it's read-only or has side effects, or any performance considerations like runtime or resource usage for codebase analysis.

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?

The description is a single, efficient sentence that directly states the tool's function without unnecessary words. It's appropriately sized and front-loaded, making it easy to understand quickly.

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 tool with no annotations and no output schema, the description is incomplete. It doesn't explain what the analysis outputs (e.g., a summary, detailed findings), how results are structured, or any behavioral traits like whether it's safe for read-only use or has dependencies on codebase size.

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 fully documents both parameters ('directory' and 'patternTypes'). The description adds no additional meaning beyond what's in the schema, such as explaining what 'analyze' entails for these inputs or how pattern detection works with them.

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 with a specific verb ('analyze') and resource ('existing codebase'), and specifies what it detects ('patterns and conventions'). However, it doesn't differentiate from sibling tools like 'analyze_codebase_deeply' or 'get_pattern_for_task', which appear related but have different scopes.

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?

The description provides no guidance on when to use this tool versus alternatives. With siblings like 'analyze_codebase_deeply' and 'get_pattern_for_task', there's no indication of when this detection-focused tool is preferred over deeper analysis or task-specific pattern retrieval.

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