Skip to main content
Glama

analyze_changes

Extracts and structures git diff data, providing context and analysis instructions for AI models via the Model Context Protocol in Lucidity MCP.

Instructions

Prepare git changes for analysis through MCP.

This tool examines the current git diff, extracts changed code, and prepares structured data with context for the AI to analyze.

The tool doesn't perform analysis itself - it formats the git diff data and provides analysis instructions which get passed back to the AI model through the Model Context Protocol.

Args: workspace_root: The root directory of the workspace/git repository path: Optional specific file path to analyze

Returns: Structured git diff data with analysis instructions for the AI

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathNo
workspace_rootNo

Implementation Reference

  • The main tool handler function decorated with @mcp.tool("analyze_changes"). It fetches git diffs, parses changes per file, detects language, generates analysis prompts using analyze_changes_prompt, and returns structured data including prompts and instructions for AI analysis via MCP.
    @mcp.tool("analyze_changes")
    def analyze_changes(workspace_root: str = "", path: str = "") -> dict[str, Any]:
        """Prepare git changes for analysis through MCP.
    
        This tool examines the current git diff, extracts changed code,
        and prepares structured data with context for the AI to analyze.
    
        The tool doesn't perform analysis itself - it formats the git diff data
        and provides analysis instructions which get passed back to the AI model
        through the Model Context Protocol.
    
        Args:
            workspace_root: The root directory of the workspace/git repository
            path: Optional specific file path to analyze
    
        Returns:
            Structured git diff data with analysis instructions for the AI
        """
        logger.info("Starting git change analysis%s in workspace %s", f" for {path}" if path else "", workspace_root)
    
        if not workspace_root:
            return {"status": "error", "message": "workspace_root parameter is required"}
    
        # Get git diff
        logger.debug("Fetching git diff...")
        diff_content, staged_content = get_git_diff(workspace_root, path)
    
        # Get list of all changed files
        changed_files = get_changed_files(workspace_root)
    
        # Combine diff and staged content for complete changes
        combined_diff = diff_content
        if staged_content:
            combined_diff = combined_diff + "\n" + staged_content if combined_diff else staged_content
    
        logger.debug("Combined diff size: %d bytes", len(combined_diff))
    
        if not combined_diff:
            logger.warning("No changes detected in git diff")
            return {"status": "no_changes", "message": "No changes detected in the git diff", "file_list": []}
    
        # Parse the diff
        logger.debug("Parsing git diff...")
        parsed_diff = parse_git_diff(combined_diff)
    
        if not parsed_diff:
            logger.warning("No parseable changes in git diff")
            return {
                "status": "no_changes",
                "message": "No parseable changes detected in the git diff",
                "file_list": changed_files,
            }
    
        logger.info("Found %d files with changes to analyze", len(parsed_diff))
    
        # Process each changed file
        analysis_results = {}
        file_list = []
    
        for filename, diff_info in parsed_diff.items():
            logger.debug("Processing file: %s (status: %s)", filename, diff_info["status"])
            file_list.append(filename)
    
            # Skip certain files
            if filename.endswith((".lock", ".sum", ".mod", "package-lock.json", "yarn.lock", ".DS_Store")):
                logger.debug("Skipping excluded file: %s", filename)
                continue
    
            try:
                # Extract original and modified code
                logger.debug("Extracting code changes for %s", filename)
                original_code, modified_code = extract_code_from_diff(diff_info)
    
                # Skip if no significant code changes
                if len(modified_code.strip()) < 10:
                    logger.debug("Skipping %s - insufficient code changes (< 10 chars)", filename)
                    continue
    
                # Detect language
                language = detect_language(filename)
                logger.debug("Detected language for %s: %s", filename, language)
    
                # Create a prompt for analysis
                logger.debug("Generating analysis prompt for %s", filename)
                from ..prompts import analyze_changes_prompt
    
                analysis_prompt = analyze_changes_prompt(
                    code=modified_code, language=language, original_code=original_code if original_code else None
                )
                logger.debug("Generated analysis prompt of size: %d chars", len(analysis_prompt))
    
                # Store the analysis prompt to be returned
                analysis_results[filename] = {
                    "status": diff_info["status"],
                    "language": language,
                    "analysis_prompt": analysis_prompt,
                    "raw_diff": diff_info["raw_diff"],
                    "original_code": original_code,
                    "modified_code": modified_code,
                }
                logger.info("Successfully analyzed %s", filename)
    
            except Exception as e:
                logger.error("Error analyzing %s: %s", filename, e)
                analysis_results[filename] = {"status": "error", "message": f"Error analyzing file: {e!s}"}
    
        logger.info("Code analysis complete - processed %d files", len(analysis_results))
    
        # Return results with instructions for AI analysis
        return {
            "status": "success",
            "file_count": len(analysis_results),
            "file_list": file_list,
            "all_changed_files": changed_files,
            "results": analysis_results,
            "instructions": """
    This data contains git changes that you should analyze for code quality issues.
    As an AI model receiving this through MCP, your task is to:
    
    1. Review each changed file:
       - Examine the raw diff showing the exact changes
       - Compare the original and modified code
       - Consider the language and file status (added, modified, deleted)
    
    2. For each file, perform the analysis following the provided analysis prompt:
       - Analyze relevant quality dimensions
       - Assign severity levels to issues you identify
       - Provide line-specific explanations
       - Suggest concrete improvements
    
    3. After analyzing all files, provide:
       - An overall assessment of the code changes
       - A prioritized list of improvements
       - Any patterns or systemic issues you've identified
    
    Your analysis should be thorough yet focused on actionable improvements.
    """,
        }
  • Package-level registration: imports analyze_changes from code_analysis.py and adds it to __all__, making it available when importing from lucidity.tools.
    from .code_analysis import analyze_changes
    
    __all__ = ["analyze_changes"]
  • Helper function decorated with @mcp.prompt("analyze_changes"). Generates a structured prompt for code change analysis, used inside the handler to prepare prompts for each changed file.
    @mcp.prompt("analyze_changes")
    def analyze_changes_prompt(code: str, language: str, original_code: str | None = None) -> str:
        """Generate a prompt for analyzing git code changes via MCP.
    
        This function creates a structured prompt that will be passed back
        to the AI model through the Model Context Protocol, guiding it to
        analyze git changes effectively.
    
        Args:
            code: The changed code to analyze
            language: The programming language of the code
            original_code: The original code before changes (optional)
    
        Returns:
            A formatted prompt for the AI to analyze git changes
        """
        return generate_analysis_prompt(code, language, original_code)
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses that the tool 'examines the current git diff' and 'formats the git diff data,' implying it's a read-only operation without side effects. However, it doesn't mention behavioral traits like error handling, performance considerations, or specific constraints (e.g., git repository must be initialized). It adds some context but isn't comprehensive.

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?

The description is appropriately sized and front-loaded, starting with the core purpose. It uses bullet points for Args and Returns, which improves structure. However, some sentences could be more concise (e.g., 'through the Model Context Protocol' is slightly redundant), and the overall flow is clear but not maximally efficient.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no annotations, 0% schema coverage, and no output schema, the description is moderately complete. It covers purpose, parameters, and return value at a high level, but lacks details on error cases, output structure, or operational constraints. For a tool with two parameters and no structured support, it's adequate but has gaps.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It explains both parameters: 'workspace_root: The root directory of the workspace/git repository' and 'path: Optional specific file path to analyze.' This adds clear meaning beyond the schema's basic titles. However, it doesn't detail format constraints (e.g., absolute vs. relative paths), so it's not a perfect 5.

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: 'examines the current git diff, extracts changed code, and prepares structured data with context for the AI to analyze.' It specifies the verb (examines, extracts, prepares) and resource (git diff/changed code). However, since there are no sibling tools, it doesn't need to distinguish from alternatives, so it doesn't reach the full 5.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage context by stating 'Prepare git changes for analysis through MCP' and 'The tool doesn't perform analysis itself,' which suggests it's a preprocessing step. However, it lacks explicit guidance on when to use it versus other potential tools (e.g., direct analysis tools) or prerequisites, as there are no siblings to compare against.

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/hyperb1iss/lucidity-mcp'

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