Skip to main content
Glama
FosterG4

Code Reference Optimizer MCP Server

by FosterG4

analyze_code_diff

Compare code versions to identify specific changes, extract minimal updates, and optimize code references efficiently for AI assistants. Supports TypeScript/JavaScript, Python, Go, and Rust.

Instructions

Analyze differences between code versions and provide minimal updates

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filePathYesPath to the source file
newContentYesCurrent version of the code
oldContentYesPrevious version of the code

Implementation Reference

  • MCP server handler for the 'analyze_code_diff' tool: destructures input arguments (filePath, oldContent, newContent), logs the call, delegates analysis to CodeReferenceOptimizer.analyzeCodeDiff, and returns the result as a formatted text content block.
    private async handleAnalyzeCodeDiff(args: any) {
      const { filePath, oldContent, newContent } = args;
      
      this.logger.info(`analyze_code_diff: filePath=${filePath}`);
      const result = await this.optimizer.analyzeCodeDiff({
        filePath,
        oldContent,
        newContent,
      });
    
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2),
          },
        ],
      };
    }
  • Core implementation of code diff analysis: generates snapshots of old/new content using DiffManager, extracts and diffs symbols at semantic level using AST parsing, produces change summary, minimal update patch, and token savings estimate.
    async analyzeCodeDiff(options: DiffAnalysisOptions): Promise<{
      changes: Array<{
        type: 'added' | 'removed' | 'modified';
        symbol: string;
        code: string;
        lineNumber: number;
      }>;
      affectedSymbols: string[];
      minimalUpdate: string;
      tokenSavings: number;
    }> {
      const { filePath, oldContent, newContent } = options;
      
      // Create snapshot from old content
      this.diffManager.createSnapshotFromContent(filePath, oldContent);
      
      // Extract symbols from old content
      const oldSymbols = await this.extractSymbolsFromContent(oldContent, filePath);
      await this.diffManager.createSymbolSnapshots(filePath, oldSymbols);
      
      // Extract symbols from new content
      const newSymbols = await this.extractSymbolsFromContent(newContent, filePath);
      
      // Generate symbol-level diff
      const symbolChanges = await this.diffManager.generateSymbolDiff(filePath, newSymbols);
      
      // Convert SymbolChange[] to the expected format
      const changes = symbolChanges.map(change => ({
        type: change.type,
        symbol: change.symbol,
        code: change.code,
        lineNumber: change.lineNumber,
      }));
      
      const affectedSymbols = changes.map(change => change.symbol);
      
      // Generate minimal update containing only changed parts
      const minimalUpdate = this.generateMinimalUpdate(changes);
      
      // Calculate token savings
      const fullContentTokens = this.estimateTokenCount(newContent);
      const minimalUpdateTokens = this.estimateTokenCount(minimalUpdate);
      const tokenSavings = fullContentTokens - minimalUpdateTokens;
      
      return {
        changes,
        affectedSymbols,
        minimalUpdate,
        tokenSavings,
      };
    }
  • src/index.ts:143-164 (registration)
    Registration of the 'analyze_code_diff' tool in the ListToolsRequestSchema response: specifies name, description, and input schema validation requiring filePath, oldContent, newContent.
    {
      name: 'analyze_code_diff',
      description: 'Perform intelligent analysis of code differences between two versions of a file. Identifies semantic changes, structural modifications, and provides minimal update suggestions. Helps understand the impact of changes and suggests optimizations for code evolution.',
      inputSchema: {
        type: 'object',
        properties: {
          filePath: {
            type: 'string',
            description: 'Path to the source file being analyzed. Used for context and language detection.',
          },
          oldContent: {
            type: 'string',
            description: 'Complete content of the previous version of the file. Should be the full file content, not just a snippet.',
          },
          newContent: {
            type: 'string',
            description: 'Complete content of the current version of the file. Should be the full file content, not just a snippet.',
          },
        },
        required: ['filePath', 'oldContent', 'newContent'],
      },
    },
  • src/index.ts:233-234 (registration)
    Dispatch/registration of tool handler in CallToolRequestSchema switch statement: routes 'analyze_code_diff' calls to handleAnalyzeCodeDiff method.
    case 'analyze_code_diff':
      return await this.handleAnalyzeCodeDiff(args);
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the tool 'analyzes differences' and 'provides minimal updates', implying a read-only analysis with output generation, but lacks details on what 'minimal updates' entails (e.g., format, scope), whether it modifies files, error handling, or performance considerations. This is inadequate for a tool with 3 parameters and no output schema.

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 front-loads the core action ('analyze differences') and outcome ('provide minimal updates'). There is zero waste, making it easy for an AI agent to parse quickly without unnecessary details.

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 complexity of code diff analysis, 3 parameters, no annotations, and no output schema, the description is incomplete. It doesn't explain the output format (e.g., patch, summary), error cases, or how 'minimal updates' are derived, leaving significant gaps for an AI agent to use the tool effectively.

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 schema description coverage is 100%, with clear descriptions for each parameter (filePath, newContent, oldContent). The description adds no additional meaning beyond the schema, such as explaining how parameters interact (e.g., oldContent vs. newContent comparison) or usage nuances. Baseline 3 is appropriate as the 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 'analyze' and the resource 'differences between code versions', with the specific outcome 'provide minimal updates'. It distinguishes from siblings like 'extract_code_context' or 'optimize_imports' by focusing on diff analysis rather than extraction or optimization. However, it doesn't explicitly differentiate from all siblings (e.g., 'update_config' might also involve updates), keeping it from a perfect score.

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. It doesn't mention prerequisites (e.g., needing old and new code versions), exclusions, or compare to siblings like 'get_cached_context' for historical analysis. Usage is implied by the action but not explicitly defined, leaving gaps for an AI agent to infer context.

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

Related 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/FosterG4/mcpsaver'

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