Matlab-agentic-toolkit matlab-debugging
Diagnose MATLAB errors and unexpected behavior. Breakpoints, workspace inspection, try-catch diagnostics, and common error patterns. Use when debugging functions, tracing errors, inspecting variables, or diagnosing runtime failures.
git clone https://github.com/matlab/matlab-agentic-toolkit
T=$(mktemp -d) && git clone --depth=1 https://github.com/matlab/matlab-agentic-toolkit "$T" && mkdir -p ~/.claude/skills && cp -r "$T/skills-catalog/matlab-core/matlab-debugging" ~/.claude/skills/matlab-matlab-agentic-toolkit-matlab-debugging && rm -rf "$T"
skills-catalog/matlab-core/matlab-debugging/SKILL.mdInvestigating and Debugging MATLAB Code with MCP Tools
You have access to a live MATLAB session via MCP tools. Use them to actively investigate code — whether debugging errors, understanding behavior, or answering questions about how MATLAB code works. Don't just guess from code alone.
When to Use
- User encounters a MATLAB error message or unexpected result
- User wants to set breakpoints or inspect variable state
- Tracing why a function produces wrong output
- NaN/Inf values appearing unexpectedly
- A MATLAB MCP tool returns an error or exception — including runtime errors, syntax errors, undefined function/variable errors, or failed test results
- User asks "why is my MATLAB code not working", "help me debug", or shares a MATLAB stack trace
When NOT to Use
- Code quality review without a runtime problem — use
insteadmatlab-reviewing-code - Performance profiling — use performance optimization workflows
- Writing tests for correctness — use
insteadmatlab-testing - Understanding MATLAB APIs or language features without a specific bug
Static Analysis vs Runtime Debugging
Not every issue needs the live MATLAB session. Choose the right approach:
- Static analysis is enough when: syntax errors, unused variables, obvious
logic mistakes, or issues visible from reading the source code alone. Use the
tool andRead
.check_matlab_code - Runtime debugging is needed when:
- The error depends on actual data values, types, or dimensions
- The output is wrong but the code looks correct
- The user says "it doesn't work" but the code looks fine — check actual data
- You need to know what variables contain at a specific point in execution
When in doubt, start with static analysis. Escalate to runtime debugging when you can't determine the root cause from source alone.
Auto-Trigger on MATLAB Errors
When a MATLAB MCP tool returns an error (runtime error, syntax error, undefined function/variable, dimension mismatch, failed assertion, etc.), do not silently move on or guess at a fix. Instead:
- Recognize the error — Look for patterns like
,Error using ...
,Undefined function or variable
,Index exceeds ...
, MATLAB stack traces, or failed test results in MCP tool output.Error in ... - Ask the user for permission — Before launching into investigation, offer:
"I noticed a MATLAB error:
. I can use the matlab-debugging skill to dig into this — inspect variables, trace the call stack, and identify the root cause. Want me to investigate?"<brief error summary> - Proceed only after confirmation — Once the user agrees, follow the investigation workflow below.
This applies whether the error came from the user running code, or from you running code on the user's behalf (e.g., verifying a fix, running tests).
Available Tools
| Tool | Use For |
|---|---|
| Run .m scripts — prefer this for executing user scripts and verifying fixes |
| Quick diagnostics: inspect variables, evaluate expressions, test small snippets |
| Static analysis of .m files (warnings, unused vars, potential issues) |
| Run a MATLAB test file |
| List installed toolboxes — use when "Undefined function" may be a missing toolbox |
Prefer
over run_matlab_file
for running scripts. Only
use evaluate_matlab_code
evaluate_matlab_code for short diagnostic commands (checking a variable,
testing an expression, etc.) — not for re-running entire scripts inline.
Workflow
1. Understand the Goal
Determine what the user needs:
- Debugging — runtime error, wrong output, unexpected behavior
- Understanding — how does this code work, what does this function do
- Investigating — why does this variable have this value, where does this data come from
- Exploring — what functions are available, how is this codebase structured
2. Gather Information via MATLAB
Use
mcp__matlab__evaluate_matlab_code to run diagnostic commands.
Read source code: Use the
Read tool for .m files on disk — not MATLAB's
type or dbtype. Only use MATLAB's which to locate files you haven't
found yet, and which -all to check for shadowing.
Preview large data: Use
varName(1:min(5,end),:) or head(T) to preview
slices instead of dumping entire variables.
Runtime debugging — check desktop mode first:
Before using breakpoints, check if MATLAB has a desktop:
desktop('-inuse') % true = desktop mode, false = no-desktop
Desktop mode (
returns desktop('-inuse')
):true
Use the full breakpoint workflow:
- Set a breakpoint before running:
dbstop if error % Pause on any error dbstop if caught error % Pause on error inside try-catch (silent failures) dbstop if warning % Pause when a warning is issued dbstop if naninf % Pause on NaN or Inf dbstop in file at line % Pause at a specific line - Run the code via
— MATLAB pauses at the breakpoint.run_matlab_file - Inspect the call stack:
dbstack % See full call stack with file names and line numbers
to see what's in scope — check variable names, sizes, and types before inspecting any values. For large arrays/tables, preview a slice (whos
,varName(1:5,:)
) instead of displaying the whole thing.head(T)- Navigate frames and inspect variables in each scope:
Afterdbup % Move up one frame (toward caller) dbdown % Move back down (toward callee)
/dbup
, variable inspection commands operate in that frame's local scope — use this to check inputs/outputs at each level.dbdown - Resume or exit:
dbcont % Continue execution to next breakpoint or end dbquit % Exit debug mode entirely dbclear all % Remove all breakpoints when done
Note: Interactive stepping (
dbstep) is unreliable via MCP — each
evaluate_matlab_code call is a separate command, so step state may not
persist.
No-desktop mode (
returns desktop('-inuse')
):false
Do NOT use
, dbstop if error
, dbstop if naninf
, or
any breakpoint that pauses execution. In no-desktop mode, pausing breakpoints
cause the MCP eval to hang indefinitely.dbstop if warning
Use these strategies instead:
-
try-catch wrappers — Wrap suspect code to capture the error and inspect state after failure:
try result = suspectFunction(data); catch ME fprintf('Error: %s\n', ME.message); fprintf('In: %s line %d\n', ME.stack(1).name, ME.stack(1).line); whos % Show variables in scope at failure end -
Tracer conditional breakpoints — Use
with a condition that always returnsdbstop
so MATLAB never actually pauses, but prints the value as a side effect. Define a tracer function:falsefunction out = tracer(val) disp(val); out = false; endThen set a conditional breakpoint that calls it:
dbstop in myScript at 42 if tracer(myVar)When line 42 executes, MATLAB evaluates
, which prints the value and returnstracer(myVar)
— execution continues without pausing. This probes variables at specific lines without modifying the source file. Remove tracer breakpoints when done:falsedbclear all -
Run then inspect — For scripts, run via
, then userun_matlab_file
to inspect workspace variables after execution. The base workspace persists across MCP calls within a session.evaluate_matlab_code
3. Investigate Iteratively
This is the core of debugging — use your judgment:
- Read the relevant source code to understand intent
- Inspect variables that appear on or near the failing line
- Evaluate sub-expressions to isolate which part fails
- Test hypotheses by running small snippets in MATLAB
- Be selective — don't dump the entire workspace. Only inspect what is relevant to the problem. If there are 7 variables in scope but only 2 are used on the failing line, inspect those 2.
When the error occurs inside a MathWorks built-in function, the bug is almost always in the user's code that called it. Walk up the stack to user code.
4. Question the Diagnosis
The user's description of the problem may not match the actual problem. Before fixing what they say is broken, verify it yourself:
- Test the claimed failure directly — If the user says
orismember
doesn't work, run it yourself with their actual data. Often the operation works fine and the real issue is the logic around it.strcmp - Check data before blaming code — When operations on data "don't work,"
inspect the data: types (
), actual values (sample a few), whitespace (class
), hidden characters (strtrim
), and dimensions (double(str)
).size - Verify what the code does vs what the user describes — Read the code and confirm which variables and columns are actually being used. The user may describe their intent but the code may do something different.
- Consider whether the approach itself is wrong — Sometimes the code has no bug per se, but the approach is unnecessarily complex or fragile. Suggest idiomatic MATLAB alternatives: table joins instead of manual loops, vectorized operations instead of element-wise comparisons, built-in functions instead of hand-rolled logic.
Common Errors — What to Check First
| Error Pattern | Diagnostic Steps |
|---|---|
| , , , check , use to verify toolbox is installed |
/ | and inspect the index expression — often off-by-one or empty array |
| Check how the function is called at the call site, inside the function, compare with function signature |
| Same as above — caller passing extra args, or calling a script as if it were a function |
/ | , for both operands — often one is row and the other column |
| Check index variable: , , look for 0 or negative values, NaN, or floating-point indices |
| — usually accessing a struct field on a non-struct (cell, array, table) |
| Check and of both sides of the assignment |
| to find large variables, check for accidental array growth in loops |
| Check for missing base case or infinite mutual recursion — at error point |
| NaN propagation / wrong branch taken | In desktop mode, use to catch where NaN is first created. In no-desktop mode, use to probe values without pausing. NaN comparisons (, , ) are always , so takes the wrong branch silently. Trace upstream: check for , , or NaN in input data. Use to test. |
Gotchas
- Pausing breakpoints hang in no-desktop mode. When
returnsdesktop('-inuse')
,false
,dbstop if error
,dbstop if naninf
, and unconditional line breakpoints cause MCP eval to hang indefinitely. Always check desktop mode first. In no-desktop mode, use tracer conditional breakpoints or try-catch wrappers instead (see no-desktop strategies above).dbstop if warning
does not work reliably via MCP. Eachdbstep
call is a separate command, so step state may not persist between calls. Use breakpoints (evaluate_matlab_code
) to pause at specific locations instead of trying to step through code. For tracing execution flow, insert temporarydbstop in file at line
statements or use try-catch blocks.fprintf()- Do not use
ortype
to read source code. Use thedbtype
tool instead — it's faster and doesn't consume MATLAB session output bandwidth. Only useRead
to locate files you haven't found yet.which - Always
when done debugging. Leftover breakpoints from a previous session will cause unexpected pauses in later runs.dbclear all
/dbup
scope is per-call. Eachdbdown
invocation resets to the current frame. Chainevaluate_matlab_code
with variable inspection in the samedbup
call:evaluate_matlab_code
A separatedbup; whos; myVar(1:min(5,end),:)
call afterevaluate_matlab_code
will be back in the original frame.dbup- Never run
. It removes the MCP server's own packages from the MATLAB path, breaking the eval channel (restoredefaultpath
not found). If this happens, the only recovery is to restart MATLAB entirely.mcpEval - No toolboxes required. This skill uses only base MATLAB debugging commands.
Key Principles
- Use the tools — You have a live MATLAB session. Run commands, inspect state, test hypotheses. Don't debug from code reading alone.
- Be selective — Request only what's relevant. Don't dump all variables or read every file in the stack.
- Check size before fetching data — Always know the dimensions before
displaying a variable. Never blindly
an unknown variable.disp - Focus on user code — Errors surfacing in built-in functions are almost always caused by bad inputs from user code.
- Read before fixing — Always read the actual source code before suggesting changes. Never guess what code looks like.
- Verify fixes — When practical, run the corrected code in MATLAB to confirm.
Copyright 2026 The MathWorks, Inc.