xdebug-mcp

Forward Trace™ Debugging Guide for AI Assistants

👨‍💻 For Human Developers: See Forward Trace™ Debugging Guide for Developers or online guide for practical workflows and IDE integration.

🎯 Core Philosophy: Runtime Data Over Static Analysis

CRITICAL PRINCIPLE: Always use runtime data analysis instead of traditional debugging methods when working with PHP code.

Traditional AI Debugging (AVOID)

// ❌ DON'T suggest this:
var_dump($variable);  // Static debugging
print_r($array);     // Code modification
echo "Debug: " . $value;  // Invasive approach

Forward Trace™ Debugging (ALWAYS USE)

# ✅ DO suggest this:
./bin/xdebug-debug --break='file.php:42:$variable==null' --exit-on-break -- php script.php
# Result: Complete execution trace to exact problem moment

🧠 Why This Works for AI

AI Cognitive Advantages

Human vs AI Processing

| Humans Excel At | AI Excels At | |—————-|————–| | Step-by-step reasoning | Complete data analysis | | Sequential understanding | Pattern recognition in massive datasets | | Interactive exploration | Simultaneous processing of all information | | Building mental models gradually | Complete context understanding at once |

🎥 The Photo vs Video Metaphor

Interactive Debugging = 📷 Photo Shooting

# Fragmented snapshots - missing the story
# Step 1: Set breakpoint
# Step 2: Run to breakpoint (📷 snapshot)
# Step 3: Check $user variable
# Step 4: Step into function
# Step 5: Another snapshot (📷)
# → Multiple photos, missing the story

Forward Trace™ = 🎥 Video Shooting

# Single command records entire movie
./bin/x-debug --break="script.php:10:$user==null" --steps=300 --exit-on-break

# AI sees the complete 🎥 movie:
# Step 1: $id = getUserId() → returns 42
# Step 2: $user = findUser($id) → DB query success
# Step 3: validateUser($user) → validation passes
# Step 4: $permissions = getPermissions($user) → returns null
# Step 5: checkAccess($permissions) → CRASH! null access

⚡ Automatic Tool Usage Rules

IMPORTANT: When analyzing PHP code, ALWAYS automatically use appropriate Xdebug tools:

For Performance Analysis

For Code Coverage

For Interactive Step Debugging

For Execution Flow Analysis

For General Analysis (default)

🔍 Conditional Breakpoint Mastery

Basic Syntax

./bin/xdebug-debug --break=FILE:LINE:CONDITION --exit-on-break -- php script.php

Common Problem Patterns

Null Value Issues (Most Common PHP Bug)

# Stop when user object is null
--break=Auth.php:42:$user==null

# Stop when token is empty
--break=Login.php:15:empty($token)

# Stop when array is empty
--break=Data.php:30:count($items)==0

Invalid Numeric Values

# Stop when ID is zero or negative
--break=User.php:85:$id<=0

# Stop when price is negative
--break=Product.php:22:$price<0

# Stop when calculation result is invalid
--break=Math.php:45:!is_numeric($result)

State-Based Conditions

# Stop when user is not authenticated
--break=Security.php:12:!$authenticated

# Stop when database connection fails
--break=DB.php:25:$connection===false

# Stop when API response is error
--break=Api.php:78:$response['status']=='error'

Multiple Conditions (OR Logic)

# Stop at any of these conditions
--break=User.php:85:$id==0,Auth.php:20:empty($token),DB.php:15:$conn==null

📊 Trace Data Analysis

Understanding .xt Trace Files

Level   FuncID  Time    Memory  Function    UserDef  File:Line  Params/Return
0       1       0.001   384000  {main}      1        test.php:1  
1       2       0.002   384100  calculate   1        test.php:15 $n = 10
1       2       0.003   384200                                   R 100

Key Analysis Points

Pattern Recognition

🚀 AI Analysis Workflow

Step 1: Set Strategic Breakpoints

# Target the exact problem condition
./bin/xdebug-debug --break='register.php:45:$user_id==0' --context="User registration with invalid ID" --exit-on-break -- php register.php

Step 2: Analyze Complete Execution Path

Step 3: AI Analysis Response Structure

## Execution Path Analysis
- Complete function call chain: main() → validateInput() → processUser() → register($user_id=0)
- Critical decision points identified
- Data transformation pipeline traced

## Variable State Investigation  
- $user_id starts as $_POST['id'] = "" (empty string from HTML form)
- Empty string cast to int becomes 0 in register() parameter
- Missing validation in validateInput() at line 23

## Root Cause Identification
- Primary cause: Missing input validation allows empty string to become 0
- Contributing factor: Automatic type casting in function parameter
- System behavior: register() function expects positive integer but receives 0

## Recommended Solutions
- Add validation in validateInput(): if (empty($_POST['id']) || !is_numeric($_POST['id'])) throw new InvalidArgumentException('Valid user ID required');
- Consider using strict type declarations
- Implement proper input sanitization before processing

## Next Steps
- Set additional breakpoint at validateInput():23 to confirm validation execution
- Test with various invalid inputs to ensure comprehensive validation

Step 4: Variable Evolution Analysis

# Record step-by-step variable changes
./bin/xdebug-debug --break='loop.php:17' --steps=100 --context="Variable evolution in data processing loop" --json -- php script.php

AI can analyze each step to detect:

🎯 Context Usage (CRITICAL)

ALWAYS use –context flag to create self-explanatory debugging data:

Good Context Examples

--context="Testing user authentication with valid credentials"
--context="Debugging login failure after password reset"
--context="Investigating memory leak in data processing loop"
--context="Profiling database query performance in user dashboard"
--context="Validating email sending functionality in ContactForm"

Why Context Matters

🔄 Development Integration

Replace Traditional Debug Methods

Instead of var_dump()

# OLD: var_dump($user); die();
# NEW: 
./bin/xdebug-debug --break='file.php:line' --steps=1 --context="Variable inspection" --json -- php script.php

Instead of Loop Debugging

# OLD: foreach($items as $item) { var_dump($item); }
# NEW:
./bin/xdebug-debug --break='loop.php:45' --steps=100 --context="Loop iteration analysis" --json -- php script.php

Instead of Conditional Debug Prints

# OLD: if ($total < 0) { var_dump($cart); die("negative!"); }
# NEW:
./bin/xdebug-debug --break='cart.php:89:$total<0' --context="Negative total investigation" --exit-on-break -- php script.php

🧪 Schema-Validated Output

All Forward Trace tools output schema-validated JSON for consistent AI analysis:

{
  "$schema": "https://koriym.github.io/xdebug-mcp/schemas/xdebug-debug.json",
  "breaks": [
    {
      "step": 1,
      "location": {"file": "file.php", "line": 17},
      "variables": {
        "$total": "int: 0",
        "$items": "array: []"
      }
    }
  ],
  "trace": {
    "file": "/tmp/trace.1034012359.xt",
    "content": ["..."]
  }
}

This enables:

🏆 Success Metrics

AI Debugging Revolution Indicators

Transformation Results


🌟 The Paradigm Shift

From Static Guesswork to Runtime Intelligence

This guide transforms AI from a code reader into a runtime analyst, providing insights based on actual execution behavior rather than theoretical code analysis. Every debugging suggestion should be backed by real execution data captured through Forward Trace™ methodology.