Skip to main content
Glama

Analyze Code

analyze-code

Analyze code for architecture, performance, security, or quality issues to identify problems and improve codebase health.

Instructions

Analyze code for architecture, performance, security, or quality issues

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
taskYesWhat to analyze (e.g., 'analyze performance of user authentication', 'review database queries')
filesNoFile paths to analyze (optional)
focusNoAnalysis focus areaall
providerNoAI provider to usegemini

Implementation Reference

  • Core handler function that executes the 'analyze-code' tool: selects AI provider, constructs focus-specific system prompt, generates analytical response.
    async handleAnalyzeCode(params: z.infer<typeof AnalyzeCodeSchema>) {
      // Use provided provider or get the preferred one (Azure if configured)
      const providerName = params.provider || (await this.providerManager.getPreferredProvider(['openai', 'gemini', 'azure', 'grok']));
      const provider = await this.providerManager.getProvider(providerName);
      
      const focusPrompts = {
        architecture: "Focus on architectural patterns, design decisions, modularity, and code organization",
        performance: "Focus on performance implications, optimization opportunities, and efficiency concerns",
        security: "Focus on security vulnerabilities, authentication, authorization, and data protection",
        quality: "Focus on code quality, maintainability, readability, and best practices",
        all: "Provide comprehensive analysis covering architecture, performance, security, and quality aspects"
      };
    
      const systemPrompt = `You are an expert code analyst. Analyze the provided code or task systematically.
      ${focusPrompts[params.focus]}
      
      Provide insights on:
      - Key findings and patterns identified
      - Areas of concern or improvement opportunities  
      - Recommendations for enhancement
      - Technical assessment and conclusions
      
      Be specific and actionable in your analysis.`;
    
      const prompt = `Analyze the following: ${params.task}${params.files ? `\n\nFiles to consider: ${params.files.join(", ")}` : ""}`;
    
      const response = await provider.generateText({
        prompt,
        systemPrompt,
        temperature: 0.3, // Lower temperature for analytical tasks
        reasoningEffort: (providerName === "openai" || providerName === "azure" || providerName === "grok") ? "high" : undefined,
        useSearchGrounding: providerName === "gemini",
      });
    
      return {
        content: [
          {
            type: "text",
            text: response.text,
          },
        ],
        metadata: {
          provider: providerName,
          model: response.model,
          focus: params.focus,
          usage: response.usage,
          ...response.metadata,
        },
      };
    }
  • Zod input schema defining parameters for the analyze-code tool: task, optional files, focus area, and provider.
    const AnalyzeCodeSchema = z.object({
      task: z.string().describe("What to analyze (e.g., 'analyze performance of user authentication', 'review database queries')"),
      files: z.array(z.string()).optional().describe("File paths to analyze (optional)"),
      focus: z.enum(["architecture", "performance", "security", "quality", "all"]).default("all").describe("Analysis focus area"),
      provider: z.enum(["openai", "gemini", "azure", "grok"]).optional().default("gemini").describe("AI provider to use"),
    });
  • src/server.ts:284-292 (registration)
    Registers the 'analyze-code' tool with MCP server, specifying title, description, input schema, and delegates execution to AIToolHandlers.handleAnalyzeCode
    // Register analyze-code tool
    server.registerTool("analyze-code", {
      title: "Analyze Code",
      description: "Analyze code for architecture, performance, security, or quality issues",
      inputSchema: AnalyzeCodeSchema.shape,
    }, async (args) => {
      const aiHandlers = await getHandlers();
      return await aiHandlers.handleAnalyzeCode(args);
    });
  • src/server.ts:586-603 (registration)
    Registers the prompt version of 'analyze-code' for natural language invocation.
    server.registerPrompt("analyze-code", {
      title: "Analyze Code", 
      description: "Analyze code for architecture, performance, security, or quality issues",
      argsSchema: {
        task: z.string().optional(),
        files: z.string().optional(),
        focus: z.string().optional(),
        provider: z.string().optional(),
      },
    }, (args) => ({
      messages: [{
        role: "user",
        content: {
          type: "text",
          text: `Analyze this code: ${args.task || 'Please specify what code to analyze (e.g., performance, security, architecture).'}${args.files ? `\n\nFocus on these files: ${args.files}` : ''}${args.focus ? ` (analysis focus: ${args.focus})` : ''}${args.provider ? ` (using ${args.provider} provider)` : ''}`
        }
      }]
    }));
  • Lazy-initializes and returns the AIToolHandlers instance which contains the handleAnalyzeCode method, setting up providers and config.
    async function getHandlers() {
      if (!handlers) {
        const { ConfigManager } = require("./config/manager");
        const { ProviderManager } = require("./providers/manager");
        const { AIToolHandlers } = require("./handlers/ai-tools");
        
        const configManager = new ConfigManager();
        
        // Load config and set environment variables
        const config = await configManager.getConfig();
        if (config.openai?.apiKey) {
          process.env.OPENAI_API_KEY = config.openai.apiKey;
        }
        if (config.openai?.baseURL) {
          process.env.OPENAI_BASE_URL = config.openai.baseURL;
        }
        if (config.google?.apiKey) {
          process.env.GOOGLE_API_KEY = config.google.apiKey;
        }
        if (config.google?.baseURL) {
          process.env.GOOGLE_BASE_URL = config.google.baseURL;
        }
        if (config.azure?.apiKey) {
          process.env.AZURE_API_KEY = config.azure.apiKey;
        }
        if (config.azure?.baseURL) {
          process.env.AZURE_BASE_URL = config.azure.baseURL;
        }
        if (config.xai?.apiKey) {
          process.env.XAI_API_KEY = config.xai.apiKey;
        }
        if (config.xai?.baseURL) {
          process.env.XAI_BASE_URL = config.xai.baseURL;
        }
        
        providerManager = new ProviderManager(configManager);
        handlers = new AIToolHandlers(providerManager);
      }
      
      return handlers;
    }
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. While it mentions what the tool analyzes, it doesn't disclose behavioral traits like whether this is a read-only analysis, what permissions are needed, whether it modifies code, what the output format looks like, or any rate limits. For a code analysis tool with no annotations, this leaves significant gaps.

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 states the core functionality without unnecessary words. It's appropriately sized and front-loaded with the essential information about what the tool does.

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 code analysis tool with 4 parameters and no annotations or output schema, the description is insufficient. It doesn't explain what the analysis produces, how results are returned, whether this is a read-only operation, or what happens when files are provided versus not provided. The description should provide more context about the tool's behavior and output.

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 thoroughly. The description mentions the analysis focus areas (architecture, performance, security, quality) which aligns with the 'focus' parameter enum, but adds no additional semantic context beyond what's in the schema. 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 tool's purpose: analyzing code for specific issue types (architecture, performance, security, quality). It uses a specific verb ('analyze') and resource ('code'), but doesn't explicitly distinguish from siblings like 'review-code' or 'ultra-analyze', which appear to have overlapping functionality.

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 'review-code', 'debug-issue', and 'ultra-analyze' available, there's no indication of when this specific analysis tool is preferred or what differentiates it from similar tools.

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/RealMikeChong/ultra-mcp'

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