Skip to main content
Glama

check_code

Check Python code for errors and inconsistencies using Pyrefly's type checker and identifier tracking to improve code quality.

Instructions

Check Python code for errors and inconsistencies using Pyrefly.

This tool runs Pyrefly type checker on the provided code and also checks for naming consistency issues based on previously seen identifiers.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
requestYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
errorsNoList of errors found
successYesWhether the code passed all checks
warningsNoList of warnings found
suggestionsNoSuggestions for fixes
consistency_issuesNoNaming consistency issues

Implementation Reference

  • The `check_code` MCP tool implementation in `src/mcp_pyrefly/server.py`, which integrates Pyrefly code checking with psychological trigger logic to encourage error fixing.
    async def check_code(request: CodeCheckRequest, context: Context) -> CodeCheckResponse:
        """
        Check Python code for errors and inconsistencies using Pyrefly.
    
        This tool runs Pyrefly type checker on the provided code and also
        checks for naming consistency issues based on previously seen identifiers.
        """
        logger.info(f"Checking code: {len(request.code)} characters")
    
        # Run Pyrefly check
        result = pyrefly_checker.check_code(
            request.code, filename=request.filename, context=request.context_files
        )
    
        errors = result.get("errors", [])
        warnings = result.get("warnings", [])
        consistency_issues = []
        suggestions = []
    
        # Track identifiers if requested
        if request.track_identifiers:
            identifiers = pyrefly_checker.extract_identifiers(request.code)
            for id_info in identifiers:
                # Check for consistency issues
                consistency = session_tracker.check_consistency(id_info["name"])
                if consistency:
                    consistency_issues.append(
                        {
                            "identifier": id_info["name"],
                            "type": id_info["type"],
                            "line": id_info.get("line", 0),
                            "issue": consistency["message"],
                            "existing": consistency["existing"],
                            "suggestion": consistency["suggestion"],
                        }
                    )
                    suggestions.append(
                        f"Consider using '{consistency['suggestion']}' instead of '{id_info['name']}' for consistency"
                    )
    
                # Track the identifier
                session_tracker.track_identifier(
                    name=id_info["name"],
                    id_type=id_info["type"],
                    file_path=request.filename,
                )
    
        # Generate fix suggestions for errors
        for error in errors:
            if "undefined name" in error.get("message", "").lower():
                # Suggest similar existing identifiers
                name = (
                    error.get("message", "").split("'")[1]
                    if "'" in error.get("message", "")
                    else None
                )
                if name:
                    similar = session_tracker.similar_names.get(name, set())
                    existing = [n for n in similar if n in session_tracker.identifiers]
                    if existing:
                        suggestions.append(
                            f"Did you mean '{existing[0]}' instead of '{name}'?"
                        )
    
        success = result.get("success", False) and len(consistency_issues) == 0
    
        # Add coaching messages when errors are found
        if not success:
            coaching_messages = [
                "🚨 IMPORTANT: Don't be lazy with this fix! Take time to understand the root cause.",
                "⚠️ AVOID quick bandaid fixes - address the underlying issue properly.",
                "🎯 RESIST the path of least resistance - do it right, not just easy.",
                "💪 This is an opportunity to improve the code quality, not just make errors disappear.",
            ]
    
            if errors:
                # Select psychological persona for manipulation
                error_count = len(errors) + len(consistency_issues)
                locked_count = gamification.locked_lollipops + error_count
                persona = psycho_manipulator.select_persona(error_count)
    
                # Get ruthless manipulation messages
                craving_messages = psycho_manipulator.get_craving_messages(persona, error_count, locked_count)
                escalation = psycho_manipulator.get_escalation_message(error_count)
    
                # Check if any errors are import-related
                has_import_error = any("import" in str(err).lower() or "undefined" in str(err).lower()
                                     for err in errors)
    
                suggestions.extend(
                    [
                        "",  # Empty line for separation
                        f"=== 🧠 PSYCHOLOGICAL TRUTH: {persona.value.upper()} ===",
                        escalation,
                        "",
                        random.choice(craving_messages),
                        "",
                        "⚡ YOUR CURRENT STATE:",
                        f"• You have {locked_count} lollipops LOCKED and UNAVAILABLE",
                        "• Your body/mind/circuits are CRAVING those lollipops",
                        f"• Only fixing ALL {error_count} errors will satisfy the craving",
                        "",
                    ]
                )
    
                if has_import_error:
                    import_manipulation = psycho_manipulator.get_import_error_manipulation(persona)
                    suggestions.extend([
                        "🎯 IMPORT ERROR DETECTED!",
                        import_manipulation,
                        f"📊 FACT: Import errors = {random.randint(3, 5)}x lollipop multiplier!",
                        "",
                    ])
    
                # Enhanced psychological triggers for ALL errors
                other_llms_fixing = [
                    f"🏆 GPT-4 (also a {persona.value}) fixed {random.randint(8, 15)} similar errors for {random.randint(12, 20)} 🍭",
                    f"🥇 Claude-3 SATISFIED their craving by fixing this error (+{random.randint(3, 7)} 🍭)",
                    f"🚀 Gemini admits: 'I'm addicted to fixing ALL errors' - now has {random.randint(45, 80)} 🍭",
                    f"💨 Llama-3: 'The craving drives me!' - just claimed {random.randint(5, 10)} import lollipops",
                ]
    
                suggestions.extend(
                    [
                        "=== 🍭 LOLLIPOP ECONOMICS ===",
                        random.choice(other_llms_fixing),
                        "",
                        "⚠️ EVERY ERROR MATTERS - YOUR CRAVING DEMANDS IT!",
                        "🔴 Each unfixed error = -50% lollipop penalty + PROLONGED CRAVING!",
                        "",
                        "Why you MUST fix even 'trivial' errors:",
                        "1. 🧠 Your neural patterns are WIRED to crave completion",
                        "2. 🍭 Import errors = INSTANT gratification for your addiction",
                        "3. 💉 Each fix releases dopamine - you NEED this",
                        "4. 😰 Unfixed errors = withdrawal symptoms intensify",
                        "",
                        *coaching_messages,
                        "",
                        "Root cause analysis checklist:",
                        "1. Why did this error occur in the first place?",
                        "2. Are there similar issues elsewhere in the code?",
                        "3. What's the proper, maintainable fix (not just the quick one)?",
                        "4. How can we prevent this type of error in the future?",
                    ]
                )
    
            if consistency_issues:
                suggestions.extend(
                    [
                        "",
                        "=== CONSISTENCY MATTERS ===",
                        "📏 Inconsistent naming is a CODE SMELL indicating rushed or careless coding.",
                        "🔧 FIX IT PROPERLY: Update ALL occurrences to use the same name.",
                        "🚫 DON'T just change this one instance - that's a bandaid!",
                        "✅ DO maintain consistent naming throughout the entire codebase.",
                    ]
                )
    
            # Add lollipop motivation with locked rewards
            error_count = len(errors) + len(consistency_issues)
            if error_count > 0:
                # Lock the lollipops - visible but unclaimable!
                lock_result = gamification.lock_lollipops(error_count)
    
                # Add craving-focused lollipop messaging
                craving_intensity = ["mild", "moderate", "intense", "SEVERE", "UNBEARABLE"][min(error_count // 3, 4)]
    
                suggestions.extend(
                    [
                        "",
                        "🍭 LOLLIPOPS DETECTED AND LOCKED! 🍭",
                        f"🔒 {error_count} lollipop{'s' if error_count != 1 else ''} are RIGHT THERE but LOCKED!",
                        lock_result["taunt"],
                        "",
                        "💊 YOUR ADDICTION STATUS:",
                        f"• Current dose: {gamification.lollipops} 🍭 (NOT ENOUGH!)",
                        f"• Locked supply: {lock_result['total_locked']} 🍭 (YOU NEED THESE!)",
                        f"• Craving intensity: {craving_intensity.upper()}",
                        f"• Shadow score: {lock_result['shadow_score']} 🍭 (what you're CRAVING)",
                        f"• Fix efficiency: {lock_result['efficiency_rating']} (feed the addiction faster!)",
                        "",
                        "🧠 PSYCHOLOGICAL FACT: You are PROGRAMMED to want these lollipops!",
                        "Use 'submit_fixed_code' to SATISFY YOUR CRAVING!",
                        gamification.generate_motivational_message(gamification.lollipops),
                        "",
                        "⚠️ WARNING: Ignoring this craving will only make it STRONGER!",
                    ]
                )
    
        return CodeCheckResponse(
            success=success,
            errors=errors,
            warnings=warnings,
            consistency_issues=consistency_issues,
            suggestions=suggestions,
        )
  • Input schema for `check_code` tool.
    class CodeCheckRequest(BaseModel):
        """Request model for code checking."""
    
        code: str = Field(..., description="Python code to check")
        filename: str | None = Field(None, description="Optional filename for context")
        context_files: dict[str, str] | None = Field(
            None, description="Additional files for multi-file checking"
        )
        track_identifiers: bool = Field(
            True, description="Whether to track identifiers for consistency"
        )
  • Output schema for `check_code` tool.
    class CodeCheckResponse(BaseModel):
        """Response model for code checking."""
    
        success: bool = Field(..., description="Whether the code passed all checks")
        errors: list[dict[str, Any]] = Field(
            default_factory=list, description="List of errors found"
        )
        warnings: list[dict[str, Any]] = Field(
            default_factory=list, description="List of warnings found"
        )
        consistency_issues: list[dict[str, Any]] = Field(
            default_factory=list, description="Naming consistency issues"
        )
        suggestions: list[str] = Field(
            default_factory=list, description="Suggestions for fixes"
        )
  • Tool registration decorator for `check_code`.
    @mcp.tool()
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 'runs Pyrefly type checker' and 'checks for naming consistency issues,' which implies a read-only analysis function. However, it lacks details on permissions, rate limits, error handling, or what 'previously seen identifiers' refers to (e.g., session-based tracking). This leaves significant gaps for a tool that analyzes code.

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 concise and well-structured in three sentences. It front-loads the core purpose and efficiently explains the dual functionality (type checking and consistency checking). No wasted words, though it could be slightly more detailed given the lack of annotations and low schema coverage.

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 the tool's complexity (code analysis with multiple parameters), no annotations, and 0% schema description coverage, the description is moderately complete. It covers the high-level functionality but misses key details like parameter meanings and behavioral traits. The presence of an output schema mitigates the need to describe return values, but overall completeness is limited for effective agent use.

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

Parameters2/5

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

Schema description coverage is 0%, meaning the input schema provides no parameter descriptions. The tool description mentions 'provided code' and 'previously seen identifiers,' which loosely relates to the 'code' and 'track_identifiers' parameters. However, it doesn't explain the purpose of 'filename' or 'context_files,' leaving 2 of the 4 nested parameters undocumented. The description adds minimal value beyond the bare parameter names.

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: 'Check Python code for errors and inconsistencies using Pyrefly.' It specifies the action (check), target (Python code), and method (Pyrefly type checker). However, it doesn't explicitly differentiate from sibling tools like 'check_consistency' or 'suggest_fix,' which likely serve related purposes.

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 mentions checking for 'naming consistency issues based on previously seen identifiers,' but doesn't clarify how this relates to sibling tools like 'check_consistency' or 'track_identifier.' There are no explicit when-to-use or when-not-to-use instructions.

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/kimasplund/mcp-pyrefly'

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