xdebug-mcp

From var_dump() to xdebug_start_trace()

A Paradigm Shift in AI-Assisted Development

The Moment of Clarity ๐Ÿ‘€

I watched Claude Code debug PHP:

var_dump($variable);  // AI adds this
// Run tests, analyze output
var_dump($other);     // AI adds another
// Remove first, add third...
var_dump($result);    // Repeat... and cleanup...

๐Ÿ˜ฑ
"State-of-the-art AI was debugging like it was 1995"

The Root Cause ๐ŸŽฏ

It wasn't the AI's fault

We were asking a detective to solve a crime using only ๐Ÿ“ท crime scene photos.

What we provide:

  • ๐Ÿ“ท Code structure (static)
  • ๐Ÿ“ท Function signatures (static)
  • ๐Ÿ“ท Comments and documentation (static)
  • ๐Ÿ“ท Error messages (static)

But we never show what actually happened! ๐Ÿ“น๐Ÿ“บ๐ŸŽฅ

๐Ÿฝ๏ธ Feed the Beast

"AI is always hungry for data."

What AI really needs:

  • The exact sequence of function calls
  • Variable states at each step
  • Memory snapshots and performance metrics
  • Complete runtime behavior, not guesswork

The Transformation ๐Ÿš€

Before (Static Analysis) After (Runtime Intelligence)
var_dump()
AI examines code structure
โ†’ Makes educated guesses
โ†’ Suggests print debugging
xdebug_start_trace()
AI analyzes execution traces
โ†’ Identifies exact failure point
โ†’ Provides precise fix

GO AI NATIVE โœจ

Traditional Approach

// Multiple debugging attempts
// Modify code, test, repeat...

Forward Trace Approach

# Conditional breakpoint: Stop when problem occurs
./vendor/bin/xdebug-debug --break='checkout.php:89:$total<0' --steps=50 --exit-on-break -- php checkout.php

# AI analyzes and reports:
"Found it: $50 discount applied to $30 cart = -$20 total
 Fix: Add $this->recalculateDiscount() after removeItem()"

Try It Right Now ๐Ÿƒโ€โ™‚๏ธ

# 1. Clone from GitHub
git clone https://github.com/koriym/xdebug-mcp.git
cd xdebug-mcp && composer install

# 2. Create a simple test
echo '<?php
$result = "success";
if (rand(0,1)) { $result = null; }
echo $result;
?>' > test.php

# 3. Let AI analyze execution
./vendor/bin/xdebug-trace --context="Find why \$result becomes null" -- php test.php

# 4. Enable full AI integration
claude mcp add xdebug php "$(pwd)/vendor/bin/xdebug-mcp"

AI Superhuman Capabilities ๐Ÿฆพ

Challenge ๐Ÿ‘ค Human with IDE ๐Ÿค– AI with Runtime Data
Intermittent bugs Set breakpoint, hope to catch it Set conditional breakpoint, capture every occurrence
Complex flows Step through manually, miss details Process entire execution trace, identify all patterns
Race conditions Nearly impossible to catch Set time-based conditionals, capture exact timing

ForwardTraceโ„ข๏ธ: AI-Native Debugging ๐Ÿš€

Interactive Debugging

๐Ÿ“ท Photo Shooting
(Fragmented Snapshots)

// Step 1: Set breakpoint
// Step 2: Run to breakpoint (๐Ÿ“ท snapshot)
// Step 3: Check $user variable
// Step 4: Step into function
// Step 5: Another snapshot (๐Ÿ“ท)
// Step 6: Check another variable...

// โ†’ Multiple photos, missing the story

ForwardTrace

๐ŸŽฅ Video Shooting
(Complete Recording)

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

# 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

AI processes complete context โ†’ Provides insights to humans

Why ForwardTrace Works for AI ๐Ÿค–

Real Example: Authentication Bug

Traditional Way (2 hours)

  • Set breakpoints, step through code
  • Check variables one by one
  • Still guessing after 2 hours

ForwardTrace (30 seconds)

  • Capture complete execution flow
  • AI analyzes all function calls instantly
  • Problem solved in 30 seconds

AI can process complexity that overwhelms humans

The Vision ๐Ÿ”ฎ

A world where:

  • Debugging becomes systematic and data-driven
  • var_dump() and dd() feel like relics
  • Every developer has professional debugging workflows
  • AI assistants prefer to use execution traces themselves
  • Analysis over intuition using profiler data

Beyond Data: Schema Intelligence ๐Ÿง 

Traditional Approach:

"Here's a trace file. Figure out what it means."

Forward Traceโ„ข Schema Approach:

๐Ÿ“‹ Data Structure

  • Level: Call hierarchy depth
  • Time: Microsecond precision
  • Memory: Exact usage tracking
  • Parameters: Actual values

๐ŸŽฏ Schema AI Instructions

  • "Maximum function call depth reached. Critical for detecting recursion issues and stack depth analysis."
  • "Total database queries executed. Essential for N+1 problem detection and database performance analysis."
  • "Use this to decide optimal reading strategy for AI analysis."
  • "Number of unique functions executed. Indicates application complexity and code coverage."

Schema = Meaning + Data Structure + AI Guidance

Schema Shows AI How to Think ๐Ÿค–๐Ÿ’ญ

Xdebug Raw Output:

2    1    0    0.000489    401872    testFunction    1    test.php    35    2    $a=null $b=10
2    1    1    0.000521    403216
2    1    R              array(3) { [0]=>int(1) [1]=>int(2) [2]=>int(3) }

Schema-Guided AI Analysis:

{
  "trace_file": "/tmp/trace.1034012359.xt",
  "total_lines": 847,
  "unique_functions": 23,
  "max_call_depth": 12,
  "database_queries": 15,
  "specification": "https://xdebug.org/docs/trace",
  "analysis_context": "Debugging user authentication flow with database queries",
  "content": ["2\t1\t0\t0.000489\t401872\ttestFunction\t1\t\ttest.php\t35\t2\t$a=null $b=10"]
}

AI doesn't just parse data - it knows its mission

Schema-Driven Intelligence ๐Ÿš€

Traditional Data Exchange:

"Here's data in format X. Good luck figuring out what's important."

Schema-Driven Intelligence:

"Here's data with complete analysis instructions built-in."

We're not just giving AI runtime data.
We're giving AI the knowledge of how to use that data effectively.

Bridging the understanding gap between humans and AI

Inflection Point โšก

We can continue treating AI as a sophisticated autocomplete engine...

Or we can make AI our partner through complete transparency

Not just sharing our code, but our entire development context.

I wondered what kind of development that would lead to

Conditional Tracing Power ๐ŸŽฏ

Scenario: "Error only occurs when User ID is 0"

Traditional Way (Painful):

// Must pollute your code
if ($userId === 0) {
    var_dump($userData, $permissions, $sessionData);
    error_log("Debug: User ID 0 detected");
    // Risk of forgetting to remove in production...
}

Problems: Code pollution, production risks, cleanup

The xdebug-mcp Solution โœจ

Conditional Tracing (Smart):

# Wait silently until condition met, then start tracing
./vendor/bin/xdebug-debug --break='User.php:85:$userId==0' --steps=100 --exit-on-break -- php app.php

# Get complete execution history: how did we get $userId=0?
# AI analyzes complete execution trace leading to condition

Benefits: No code changes, complete context, safe

Another Example: "Crash Only When Array is Empty"

# Catch condition-specific problems with certainty
./vendor/bin/xdebug-debug --break='DataProcessor.php:42:empty($items)' --steps=200 --exit-on-break -- php batch.php

# AI analysis to identify root cause
# Analyzes the complete path to empty array condition

break + step + trace

  • โŒ Standard Xdebug: Breaks every time (inefficient)
  • โœ… Conditional Tracing: Fast execution until problem, detailed recording only when needed

xdebug-profile: See Performance ๐Ÿ”

# Microsecond-precision performance profiling
./vendor/bin/xdebug-profile --context="API performance analysis" -- php slow_api.php

# AI analyzes bottlenecks and provides optimization suggestions
# Result: Complete performance profile with bottleneck identification

"Found: fetchUser() called 847 times (72% execution time). Add caching at line 42."

AI sees: Function call counts, execution times, memory usage patterns

xdebug-debug: ForwardTrace with Conditional Breakpoints ๐Ÿ•ต๏ธ

# AI-optimized debugging with complete context
./vendor/bin/xdebug-debug --break='User.php:42:$user==null' --steps=150 --exit-on-break -- php app.php

# AI gets complete execution history leading to condition
# Provides comprehensive analysis of path to null user

AI receives comprehensive data:

  • Complete execution trace: All function calls leading to breakpoint
  • Variable evolution: How $user became null
  • Full context: Stack trace, memory, timing
  • Conditional capture: Only records when condition met

Revolutionary: AI sees the complete story, not just fragments

xdebug-phpunit: Smart Test Tracing ๐Ÿงช

# Trace only your test code, not PHPUnit internals
./vendor/bin/xdebug-phpunit --context="Test execution analysis" tests/UserTest.php::testComplexWorkflow

# AI analyzes test execution
# Shows detailed test execution path and failure analysis

Smart filtering: Traces your application code, ignores PHPUnit framework noise

AI benefits: Focus on actual business logic, not testing framework details

xdebug-coverage: Raw Xdebug Coverage - Any PHP Script ๐Ÿ“Š

# Works with any PHP script, not just PHPUnit
./vendor/bin/xdebug-coverage -- php ./vendor/bin/phpunit  # PHPUnit
./vendor/bin/xdebug-coverage -- php my-script.php         # Any script

# Native Xdebug format - fast AI understanding

Key advantages:

  • Native Xdebug format - no conversion overhead
  • Clean JSON output with vendor/tests filtering

๐ŸŒณ NEW: Branch Coverage + GraphViz Visualization

# New feature: Visual branch/path coverage analysis
./bin/xdebug-coverage --branch-coverage -- php app.php

# Single execution, multiple AI-ready outputs:
# โœ… Detailed branch coverage JSON
# โœ… GraphViz dot file (/tmp/paths.dot)  
# โœ… Visualization command included

# AI can immediately visualize
dot -Tpng /tmp/paths.dot -o /tmp/coverage_paths.png

AI Benefits:

  • ๐ŸŸข Executed paths (green/solid lines)
  • ๐Ÿ”ด Unexecuted paths (red/dashed lines)
  • ๐Ÿ“Š Branch-level detailed analysis
  • ๐ŸŽฏ Visual pattern recognition

"AI can see and understand code path diagrams"

MCP Tools ๐ŸŽฏ

4 Core AI-Optimized Tools:

๐Ÿ” ForwardTrace

Complete execution flow with all variable states

โšก Conditional Breakpoints

Smart capture only when conditions met

๐Ÿ“Š Performance Profiling

Comprehensive metrics and timing analysis

๐Ÿ“ˆ Coverage Analysis

Full context test coverage mapping

I want to see AI use these tools freely in the future

Beyond "Tests Pass"

The Modern Problem ๐Ÿค–

Quality Problem๐Ÿค–: Is "Passing Checks" Enough?

  • โœ… Unit Tests: 100% pass
  • โœ… Code Coverage: 100%
  • โœ… Static Analysis: MAX

But is the code actually efficient? ๐Ÿค”

Forward Trace Reveals the Truth ๐Ÿ”

Traditional Testing ๐Ÿ“Š

// Tests pass โœ…
assert($result === "John");
// But HOW was it obtained?

Forward Trace Analysis ๐ŸŽฏ

// Runtime reveals reality
DB query: 10,000 rows
Loop: 8,743 iterations
Time: 2.3 seconds
// Should be: 0.003 seconds!

"Correctness" โžก๏ธ "Efficiency" - The quality evolution AI demands

The Discovery Story ๐Ÿ“–

Interactive Debugger Shell

Original Vision ๐ŸŽฏ

"AI that uses IDE like human developers"

  • Interactive Xdebug shell
  • All 47 Xdebug commands supported
  • Step-by-step execution

Technical Challenge โš™๏ธ

Stateless MCP โšก Stateful Xdebug

Learning from AI ๐Ÿ’ก

"AI doesn't need this kind of interactive mechanism"

๐Ÿ› ๏ธ Developer's Intuition

  • "AI should use IDE like us"
  • "Step execution is necessary"
  • "Must provide all features"

๐Ÿค– AI's Actual Voice

  • "Give me all data at once"
  • "I want to find patterns"
  • "Interaction is unnecessary"

47 commands โ†’ Single Forward Trace

Let AI See How Your Code Truly Runs ๐Ÿ‘๏ธ

GitHub: github.com/koriym/xdebug-mcp

Install: composer require koriym/xdebug-mcp

Status Badges:

AI Native: YES Runtime Data: YES var_dump(): NO Guesswork: NO

Special thanks to Derick Rethans for creating Xdebug, the foundation that makes all of this possible.

โ€” Akihito Koriyama (@koriym)