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
| Name | Required | Description | Default |
|---|---|---|---|
| request | Yes |
Implementation Reference
- src/mcp_pyrefly/server.py:81-276 (handler)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, ) - src/mcp_pyrefly/server.py:32-43 (schema)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" ) - src/mcp_pyrefly/server.py:45-60 (schema)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" ) - src/mcp_pyrefly/server.py:80-80 (registration)Tool registration decorator for `check_code`.
@mcp.tool()