This document provides a complete reference for all tools available in mcp-debugger, based on real testing conducted on 2025-06-11.
- Session Management
- Breakpoint Management
- Execution Control
- State Inspection
- Additional Tools — list_supported_languages, attach_to_process, detach_from_process, list_threads
- IDE Mirror
- Language-Specific Tools
Creates a new debugging session.
Parameters:
language(string, required): The programming language to debug. Languages are discovered dynamically from installed adapters. The default fallback languages (when dynamic discovery is unavailable) are"python"and"mock". When all adapters are available, the full list is:"python","ruby","javascript","rust","go","java","dotnet","cpp","mock". The actual list depends on which@debugmcp/adapter-*packages are discoverable at runtime. A language may be usable in one mode only — e.g. in the Docker container Ruby is attach-only (the adapter ships without a Ruby runtime; attach connects directly to a remote rdbg socket). Checklist_supported_languagesmodesfor per-mode availability; creating a session for an attach-only language is allowed, and onlystart_debuggingwill fail.name(string, optional): A descriptive name for the debug session. Defaults to"<language>-debug-<timestamp>"(e.g.,"python-debug-1711500000000"), built from the session language andDate.now().executablePath(string, optional): Path to the language interpreter/executable (e.g., Python interpreter path).
Response:
{
"success": true,
"sessionId": "a4d1acc8-84a8-44fe-a13e-28628c5b33c7",
"message": "Created python debug session: Test Debug Session"
}Example:
{
"language": "python",
"name": "My Debug Session"
}Notes:
- Session IDs are UUIDs in the format
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - Sessions start in
"created"state - When a
portparameter is provided increate_debug_session, the server performs an inline attach (creating the session and immediately attaching to a running process on that port)
Lists all active debugging sessions.
Parameters: None (empty object {})
Response:
{
"success": true,
"sessions": [
{
"id": "a4d1acc8-84a8-44fe-a13e-28628c5b33c7",
"name": "Test Debug Session",
"language": "python",
"state": "created",
"createdAt": "2025-06-11T04:53:14.762Z",
"updatedAt": "2025-06-11T04:53:14.762Z"
}
],
"count": 1
}Session States (from SessionState enum):
"created": Session created but not started"initializing": Debug session starting up"ready": Session initialized and ready to start debugging"running": Actively debugging (program executing)"paused": Paused at breakpoint or step"stopped": Session stopped (program terminated)"error": Session encountered an error
Closes an active debugging session.
Parameters:
sessionId(string, required): The ID of the debug session to close.
Response:
{
"success": true,
"message": "Closed debug session: a4d1acc8-84a8-44fe-a13e-28628c5b33c7"
}Notes:
- Sessions may close automatically on errors
- Closing a non-existent session returns
success: false
Sets a breakpoint in a source file.
Parameters:
sessionId(string, required): The ID of the debug session.file(string, required): Path to the source file (absolute or relative to project root).line(number, required): Line number where to set breakpoint (1-indexed).statement(string, optional): Content addressing — instead ofline, pass the text of the target line, like an Edit-tool match — a distinctive substring is enough (leading/trailing whitespace and trailing///#comments are ignored; an exact whole-line match always wins over substring matches). Can only land on a line containing your stated text — an inexact or multi-candidate match still sets the breakpoint but adds awarningto the response; if the text appears on multiple lines the error lists every match; anchors re-resolve acrossrestart_debuggingafter file edits. ProvidestatementORline, not both. See Statement anchors.function(string, optional): Symbol addressing — break on entry to a function/method by name (DAP function breakpoint). Session-global: nofileorlineat all, and names survive edits better than both. Composes withconditiononly. Supported by Python, Go, Rust, C/C++, .NET, Java, and JavaScript (JavaScript names are dotted runtime paths delivered over the CDP bridge — see Function breakpoints); Ruby is accepted with a warning and validated at launch.nearLine(number, optional): Withstatementonly — when the statement text appears on multiple lines, bind to the match closest to this line (ties go to the lower line).expectedContent(string, optional): Withlineonly — assert the text of the target line before setting; a distinctive substring is enough (leading/trailing whitespace and trailing///#comments are ignored). On a mismatch the breakpoint is not set and the error shows the actual content of that line and its neighbors — a fast, self-explanatory failure instead of a breakpoint that silently lands on the wrong line. A relaxed match (substring, or one that only holds after ignoring text past a///#marker) still sets the breakpoint but adds awarningquoting the actual line. See Content assertions and loud snapping.condition(string, optional): Conditional expression — only break (or log) when it evaluates truthy.logMessage(string, optional): Create a logpoint instead of a pausing breakpoint — see Logpoints below.suspendPolicy(string, optional): Suspend policy when the breakpoint is hit —"all"suspends all threads (default),"thread"suspends only the event thread. Only supported by the Java/JDI adapter.
Response:
{
"success": true,
"breakpointId": "28e06119-619e-43c0-b029-339cec2615df",
"file": "C:\\path\\to\\debug-mcp-server\\examples\\python_simple_swap\\swap_vars.py",
"line": 10,
"verified": false,
"message": "Breakpoint set at C:\\path\\to\\debug-mcp-server\\examples\\python_simple_swap\\swap_vars.py:10",
"context": {
"lineContent": " a = b # Bug: 'a' loses its original value here",
"surrounding": [
{ "line": 8, "content": " # Or Python's tuple assignment: a, b = b, a" },
{ "line": 9, "content": " " },
{ "line": 10, "content": " a = b # Bug: 'a' loses its original value here" },
{ "line": 11, "content": " b = a # Bug: 'b' gets the new value of 'a' (which is original 'b')" },
{ "line": 12, "content": " " }
]
}
}Important Notes:
- Breakpoints show
"verified": falseuntil debugging starts - The response includes the absolute path even if you provide a relative path
- Setting breakpoints on non-executable lines (comments, blank lines, declarations) may cause unexpected behavior
- Executable lines that work well: assignments, function calls, conditionals, returns
- The top-level
contentfield echoes the bound line's text (same ascontext.lineContent)
expectedContent is a checksum on intent: agents that compute line numbers from a code listing routinely land one line off, and a breakpoint on a blank line or brace produces confusing session behavior much later. With expectedContent, the mismatch fails at set time:
Breakpoint not set: line 12 of /abs/app.py does not match expectedContent.
Expected: "total = sum(prices)"
Actual: "return total"
Context:
10 | prices = load()
11 | total = sum(prices)
> 12 | return total
13 |
14 | def main():
The file may have changed since you last read it. Pick the correct line from the context above.
Relatedly, when a debug adapter accepts a breakpoint but binds it to a different line (adapters snap requests on non-executable lines to the nearest valid one), the response reports it prominently instead of silently mutating the line: message and warning carry "requested line 12, bound to line 13: \...`", and the response includes requestedLinealongside the boundline. Adapters that relocate breakpoints asynchronously (after the response) surface the move in list_breakpoints, where line≠requestedLine` marks a snapped breakpoint.
expectedContent requires a source file the server can read: it is rejected for Java FQCN breakpoints and attach-mode sessions (remote filesystems). Both addressing aids can be restricted with the DEBUG_MCP_BP_ADDRESSING environment variable (line = pre-existing behavior, assert = + expectedContent/loud snapping, content = all features; default content) — useful for controlled comparisons of agent behavior.
statement addresses a breakpoint by content instead of line number — the single most practiced agent skill (Edit-tool old_string matching) instead of line arithmetic:
{ "sessionId": "...", "file": "/abs/app.py", "statement": "total = sum(prices)" }- Matching: whole-line equality after trimming leading/trailing whitespace; when no exact match exists anywhere, a substring match against comment-stripped lines is accepted (exact matches always win — the two populations never mix). Multi-line input is rejected — anchor on the first line of a multi-line construct.
- Ambiguity is an error, and the error is the disambiguation UI: every matching
line: contentpair is listed (capped at 20); addnearLineto bind to the closest match. AnearLinepick among multiple matches adds awarningnaming every candidate line — proximity is a heuristic, not a guarantee. - Blank/comment anchors are rejected (
#,//,/*prefixes) — debuggers cannot break there reliably. - The anchor is stored on the breakpoint record (visible in
list_breakpoints) and re-resolves onrestart_debugging: after you edit the file — the whole point of a debug session — the relaunch re-finds each anchored statement in the current file (the breakpoint's previous line breaks ties between duplicates). Moves are reported in the restart response'sdata.anchorResolution.moved— a move picked among multiple matching lines carries acandidateslist and a restartwarning; anchors that no longer match keep their previous line and warn (data.anchorResolution.stale) rather than failing the restart or dropping state. - Same readable-file requirement as
expectedContent(no Java FQCNs, no attach sessions); composes withcondition,logMessage, andsuspendPolicyunchanged. - A matching
expectedContentalongsidestatementis accepted as redundant (matching under the same relaxed rules: trailing comments ignored, either value may be a substring of the other); a genuinely different one is an error (contradictory intent).
set_breakpoint {sessionId, function: "process_order", condition?} breaks on entry to a symbol, with no file or line:
- Session-global, name-addressed — the adapter resolves the symbol across the whole program, and the name survives any file edit.
restart_debuggingre-applies them natively. - Composes with
conditiononly (logMessageandsuspendPolicyhave no DAP function-breakpoint form; file/line/statement/expectedContent are contradictory and rejected). - The response and
list_breakpointsreport the adapter's bound location asboundFile/boundLineonce verified.list_breakpointsreturns function breakpoints in a separatefunctionBreakpointsarray (excluded when filtering by file);remove_breakpointacceptsfunction: "name"or the breakpoint id; an unscopedclear_breakpointsremoves them, a file-scoped clear does not. - Support is adapter-gated: Python, Go, Rust, C/C++, .NET, Java, and JavaScript work; Ruby is accepted with a warning and validated against the adapter's live capabilities at launch.
- A name that never binds is reported, not silent: known-hazard names warn at set time (Go's bare identifiers need package qualification —
main.main; a baremainon Rust resolves to the C runtime's entry point, usemy_crate::main); function breakpoints still unbound after launch produce awarningin thestart_debuggingresponse (suppressed for JavaScript/Java, which bind late by design); and breakpoints that never bound by program exit get an explanatorymessageinlist_breakpointsplus a[mcp-debugger] Warning:entry inget_output. - Java names may be bare (
helper), class-qualified (Foo.helper,com.example.Foo.helper,Outer.Inner.helper), or constructors (Foo.<init>). Every concrete overload binds (the reportedboundLineis the first); classes not yet loaded bind on load and report through breakpoint events. Bare names skip JDK-internal classes (java.*,javax.*,sun.*,jdk.*,com.sun.*) — qualify the class to target those. - JavaScript semantics differ by design (js-debug implements no DAP function breakpoints upstream — vscode-js-debug#952 — so ours are delivered over js-debug's CDP proxy via V8's
Debugger.setBreakpointOnFunctionCall, the same primitive behind Chrome DevTools'debug(fn)). The name is a dotted runtime path (handler,obj.method,globalThis.tick), resolved side-effect-free against the top paused frame's scope (or global scope while running) and bound to the function value it resolves to at that moment — it is not a source-symbol search ("all functions named X" is not the contract), and reassigning the property later does not move the breakpoint. Top-levelfunctiondeclarations of the main module bind at launch;const fn = ...and functions in lazily-loaded modules stayverified: falsewith an explanatory message and bind automatically at the next pause. Names resolve against runtime names, not TypeScript/minified source names. Launch and attach modes both work (attach has no entry pause, so module-scoped names bind at the first pause after attach).
Passing logMessage turns the breakpoint into a DAP logpoint: when the line is hit the program does not pause — the message is logged and execution continues at full speed. Expressions in {curly braces} are interpolated with live values (e.g. "order={orderId} total={total}"), and the messages arrive in the session output, readable via get_output and the debug://sessions/{id}/output resource. condition may be combined with logMessage — the message is only logged when the condition holds.
This is the prod-safe just-in-time diagnostics primitive: attach to a live process, plant logpoints at suspect lines, read interpolated values from get_output — no pauses, no pre-instrumented logging.
Support is adapter-dependent:
| Adapters | Behavior |
|---|---|
| Python, JavaScript/TypeScript, Go, Rust, mock | Supported — logs without pausing |
| Java, .NET | Not supported — set_breakpoint with logMessage fails fast with a clear error |
| Ruby | Unknown — accepted with a warning; validated against the adapter's capabilities at launch |
Lists all breakpoints in a session with their current verified state and adapter-assigned ids. Works before launch (queued breakpoints, verified: false), while running or paused, and after the program exits.
Parameters:
sessionId(string, required): The ID of the debug session.file(string, optional): Only list breakpoints in this file.
Response:
{
"success": true,
"breakpoints": [
{
"id": "28e06119-619e-43c0-b029-339cec2615df",
"file": "C:\\path\\to\\project\\app.py",
"line": 10,
"verified": true,
"adapterId": 3
}
],
"count": 1,
"functionBreakpoints": [],
"functionCount": 0
}Notes:
- The array is sorted by file, then line. Conditional breakpoints include their
condition; Java suspend policies appear assuspendPolicy. functionBreakpoints/functionCountare always present in the unfiltered response (empty arrays when none exist). When filtering byfilethey are omitted — function breakpoints are session-global, not file-scoped.adapterIdis the debug adapter's own numeric id for the breakpoint, captured from setBreakpoints responses and breakpoint events. It is absent until the adapter has seen the breakpoint.- Verification is eventually consistent: some adapters (js-debug, JDI, netcoredbg) bind breakpoints asynchronously and confirm via DAP breakpoint events shortly after launch or class load.
Removes one breakpoint by id, or every breakpoint at a file + line location. Takes effect immediately while the program is running or paused (the file's remaining breakpoint set is re-sent to the adapter); also works after the program exits, so breakpoints can be adjusted before a relaunch.
Parameters:
sessionId(string, required): The ID of the debug session.breakpointId(string, optional): Breakpoint id fromset_breakpointorlist_breakpoints. Takes precedence overfile+line.file(string, optional): Alternative addressing — source file path (use together withline). Removes all breakpoints at that location.line(number, optional): Alternative addressing — line number (use together withfile).
Response:
{
"success": true,
"removed": [
{ "id": "28e06119-619e-43c0-b029-339cec2615df", "file": "C:\\path\\to\\project\\app.py", "line": 10, "verified": true }
],
"message": "Removed 1 breakpoint(s)"
}Notes:
- An unknown
breakpointId(or an empty location) returnssuccess: falsewith an explanatory error. - If the live re-send to the adapter fails, the breakpoint is still removed from the session (it will not be re-applied on the next launch) and the response carries a
warning.
Removes all breakpoints in a session, or all breakpoints in one file. Clearing zero breakpoints is success, not an error.
Parameters:
sessionId(string, required): The ID of the debug session.file(string, optional): Only clear breakpoints in this file.
Response:
{
"success": true,
"cleared": 2,
"files": ["C:\\path\\to\\project\\app.py"],
"message": "Cleared 2 breakpoint(s)"
}Starts debugging a script.
Parameters:
sessionId(string, required): The ID of the debug session.scriptPath(string, required): Path to the script to debug.args(array of strings, optional): Command line arguments for the script.dapLaunchArgs(object, optional): Standard DAP launch arguments:stopOnEntry(boolean): Stop at first linejustMyCode(boolean): Debug only user code- Additional DAP launch keys (
program,cwd,env, language-specific options) pass through to the adapter. Top-level parameters do not belong here: a nestedbreakOnExceptionsis honored as an alias (the top-level value wins if both are given) and reported via awarningin the response; other misplaced top-level keys (dryRunSpawn,sessionId,scriptPath,adapterLaunchConfig) are stripped with a warning instead of silently riding into the launch config.
adapterLaunchConfig(object, optional): Adapter-specific launch configuration overrides. Use this for language-specific settings that go beyond standard DAP arguments (e.g.,mainClassandclasspathfor Java,buildCommandfor Rust).dryRunSpawn(boolean, optional): Test spawn without actually startingbreakOnExceptions(string, optional):"uncaught"pauses at uncaught exceptions at the crash site (stack and locals inspectable) instead of terminating the session;"all"also pauses on caught/raised exceptions (language-dependent). Launch sessions default to"uncaught"(issue #244) — a crashing script pauses withlastStop.reason: "exception"instead of terminating; pass"none"to opt out and let it run to termination. Ruby is the exception: rdbg has no uncaught-only filter, so Ruby launches stay"none"by default (only explicit"all"is available). Attach sessions never apply a language default. The abstract mode maps to per-language debugger filters (e.g. Pythonuncaught/raised, JavaScriptuncaught/all, Javauncaught/caught, .NETuser-unhandled/all, Gounrecovered-panic+runtime-fatal-throw, Rustrust_panic, C/C++cpp_throwfor"all"— its"uncaught"default sets no filter since uncaught throws crash via SIGABRT, which pauses natively); an explicitly requested unsupported mode is skipped with a warning. Python edge: debugpy treatssys.exit(n)with a non-zero code as an unhandledSystemExitand pauses there (sys.exit(0)runs to completion normally) — pass"none"if a script legitimately exits non-zero viasys.exit.
Response:
{
"success": true,
"state": "paused",
"message": "Debugging started for examples/python_simple_swap/swap_vars.py. Current state: paused",
"data": {
"message": "Debugging started for examples/python_simple_swap/swap_vars.py. Current state: paused",
"reason": "breakpoint"
}
}Pause Reasons:
"breakpoint": Stopped at a breakpoint"step": Stopped after a step operation"entry": Stopped on entry (if configured)"exception": Stopped at an exception (the launch default for most languages; seebreakOnExceptions).lastStop.description/lastStop.textcarry the exception class and message where the adapter reports them. Where the adapter supports the DAPexceptionInforequest (Python, JavaScript, Java, .NET, mock),lastStop.exceptionInfois additionally populated best-effort withexceptionId,breakMode, and optionaldetails(message, type names, adapter-side stack trace). The enrichment is requested asynchronously right after the pause, so it may appear inlist_debug_sessions/get_stack_tracea moment after the stop itself — re-query if it is absent immediately after pausing.
Exit code: when the debuggee terminates, the exit code reported by the adapter is surfaced as exitCode in list_debug_sessions, so a crash (non-zero) is distinguishable from a clean exit.
Restarts the debuggee in one call: terminates the current program (if still running) and relaunches it with the same configuration as the last start_debugging. All current breakpoints are re-applied automatically — the core edit-rerun loop (fix a line → restart → confirm at the same breakpoints) becomes a single tool call instead of close/create/re-set/start.
Parameters:
sessionId(string, required): The ID of the debug session.
Response: mirrors start_debugging, plus:
{
"success": true,
"state": "paused",
"message": "Debugging started for /path/app.py. Current state: paused",
"data": {
"reason": "breakpoint",
"breakpointsReapplied": 2,
"outputReset": true
}
}Notes:
- Works while the program is running, paused, or after it has exited (the primary use case — a finished session can be restarted without recreating it).
- Restart is implemented uniformly as terminate + relaunch (the DAP-spec-blessed emulation; no adapter advertises native restart), so every launch-mode language works identically. Native DAP
restartis a possible future optimization. - The launch configuration is replayed verbatim (script, args,
dapLaunchArgs,adapterLaunchConfig,breakOnExceptions); there are no per-restart overrides — callstart_debuggingfor a different configuration. - The output buffer starts fresh:
outputReset: truesignals thatget_outputcursors from the previous launch are stale — read fromsince: 0. - Not available for attach sessions (no launch configuration to replay — detach and re-attach instead) or for sessions that were never launched (including dry-run-only sessions).
Steps over the current line, executing it without entering function calls.
Parameters:
sessionId(string, required): The ID of the debug session.
Response:
{
"success": true,
"state": "paused",
"message": "Stepped over"
}Steps into function calls on the current line.
Parameters:
sessionId(string, required): The ID of the debug session.
Response:
{
"success": true,
"state": "paused",
"message": "Stepped into"
}Steps out of the current function.
Parameters:
sessionId(string, required): The ID of the debug session.
Response:
{
"success": true,
"state": "paused",
"message": "Stepped out"
}Continues execution until the next breakpoint or program end.
Parameters:
sessionId(string, required): The ID of the debug session.
Response:
{
"success": true,
"state": "running",
"message": "Continued execution"
}Error Response:
{
"code": -32603,
"message": "MCP error -32603: Failed to continue execution: Managed session not found: {sessionId}"
}Pauses a running program. The debugger sends a DAP pause request and returns immediately; the paused state is updated asynchronously when the stopped event arrives.
Parameters:
sessionId(string, required): The ID of the debug session.
Response:
{
"success": true,
"state": "running",
"data": {
"message": "Execution paused"
}
}Notes:
- The
"state"field in the response reflects the session state at the moment the pause request is acknowledged, which is still"running". The state transitions to"paused"asynchronously when the stopped event arrives from the debug adapter; polllist_debug_sessionsor wait for subsequent tool calls to observe the paused state. - When the stop is observed before the tool returns,
data.stopReasoncarries the (normalized) stop reason and — if the adapter reported a misleading raw reason that was normalized —data.rawStopReasoncarries the original. Example: CodeLLDB delivers an explicit pause via SIGSTOP and reports"exception"; the result isstopReason: "pause", rawStopReason: "exception". js-debug similarly reports pauses as"step". The same raw reason appears aslastStop.rawReasoninlist_debug_sessions. Stale stops from before the pause request are never echoed. - The session must be in a
"running"state; pausing an already-paused session returns success immediately with"Already paused"(plus the currentstopReason) - After pausing, you can inspect variables, evaluate expressions, and step through code
Debuggers see everything in scope — including credentials — and when the debugging driver is an AI agent, variable values flow into model context and transcripts. By default, mcp-debugger masks credential-shaped values in every value-bearing surface: get_variables, get_local_variables, evaluate_expression results, and captured output (get_output and the debug://sessions/{id}/output resource).
Masking is per-token and labeled, so the rest of the value stays legible:
{ "name": "gh_token", "value": "<redacted:github-pat>", "type": "str", "redacted": true }Two detection layers apply:
- Value shapes — well-known token formats (GitHub/GitLab PATs, OpenAI/Anthropic-style
sk-keys, Slack, Stripe, AWS access key IDs, Google API keys, npm/PyPI/Hugging Face tokens, SendGrid, JWTs, PEM private-key blocks,Bearercredentials, connection-string passwords, URL userinfo passwords). Patterns are adapted from the MIT-licensed gitleaks corpus. - Sensitive names — a variable whose name exactly matches a known sensitive name (
password,api_key,client_secret, ...) has its whole value masked as<redacted:sensitive-name>, unless the value is trivial (None,'',0, ...) so "why is my token empty?" stays debuggable. Matching is exact after normalization, never substring —tokenCount,PATH, andpatienceare untouched.evaluate_expressiontreats the expression's final dot-segment as the name, soconfig.passwordis masked like the variablepassword.
Results that had values masked carry a redaction field ({ masked, notice } on variable/output tools; { rules, notice } on evaluate results) explaining that only the display is masked, not program state. Redacted variables and output entries are flagged redacted: true.
Opting out: start the server with DEBUG_MCP_NO_REDACT=1 to disable redaction entirely (e.g. when debugging credential-handling code itself). Adapter stderr sanitization (unconditional, whole-line) is unaffected by this flag.
Limitations: redaction is display-level protection against credentials leaking into transcripts, not a security boundary against a hostile agent — an agent can still compute over secrets via evaluate_expression side effects. Secrets split across separate output chunks, and generic high-entropy strings with no recognizable shape or name, are not detected. The expose_session IDE mirror shows raw, unredacted values — it serves a human's IDE, not the agent.
For security-sensitive deployments, DEBUG_MCP_VARIABLE_ACCESS=explicit disables bulk scope dumps: get_variables and get_local_variables require a names filter, so the agent must ask for specific variables instead of sweeping every value in scope into its context. An unfiltered call is rejected with a clear InvalidParams error that teaches the correct call shape; the tool schemas and the initialize instructions advertise the requirement.
The names parameter works in the default (open) mode too, as an ordinary filter:
- Exact-match and case-sensitive against variable names (DAP names are language identifiers).
- The response's
notFoundarray lists requested names absent from the scope, so "filtered out" is distinguishable from "doesn't exist". - Unrequested values are dropped in the session layer, before redaction and logging.
evaluate_expression is deliberately not restricted in explicit mode: least-privilege guards against indiscriminate bulk exposure, not against a determined agent — evaluate is already explicit-by-name, per-request, and audit-logged, which is exactly the access discipline the mode enforces, and removing the core debugging primitive would make the mode unusable. Secret redaction still applies to evaluate results.
Gets the current call stack.
Parameters:
sessionId(string, required): The ID of the debug session.
Response:
{
"success": true,
"stackFrames": [
{
"id": 3,
"name": "swap_variables",
"file": "C:\\path\\to\\debug-mcp-server\\examples\\python_simple_swap\\swap_vars.py",
"line": 5,
"column": 1
},
{
"id": 4,
"name": "main",
"file": "C:\\path\\to\\debug-mcp-server\\examples\\python_simple_swap\\swap_vars.py",
"line": 21,
"column": 1
},
{
"id": 2,
"name": "<module>",
"file": "C:\\path\\to\\debug-mcp-server\\examples\\python_simple_swap\\swap_vars.py",
"line": 30,
"column": 1
}
],
"count": 3
}Notes:
- Stack frames are ordered from innermost (current) to outermost
- Frame IDs are used with
get_scopes - Internal/runtime frames (e.g. Node.js internals, Go
/runtime/,System.*) are filtered out by default; passincludeInternals: trueto see them. When any frames were hidden, the response additionally carrieshiddenFrames(count) and anoteexplaining how to reveal them. - The filtered stack is never empty when the adapter reported frames: if every frame is internal (e.g. a goroutine paused inside the Go runtime), the top internal frame is kept so
get_scopes/evaluate_expressionstill have a validframeId, and thenotesays so.
Gets variable scopes for a specific stack frame.
Parameters:
sessionId(string, required): The ID of the debug session.frameId(number, required): The ID of the stack frame fromget_stack_trace.
Response:
{
"success": true,
"scopes": [
{
"name": "Locals",
"variablesReference": 5,
"expensive": false,
"presentationHint": "locals",
"source": {}
},
{
"name": "Globals",
"variablesReference": 6,
"expensive": false,
"source": {}
}
]
}Important:
- The
variablesReferenceis what you pass toget_variablesas thescopeparameter - This is NOT the same as the frame ID!
Gets variables within a scope.
Parameters:
sessionId(string, required): The ID of the debug session.scope(number, required): ThevariablesReferencenumber from a scope or variable.names(string[], optional): Only return variables with these exact names (case-sensitive). Requested names missing from the scope are listed in the response'snotFound. Required in least-privilege mode.
Response:
{
"success": true,
"variables": [
{
"name": "a",
"value": "10",
"type": "int",
"variablesReference": 0,
"expandable": false
},
{
"name": "b",
"value": "20",
"type": "int",
"variablesReference": 0,
"expandable": false
}
],
"count": 2,
"variablesReference": 5
}Variable Properties:
variablesReference: 0 for primitive types, >0 for complex objects that can be expandedexpandable: Whether the variable has child properties- Values are always returned as strings
Size guards (issues #356/#359): responses are capped so an enormous scope (e.g. a JS internal frame reaching process/global) can't exceed an MCP client's per-result size limit. Per variable, values longer than 1024 chars are cut and flagged truncated: true; per call, at most 300 variables (256KB total) are returned. When anything was cut, the response carries a top-level truncation object — { omittedCount, valueTruncatedCount, notice } — and the names filter is the escape hatch to fetch specific variables in full. Limits are env-overridable: DEBUG_MCP_MAX_VARIABLE_VALUE_CHARS, DEBUG_MCP_MAX_VARIABLES, DEBUG_MCP_MAX_VARIABLES_TOTAL_CHARS.
Gets local variables by traversing all stack frames and their scopes, then using the language adapter's policy to extract the relevant local variables. This is a convenience tool that collects scopes and variables across all frames (not just the top frame) so that closures and outer-scope locals are included, then returns the filtered result without needing to manually call stack→scopes→variables.
Parameters:
sessionId(string, required): The ID of the debug session.includeSpecial(boolean, optional): Include special/internal variables likethis,__proto__,__builtins__, etc. Default: false.names(string[], optional): Only return variables with these exact names (case-sensitive). Requested names missing from the extracted locals are listed in the response'snotFound. Required in least-privilege mode.
Response:
{
"success": true,
"variables": [
{
"name": "x",
"value": "10",
"type": "int",
"variablesReference": 0,
"expandable": false
},
{
"name": "y",
"value": "20",
"type": "int",
"variablesReference": 0,
"expandable": false
}
],
"count": 2,
"frame": {
"name": "main",
"file": "C:\\path\\to\\script.py",
"line": 31
},
"scopeName": "Locals"
}Size guards: same caps and truncation advisory as get_variables; additionally, the multi-frame scope fan-out stops issuing DAP requests once the per-call variable budget is spent (truncation.scopesSkipped reports scopes never fetched). Top-frame scopes are fetched first, so the locals that matter are unaffected.
Example - Python:
// Request
{
"sessionId": "842ef9bb-037a-4d3c-960c-ad79a63ccfab",
"includeSpecial": false
}
// Response
{
"success": true,
"variables": [
{"name": "x", "value": "10", "type": "int", "variablesReference": 0, "expandable": false},
{"name": "y", "value": "20", "type": "int", "variablesReference": 0, "expandable": false}
],
"count": 2,
"frame": {
"name": "main",
"file": "C:\\path\\to\\test-scripts\\python_test_comprehensive.py",
"line": 31
},
"scopeName": "Locals"
}Example - JavaScript:
// Request
{
"sessionId": "ec46719a-68d9-4755-9c28-70478e0cde7d",
"includeSpecial": false
}
// Response
{
"success": true,
"variables": [
{"name": "x", "value": "10", "type": "number", "variablesReference": 0, "expandable": false}
],
"count": 1,
"frame": {
"name": "main",
"file": "c:\\path\\to\\test-scripts\\javascript_test_comprehensive.js",
"line": 40
},
"scopeName": "Local"
}Edge Cases:
// Empty locals
{
"success": true,
"variables": [],
"count": 0,
"frame": {"name": "<module>", "file": "script.py", "line": 2},
"scopeName": "Locals",
"message": "The Locals scope is empty."
}
// Session not paused
{
"success": false,
"error": "Session is not paused",
"message": "Cannot get local variables. The session must be paused at a breakpoint."
}Key Advantages:
- Single Call: Get local variables with one tool call instead of three (stack_trace → scopes → variables)
- Language-Aware Filtering: Automatically filters out internal/special variables based on language
- Consistent Format: Returns a consistent structure across Python and JavaScript
- Smart Defaults: By default, excludes noise like
__proto__,this,__builtins__unless explicitly requested
Language-Specific Behavior:
- Python: Looks for "Locals" scope, filters out
__builtins__, special variables, and internal debugger variables - JavaScript: Looks for "Local", "Local:", or "Block:" scopes, filters out
this,__proto__, and V8 internals - Other Languages: Falls back to generic behavior (first non-global scope)
Notes:
- Session must be paused at a breakpoint for this tool to work
- The tool traverses all frames in the call stack and collects scopes/variables from each, then uses the adapter policy to extract relevant locals (the reported frame is still the top frame)
- When
includeSpecialis true, all variables including internals are returned - This is especially useful for AI agents that need quick access to current local state
Evaluates an expression in the context of the current debug session.
Parameters:
sessionId(string, required): The ID of the debug session.expression(string, required): The expression to evaluate.frameId(number, optional): Stack frame ID for context. If not provided, automatically uses the current (top) frame.timeout(number, optional): Maximum time in milliseconds to wait for the evaluation to complete (default: 30000, max: 600000). On expiry the request fails but the expression may keep executing in the debuggee.
Response:
{
"success": true,
"result": "10",
"type": "int",
"variablesReference": 0,
"presentationHint": {}
}Example - Simple Variable:
// Request (no frameId needed!)
{
"sessionId": "d507d6fb-45fc-4295-9dc0-4f44b423c103",
"expression": "x"
}
// Response
{
"success": true,
"result": "10",
"type": "int",
"variablesReference": 0
}Example - Arithmetic Expression:
// Request
{
"sessionId": "d507d6fb-45fc-4295-9dc0-4f44b423c103",
"expression": "x + y"
}
// Response
{
"success": true,
"result": "30",
"type": "int",
"variablesReference": 0
}Example - Complex Expression:
// Request
{
"sessionId": "d507d6fb-45fc-4295-9dc0-4f44b423c103",
"expression": "[i*2 for i in range(5)]"
}
// Response
{
"success": true,
"result": "[0, 2, 4, 6, 8]",
"type": "list",
"variablesReference": 4 // Can be expanded to see elements
}Error Handling:
// Request - undefined variable
{
"sessionId": "d507d6fb-45fc-4295-9dc0-4f44b423c103",
"expression": "undefined_variable"
}
// Response
{
"success": false,
"error": "Name not found: Traceback (most recent call last):\n File \"<string>\", line 1, in <module>\nNameError: name 'undefined_variable' is not defined\n"
}Important Notes:
- Automatic Frame Detection: When
frameIdis not provided, the tool automatically gets the current frame from the stack trace - Side Effects Are Allowed: Expressions CAN modify program state (e.g.,
x = 100). This is intentional and useful for debugging - Session Must Be Paused: The debugger must be stopped at a breakpoint for evaluation to work
- Results Are Strings: All results are returned as strings, even for numeric types
- Python Truncation: Python/debugpy automatically truncates collections at 300 items for performance
Gets source code context around a specific line in a file.
Parameters:
sessionId(string, required): The ID of the debug session.file(string, required): Path to the source file (absolute or relative to project root).line(number, required): Line number to get context for (1-indexed).linesContext(number, optional): Number of lines before and after to include (default: 5).
Response:
{
"success": true,
"file": "C:\\path\\to\\script.py",
"line": 15,
"lineContent": " result = calculate_sum(x, y)",
"surrounding": [
{ "line": 12, "content": "def main():" },
{ "line": 13, "content": " x = 10" },
{ "line": 14, "content": " y = 20" },
{ "line": 15, "content": " result = calculate_sum(x, y)" },
{ "line": 16, "content": " print(f\"Result: {result}\")" },
{ "line": 17, "content": " return result" },
{ "line": 18, "content": "" }
],
"contextLines": 3
}Example:
{
"sessionId": "a4d1acc8-84a8-44fe-a13e-28628c5b33c7",
"file": "test_script.py",
"line": 25,
"linesContext": 3
}Notes:
- Useful for AI agents to understand code structure without reading entire files
- Returns the requested line content and surrounding context
- Handles file boundaries gracefully (won't return lines before 1 or after EOF)
- Uses efficient line reading with LRU caching for performance
Gets the debuggee's output (stdout/stderr/console) captured for a session. Output is delivered by the debug adapter as DAP output events and buffered per launch (issue #218).
Parameters:
sessionId(string, required): The ID of the debug session.since(number, optional): Sequence cursor — only entries withseqgreater than this are returned. PassnextSincefrom the previous response to fetch only new output. Default:0(start of the buffer).limit(number, optional): Maximum entries to return (default: 100, max: 1000).
Response:
{
"success": true,
"sessionId": "a4d1acc8-84a8-44fe-a13e-28628c5b33c7",
"entries": [
{ "seq": 1, "category": "stdout", "output": "Factorial of 5: 120\n", "timestamp": 1754140800123 },
{ "seq": 2, "category": "stderr", "output": "warning: deprecated\n", "timestamp": 1754140800345 }
],
"nextSince": 2,
"hasMore": false,
"dropped": 0
}Notes:
- The buffer holds the last 1000 entries per launch; older entries are evicted and counted in
dropped. Individual entries longer than 8192 characters are cut and flagged"truncated": true. - Adapter-internal
telemetryevents are filtered out at capture time, as are output events an adapter policy declares to be pure adapter noise — e.g. LLDB's harmless DWARF-parser error spew on MinGW-built rust/cpp binaries (issue #361); suppressed lines remain visible in debug logs. All other categories (stdout,stderr,console,important, ...) are kept. Adapters that omit a category default toconsole. - Works while the program is running and after it finishes — output stays readable until
close_debug_session. Re-launching a session starts a fresh buffer (seq restarts at 1). hasMore: truemeans more entries matched thanlimitallowed; call again withsince: nextSince.- Incremental polling recipe: call once, remember
nextSince, and pass it assinceon the next call — you'll only ever see new output. - Adapter support: Python (
redirectOutput), JavaScript (outputCapture: 'std'), Go (outputMode: 'remote'), and Java forward debuggee stdio as output events; .NET typically does as well. Ruby launch mode and Rust on Windows route debuggee stdio to the adapter process; the proxy forwards those lines as synthesizedstdout/stderrevents (#222/#223), excluding rdbg'sDEBUGGER:banners. Ruby attach captures nothing — the target's stdio stays wherever the process was started.
Each session also exposes its captured output as an MCP resource:
- URI:
debug://sessions/{sessionId}/output(text/plain) — the verbatim console transcript (all categories interleaved in arrival order). resources/listenumerates one output resource per session; the list changes on session create/close (notifications/resources/list_changed).resources/subscribeto a session's URI to receivenotifications/resources/updatedpings as output arrives. Pings are coalesced (~150 ms), so notification volume is independent of how fast the debuggee prints — on a ping, re-read the resource or callget_outputwith your cursor.- Subscriptions are tracked per server instance and cleaned up when the session closes.
The following tools are also available but are not fully documented with examples here:
-
list_supported_languages: Lists all supported debugging languages with metadata (installed status, display name, default executable). Takes no parameters. Each entry in
available[]carries per-mode availability (issue #331):{ "language": "ruby", "package": "@debugmcp/adapter-ruby", "installed": true, "modes": { "launch": { "supported": true, "available": false, "reason": "Ruby executable not found..." }, "attach": { "supported": true, "available": true } } }supportedsays whether the adapter implements the mode at all;availablesays whether it is usable in this runtime right now (with areasonwhen it isn't). Attach for Python and Ruby is a direct connection to a debugpy/rdbg DAP socket, so it stays available even when the local toolchain is missing — the container image uses exactly this to offer Ruby attach without a Ruby runtime. Disabled languages (DEBUG_MCP_DISABLE_LANGUAGES) stay listed with a disabled reason on both modes.installed[]keeps its historical meaning: adapter package loadable and not disabled. -
attach_to_process: Attaches the debugger to a running process. Parameters include
sessionId,processIdor connection details, optionallybreakOnExceptions(same mode semantics as onstart_debugging, but attach never applies a language default — it stays"none"unless requested), and optionallyadapterConfig— an object of adapter-specific attach extras merged into the attach config before the adapter transforms it, mirroringstart_debugging'sadapterLaunchConfig(C/C++/LLDB example:{"program": "/proc/1/root/pricer"}for symbol resolution from a kubectl-debug ephemeral container, orinitCommands). Reserved keysrequest/__attachModeare ignored with a warning; setstopOnEntryvia the top-level parameter.adapterConfigis not applied to js-debug attach, which builds its own attach request. Languages whose adapter has no attach implementation (rust,go,mock) fail fast with a clear error. -
detach_from_process: Detaches the debugger from an attached process. Parameters include
sessionIdand optionalterminateProcessflag. -
list_threads: Lists all threads in the debug session. Parameters include
sessionId.
The DAP mirror (issue #217) lets a human attach an IDE — VS Code, nvim-dap, any DAP client — to an agent-owned debug session as a read-only second client. The agent debugs a process no IDE launched (CI, a container, a terminal-driven run), parks it at an interesting point, and hands over host/port/token; the human lands on the live paused frame and inspects real state. Execution control stays with the MCP session.
Starts a per-session DAP server endpoint on 127.0.0.1 (ephemeral port) inside the session's debug proxy. Requires an active session (launched or attached); works while running or paused. Idempotent — calling it again returns the same endpoint and token.
Parameters:
sessionId(string, required): The debug session ID
Response:
{
"success": true,
"state": "paused",
"host": "127.0.0.1",
"port": 52341,
"token": "kx3P…32-char-random…",
"message": "Session exposed for IDE attach at 127.0.0.1:52341. VS Code: add a launch.json config … and start it. …"
}The endpoint closes on unexpose_session, close_debug_session, restart_debugging, or debuggee exit. list_debug_sessions shows exposure: {host, port} for exposed sessions (never the token).
Note: the mirror serves a human's IDE and proxies DAP responses directly, so it shows raw variable values — secret redaction does not apply to this surface.
Connecting VS Code:
debugServer points VS Code directly at a running DAP server; extra properties like mirrorToken are passed through in the attach request, where the mirror validates them.
| Session language | VS Code type |
|---|---|
| python | python |
| javascript | node |
| java | java |
| go | go |
| rust | lldb |
| dotnet | coreclr |
| ruby | rdbg |
Other DAP clients (nvim-dap, etc.): connect a TCP DAP client to the host/port and include mirrorToken in the attach request arguments.
What the mirror serves:
- Answered locally:
initialize(from the adapter's real capabilities, with control affordances masked off),attach/launch(token check),configurationDone(also the trigger for the late-join stopped replay below),disconnect(that client only),cancel. - Forwarded to the live adapter:
threads,stackTrace,scopes,variables,source,evaluate,exceptionInfo,loadedSources,modules. - Soft-succeeded so IDE attach flows survive:
setBreakpoints/setFunctionBreakpoints(reported unverified — breakpoints stay agent-owned),setExceptionBreakpoints. - Rejected with a quiet error:
continue,next,stepIn,stepOut,pause,setVariable,restart,terminate, and every other control or mutation request.
On attach while the session is paused, the mirror replays the last stop as a stopped event, so the IDE lands directly on the paused frame. The replay is delivered when the client sends configurationDone (standard DAP handshake order); clients that skip configurationDone receive it after a short (~200ms) fallback. Live events, by contrast, are broadcast to every attached client immediately.
Security: the endpoint binds loopback only and every client must present the per-expose token. Treat the token as a debuggee-execution capability, not a view-only credential — evaluate is forwarded, and DAP evaluate can run arbitrary code in the debuggee. The token appears only in the expose_session result and is redacted from logs. "Read-only" means execution control and breakpoint changes are rejected, not that the debuggee is immutable.
Container note: when the server runs inside a container, the mirror listens on the container's loopback — a host IDE cannot reach it without extra networking (docker run --network host on Linux, or a socat/ssh forward into the container). The same applies to any deployment where the MCP server host is not the IDE host.
Closes the mirror endpoint and disconnects any attached IDE clients (they receive a terminated event). A no-op success when the session is not exposed.
Parameters:
sessionId(string, required): The debug session ID
Response:
{
"success": true,
"state": "paused",
"wasExposed": true,
"message": "Mirror endpoint closed (1 client disconnected)"
}Hot-swap changed Java classes into a running JVM using JDI VirtualMachine.redefineClasses(). Java only.
Parameters:
sessionId(string, required): The debug session ID (must be an active Java session)classesDir(string, required): Absolute path to compiled classes directory (e.g.,build/classes/java/main/)sinceTimestamp(number, optional): Unix timestamp in milliseconds. Only redefine.classfiles modified after this time.0or omitted = scan all files.timeout(number, optional): Maximum time in milliseconds to wait for the redefinition to complete (default: 30000, max: 600000). Increase when hot-swapping many classes at once.
Response:
{
"success": true,
"redefined": ["com.example.Foo", "com.example.Bar"],
"redefinedCount": 2,
"skippedNotLoaded": 3,
"failedCount": 1,
"failed": [
{ "fqcn": "com.example.Baz", "error": "UnsupportedOperationException: class redefinition failed: attempted to add a method" }
],
"scannedFiles": 6,
"newestTimestamp": 1711500000000
}Example — full scan:
{
"sessionId": "abc-123",
"classesDir": "/project/build/classes/java/main"
}Example — incremental scan (pass newestTimestamp from previous call):
{
"sessionId": "abc-123",
"classesDir": "/project/build/classes/java/main",
"sinceTimestamp": 1711500000000
}Notes:
- Only works with Java debug sessions (requires JDI support)
- Classes must already be loaded in the target JVM — unloaded classes are skipped (
skippedNotLoaded) - Schema changes (adding/removing methods or fields) will fail for individual classes without blocking others
- The
newestTimestampin the response enables incremental workflows: recompile, then pass it assinceTimestampon the next call to only redefine newly modified files - The session can be paused or running when calling this tool
Tools can return errors in two formats:
- MCP transport errors: Standard JSON-RPC error responses with numeric error codes. These indicate protocol-level failures.
- Application-level failures: JSON payloads with
{ "success": false, "error": "..." }. Most tool failures use this format, where the HTTP/transport layer succeeds but the operation itself failed.
-32603: Internal error (feature not implemented, unexpected failures)-32602: Invalid parameters (e.g., missingsessionId)
Session-lifecycle failures (unknown/terminated session, proxy not running) are application-level failures: they return { "success": false, "error": "..." } rather than an MCP transport error.
{
"code": -32603,
"name": "McpError",
"message": "MCP error -32603: {specific error message}",
"stack": "{stack trace}"
}{
"success": false,
"error": "Session is not paused",
"message": "Cannot get local variables. The session must be paused at a breakpoint."
}- Session not found: Occurs when a session terminates unexpectedly
- Invalid language: Language must be one of the supported languages (discovered dynamically from installed adapters)
- File not found: When setting breakpoints in non-existent files
- Invalid scope: When passing wrong variablesReference to get_variables
- Always check session state before performing operations
- Use absolute paths for files to avoid ambiguity
- Get scopes before variables - you need the variablesReference
- Handle session termination gracefully - sessions can end unexpectedly
- Set breakpoints on executable lines - avoid comments and declarations
Last updated: 2026-08-19 based on source code review of mcp-debugger v0.24.0 (28 tools)