Skip to content

Latest commit

 

History

History
324 lines (218 loc) · 36.2 KB

README.md

File metadata and controls

324 lines (218 loc) · 36.2 KB

Python Debugging with Debug MCP Server

The Debug MCP Server provides support for Python debugging through the debugpy library. This document explains how to use the Python debugging capabilities.

Tool calls below are written the way the rest of these docs write them: the tool name followed by its JSON arguments — the shape your MCP client sends.

Prerequisites

Before using the Python debugging features, ensure you have:

  1. Python 3.7 or higher installed
  2. The debugpy package installed:
    pip install debugpy
    Verify with python -m debugpy --version.

The interpreter is auto-detected from PATH. To pin a specific one, set the PYTHON_PATH environment variable (PYTHON_EXECUTABLE is checked as a fallback), or pass executablePath in create_debug_session.

Use absolute paths. In host mode relative file/scriptPath values are rejected; in container mode paths are resolved against the /workspace/ mount.

Debugging Workflow

1. Create a Debug Session

First, create a Python debug session:

create_debug_session { "language": "python", "name": "My Python Debug Session" }

This returns a session ID that you'll use for all subsequent debugging commands.

2. Set Breakpoints

Set breakpoints in your code before starting execution:

set_breakpoint { "sessionId": "your-session-id", "file": "/abs/path/script.py", "line": 10 }

"verified": false in the response is normal for Python — debugpy verifies breakpoints asynchronously once it loads the module. Set them anyway and start; they bind and hit. Do not retry-loop on the flag.

Three sturdier ways to address a breakpoint than a bare line number:

# By content, like an Edit-tool match — survives file edits across restart_debugging
set_breakpoint { "sessionId": "...", "file": "/abs/path/script.py", "statement": "total = price * qty" }

# Line plus an assertion — if the text is not on that line the breakpoint is NOT set,
# and the error shows the line's actual content
set_breakpoint { "sessionId": "...", "file": "/abs/path/script.py", "line": 10,
                 "expectedContent": "total = price" }

# By symbol — no file and no line at all (function goes alone, optionally with condition)
set_breakpoint { "sessionId": "...", "function": "compute_total" }

Conditional breakpoints and logpoints:

set_breakpoint { "sessionId": "...", "file": "/abs/path/script.py", "line": 15, "condition": "x > 5" }
set_breakpoint { "sessionId": "...", "file": "/abs/path/script.py", "line": 15, "logMessage": "x={x} y={y}" }

A logpoint never pauses: it interpolates the {expressions} and writes the line to get_output while the program keeps running. Each hit does cost time, however — measured at 11.7 µs per hit on Python 3.13 + debugpy (sys.monitoring, 1.2% of a core at 1,000 hits/s), and placing a logpoint anywhere in a function slows that whole function by 56× — so keep logpoints off tight loops. When hits outrun debugpy's delivery rate (a few thousand lines a second), lines still queued when the program exits are lost and the session's end answer does not report the loss (issue #1265). See Logpoints for measurement conditions and what was not measured.

What a logpoint message may contain

A field is an expression in the program's language. For Python, f-string field syntax ({x!r}, {total:.2f}, {x=}) is accepted where the server checked the message on the program's own interpreter, which takes a launched session (the launches that are not checked are listed below). Elsewhere the message goes to debugpy as written, which evaluates each field as a plain expression, and the answer says it was not checked. debugpy's own reading wins wherever the check finds it can run the message: {{x}} is a set and %% is %.

debugpy turns the message into one Python expression — the text becomes a %-template and each {...} group a plain expression — and evaluates it at every hit. When the launch starts (and for a logpoint set while the program runs), the server asks the program's own interpreter, with the debugpy it runs, whether that expression can run; nothing is evaluated in that check, and nothing is refused:

  • A message that runs is sent exactly as written. If it contains an assignment expression ({step:=99}, which an f-string would read as a format spec), the answer says so, because where it runs it assigns — on Python 3.13 and later to the running function's own variable, and on 3.12 too with some debugpy versions (1.8.0 does, 1.8.20 does not) — and names the f-string reading.
  • A message the check finds cannot run for any values is repaired in the smallest way that the interpreter validates: each group that does not compile on its own becomes the same field as an f-string ({x!r} is sent as {f'{x!r}'}), and when the text cannot be formatted with % for any values (100% {x}), the text's % is doubled. Every other part is untouched. The answer shows logMessageSent, what debugpy received, and logMessageCheck, why; list_breakpoints keeps the message you wrote in logMessage. A message with a starred group ({*items}) is the exception for % (below).
  • A message that cannot run and has no such repair (a brace inside a string in a field, {d['}']}, which debugpy splits there) is sent as written, and the answer says why and what every hit logs in its place: a compile error, a % formatting error or debugpy's "Unbalanced braces" line, with CPython's words where CPython has some.
  • Not checked, and sent as written, with the reason in the answer: an attach (the program runs in a process this server did not start), a launch that names its own interpreter or interpreter flags (python, pythonPath, pythonArgs), a child process whose interpreter cannot be confirmed as the checked one, a message longer than 4,096 characters, a %-directive width or precision of more than 4 digits, or widths and precisions adding up to more than 65,536 (a message with a starred group is not held to these, since its % is not examined at all), anything the check itself could not finish (its recursion limit, its memory, the interpreter's own tokenizer raising on a field, which Python 3.12.13's does on one known shape, an audit hook added from Python in its process that raised while it compiled), and a check that ran out of time (below).

The check runs in a short-lived helper process on the program's interpreter, started for a run's first logpoint and stopped when the run ends (when the program and every child process it started have ended), on close_debug_session (which waits for it), and when the server exits; it reads its input until the server goes away. A check has 2 seconds from the moment it is asked, waiting behind other checks included, or 5 seconds when it starts the helper: a set_breakpoint is delayed by no more than that however many calls arrive at once, and past it the message is sent as written and the answer says it was not checked. A launch's checks share one such budget. When the helper cannot be started, exits before it has answered, or does not answer in its first 5 seconds, the run's later checks are answered at once as not checked, with that reason, and nothing is started again until the next run; a helper that fails after it had answered is started again once in the run.

The check is a verdict in one direction only. What it finds cannot compile is a fact about the text, meant to hold in every process: the helper is a sibling of the program on the same interpreter binary, and the settings of its own process that the compiler is known to consult are relaxed in it — the integer digit limit lifted, warnings ignored, its working directory kept off the path of the modules the compiler imports — and what it cannot relax (the recursion limit, memory, an audit hook added from Python) makes the message not checked instead of failed. One thing in its own process it does not tell from the compiler is an audit hook registered from C (below). What it finds compiles can still fail at a hit in a program that made its own compiler stricter: one that turns warnings into errors (-W error, PYTHONWARNINGS=error, warnings.simplefilter("error"): {1 is 1} then logs "is" with 'int' literal), one that lowered the integer digit limit (sys.set_int_max_str_digits(640), PYTHONINTMAXSTRDIGITS: a long literal then logs Exceeds the limit (640 digits)), one with a lower recursion limit or a deeper stack at the hit, one with an audit hook, and a child process started with interpreter flags of its own (-W error, -X int_max_str_digits=640), which a child's check, made on the same interpreter binary, does not see. That is what "this check did not execute a hit" in the answer means. A repair claims only a compile: it was not run, and real values can still raise. A message with a starred group ({*items}) is checked for what compiles only, whatever the verdict: how many values the group gives is known at the hit alone, so the text's % is not examined and never doubled. {*items} 100% is answered as running and {x!r} {*items} 100% is sent as {f'{x!r}'} {*items} 100%; every hit of either logs an error in its place. A rewritten field is different source text from the one you wrote, so a program that inspects what it compiles — an audit hook that judges compile events by their source — can tell {f'{x!r}'} from {repr(x)} and treat them differently.

Four more things a user can meet, each with what the check does there. On macOS (and other systems without /proc) a child process's executable cannot be looked up, so every logpoint of an adopted child there is not checked (the root's are). The helper runs with the debug adapter's environment and working directory, not the launch's env or envFile: what a launch sets for the program alone (PYTHONWARNINGS=error, a PYTHONPATH) is not seen by the check, which answers as if it were not set, and is one more way a program can be stricter than its check. A file on the PYTHONPATH the helper inherits that stands in for a module the compiler uses (unicodedata) and leaves it without its table of character names makes every check of that run not checked; that takes an interpreter that loads the module from a file, and one that has it built in (Ubuntu 24.04's own Python 3.12 is one) never loads the file and answers as usual. An audit hook registered from C in the helper's process (an extension calling PySys_AddAuditHook) is not told apart from the compiler, as a hook added from Python is: a SyntaxError or ValueError it raises while the check compiles is read as the text's, and the message can then be answered as failing, or be rewritten.

3. Start Debugging

Start debugging your Python script:

start_debugging { "sessionId": "your-session-id", "scriptPath": "/abs/path/script.py",
                  "args": ["--optional", "arguments"] }

Optional tuning:

  • dapLaunchArgs: { "stopOnEntry": true } pauses on the first line (the default is false); { "justMyCode": false } steps into library code (the default is true).
  • Module launch: dapLaunchArgs: { "module": "pytest", "cwd": "/abs/project" } with args: ["tests/test_billing.py::test_rounding", "-x"] runs python -m pytest … under the debugger instead of scriptPath (issue #985). debugpy takes exactly one of program, module and code, so the launch goes out without program, and the answer's warning says so (dapLaunchArgs.module: launched as a module (python -m); program is not sent …). scriptPath still has to name an existing file — the test file, or the package's __main__.py — and cwd is what -m puts on sys.path: it defaults to the directory above the top-most package containing scriptPath (so python -m modpkg from modpkg/__main__.py resolves), and the warning names the directory chosen; set it explicitly — the project root for a pytest run — when the module lives elsewhere. code (python -c) works the same way.
  • breakOnExceptions: launch sessions default to "uncaught", so a crashing script pauses at the crash site with stack and locals intact instead of terminating the session. "all" also pauses on caught/raised exceptions; "none" opts out. Python edge case: debugpy treats sys.exit(n) with a non-zero code as an unhandled SystemExit and pauses there (sys.exit(0) runs to completion) — pass "none" if your script legitimately exits non-zero that way.
  • dryRunSpawn: true validates the spawn configuration without starting anything, and leaves the session exactly as it was — a running program included (issue #812); the same session then takes the real launch.

Debug a failing test in one call (pytest preset)

The most common entry point is a failing test, and translating it into a debug launch takes runner knowledge you should not need. testRunner: "pytest" does it (issue #985):

start_debugging { "sessionId": "...", "scriptPath": "/abs/project/tests/test_billing.py",
                  "testRunner": "pytest", "testTarget": "test_proration_rounding" }

No breakpoint is needed. The answer is the autopsy: state: "paused" at the failing assert, with snapshot.exception (AssertionError, pytest's rewritten explanation as the message), snapshot.frames and snapshot.locals (the test's variables, plus pytest's @py_assert* rewriting temporaries). A passing test runs to completion with exit code 0. testTarget is a selector inside the file — test_name, Class::test_name, test_name[param] — or a full node id of that file; omit it to run the whole file (-x stops at the first failure).

What the preset does, measured in spike-notes-pytest.md:

  • Runs python -m pytest <file>[::<target>] -x from pytest's rootdir — the nearest ancestor of the test file holding pytest.ini, a pyproject.toml with a [tool.pytest.ini_options] table, a tox.ini with [pytest] or a setup.cfg with [tool:pytest], else the nearest setup.py (pytest's own rule), else the top-most conftest.py ancestor, else the file's directory. dapLaunchArgs.cwd overrides it; your args are appended as pytest arguments.
  • Turns pytest-xdist and pytest-cov off for the run: -p no:xdist / -p no:cov when nothing asks for them (silent when the plugin is absent), or the plugin's inert switch — -n0 / --no-cov — when the project's own addopts turns it on (-p no: would make pytest reject those options with a usage error); your args asking for a plugin leave it alone. The PYTEST_ADDOPTS environment variable is not read: a project that enables a plugin there should name it in args. xdist's workers are child debug sessions whose stop only wait_for_stop reports, not the launch answer this preset promises (and the spawn used to fail under the Windows debuggee, issue #993); coverage's tracer competes with the debugger's on Pythons before 3.12.
  • Arms debugpy's userUnhandled filter beside uncaught under the breakOnExceptions default — pytest catches every test failure, so uncaught alone never fires on one. "all" and "none" behave as usual ("none" lets the failing test run to exit code 1). Any dapLaunchArgs: { "module": "pytest" } launch gets the same filters.
  • Where it stops: the failing assert in the test frame; for an exception raised in a helper, the raise site is the top frame with its locals readable, flagged unwound: true, and the live test frame is below it, the first frame without the flag; the answer's note says where the exception was raised and where execution is paused (issue #1143: frame names no longer carry pydevd's (Current frame) marker); a fixture that raises pauses in the fixture; pytest.skip() pauses once (Skipped, continue to move on); a decorated test lands on its assert. An exception pytest.raises expects never pauses under pydevd's sys.monitoring path — Python 3.12+ with debugpy 1.8.6 or later — which only sees an exception leave the test frame; under frame tracing — 3.11 and older, or an older debugpy on any Python (Ubuntu 24.04's packaged 1.8.0, say) — it pauses once at the raise — continue, and the test passes. A print before the assert reaches get_output with pytest's report after the run, not before the pause — pass args: ["-s"] for live prints.
  • restart_debugging replays the preset; dryRunSpawn: true answers data.script: "module: pytest" with the expansion in warning. A runner Python has no preset for is refused by name before anything starts.

4. Control Execution

When execution pauses at a breakpoint, you can:

Step Over (execute current line and pause at next line)

step_over { "sessionId": "your-session-id" }

Step Into (go into functions called on current line)

step_into { "sessionId": "your-session-id" }

Step Out (run until exiting current function)

step_out { "sessionId": "your-session-id" }

Continue (run until next breakpoint)

continue_execution { "sessionId": "your-session-id" }

Pause (pause a running program)

pause_execution { "sessionId": "your-session-id" }

5. Examine Program State

When paused, you can examine the program's state using the get_stack_trace -> get_scopes -> get_variables sequence. Each step returns numeric handles that feed into the next:

Step 1: Get the Stack Trace

get_stack_trace { "sessionId": "your-session-id" }

This returns stack frames, each with a numeric id (the frame ID). The top frame's id is not necessarily 0.

Step 2: Get Scopes for a Frame

Use the id from the top stack frame:

get_scopes { "sessionId": "your-session-id", "frameId": 3 }

This returns scopes (e.g., "Locals", "Globals"), each with a numeric variablesReference.

Step 3: Get Variables for a Scope

Use the variablesReference from a scope (not the frame ID):

get_variables { "sessionId": "your-session-id", "scope": 5 }

The scope parameter is the numeric variablesReference from get_scopes. Frame IDs and variable references are different numbers — never swap them.

debugpy may return a special variables entry inside a Locals scope. That is a container, not a variable: call get_variables again with scope set to its variablesReference to expand it and reveal the real locals.

Shortcut: Get Local Variables

For convenience, get_local_variables performs the full stack->scopes->variables traversal in a single call and filters out debugpy's special/internal entries (pass includeSpecial: true to keep them):

get_local_variables { "sessionId": "your-session-id" }

Evaluate Expressions

evaluate_expression { "sessionId": "your-session-id", "expression": "x + y * 2" }

Get Source Context

get_source_context { "sessionId": "your-session-id", "file": "/abs/path/script.py",
                     "line": 15, "linesContext": 5 }

6. Read Program Output

Python launches run with debugpy's redirectOutput, so print() and stderr are captured:

get_output { "sessionId": "your-session-id" }
get_output { "sessionId": "your-session-id", "since": 42 }

Output is buffered per launch and readable while the program runs and after it exits, until the session closes. Pass since = the previous response's nextSince to fetch only new entries. The same transcript is also exposed as the MCP resource debug://sessions/{sessionId}/output, which supports resources/subscribe.

7. Close the Session

When finished debugging, close the session:

close_debug_session { "sessionId": "your-session-id" }

Managing Breakpoints

Breakpoints have a lifecycle beyond set_breakpoint. All three tools below take effect immediately while the program is running or paused, and also work before launch and after the program has exited:

list_breakpoints   { "sessionId": "..." }                    # add "file" to scope to one file
remove_breakpoint  { "sessionId": "...", "breakpointId": "..." }
remove_breakpoint  { "sessionId": "...", "file": "/abs/path/script.py", "line": 15 }
remove_breakpoint  { "sessionId": "...", "function": "compute_total" }
clear_breakpoints  { "sessionId": "..." }                    # add "file" to scope to one file

list_breakpoints reports each breakpoint's verified state and adapter-assigned id; session-global function breakpoints appear separately as functionBreakpoints.

The Edit-Rerun Loop

restart_debugging terminates the current program (if it is still running) and relaunches it with the same configuration as the last start_debugging, re-applying all current breakpoints:

restart_debugging { "sessionId": "your-session-id" }

That turns "fix a line -> rerun -> land on the same breakpoints" into a single call. Two notes: the get_output buffer starts fresh (read from since: 0 after a restart), and restart_debugging is rejected for attach sessions.

Statement-anchored breakpoints (see above) are what make this loop robust — they re-resolve against the edited file instead of drifting when your edit shifts line numbers.

Attach Mode

Python attach is port-only: mcp-debugger connects directly to a listening debugpy endpoint. A processId — alone or beside a port — is refused by name before anything starts, with the --listen recipe (issue #903).

Start the target yourself:

python -m debugpy --listen 127.0.0.1:5678 --wait-for-client script.py

--wait-for-client blocks the script until a debugger attaches — use it for anything short-lived. Then:

create_debug_session { "language": "python" }
attach_to_process    { "sessionId": "...", "host": "127.0.0.1", "port": 5678 }
set_breakpoint       { "sessionId": "...", "file": "/abs/path/script.py", "line": 20 }
continue_execution   { "sessionId": "..." }

Shorthand: passing port to create_debug_session (or any attach target attach_to_process takes) creates the session and attaches in one call, with the same arguments.

After the handshake the attach is verified by polling for threads; raise verifyTimeout (default 20000 ms) for slow targets. breakOnExceptions applies no language default on attach — set it explicitly if you want it. detach_from_process { "sessionId": "...", "terminateProcess": false } leaves the target running. The target's Python children become child debug sessions of the attach session — the target decides at listen time: started with --configure-subProcess false (or debugpy.configure(subProcess=False)), they run undebugged — and close_debug_session or detach_from_process on the attach session releases them with it; the target and its children run on. close_debug_session on one of those child sessions releases that child the same way, with its own children, and answers released: true: no close ends a process of an attached tree (issue #1343; it used to end the child and answer processEnded: true).

Ending an attach session while the target is busy

The debug adapter behind --listen belongs to the target: debugpy starts it once, it owns the listening port, and nothing starts it again. It answers a disconnect only after pydevd inside the target has processed it, which needs the interpreter: within milliseconds on an idle target, but as long as the target holds the interpreter when it is busy (a long call into C code that keeps the GIL, a regular expression that backtracks, a stop-the-world pause). And when its client closes the connection before that answer is written, the adapter ends itself (debugpy/common/messaging.py, _run_handlers: self.close(); os._exit(1)): the target runs on, but its debug port is closed for the rest of its life.

close_debug_session and detach_from_process therefore both send the detaching disconnect and wait up to 10 s for the answer before the session's connection is closed (issue #1325). A session ended during a 3 to 4 s hold answers released: true when the hold ends, and the port serves the next attach. close_debug_session used to give the adapter 1 s, so closing a session while the target was busy for more than a second closed the target's debug port (measured with 0.27.0 and debugpy 1.8.22: a close during a 4 s hold, the adapter process gone, connections refused, the service itself still answering).

A second disconnect on the same connection does the same harm: a close sent while a detach waited for its answer used to send one, and the adapter ended while both calls said released: true. Between close_debug_session and detach_from_process calls, one session now has at most one release in flight. A close or a detach that arrives while another is in flight waits for it, sends no second release after a confirmed one, and answers from what it observed (measured with debugpy 1.8.20: a detach during a held interpreter and a close 200 ms later, one disconnect on the wire, both answers released: true once the hold ended, and the port served the next attach). That holds when the detach's release was confirmed and the detach then fails because stopping its worker failed, too (shown with an injected stop failure in the unit tests, not measured against debugpy). A detach whose release was not confirmed, whose request may never have reached the adapter, leaves the release to a close that joins it, which sends its own under the same 10 s bound rather than leave it to the worker's 1 s shutdown. close_debug_session lists each pairing's answer. The server's own exit does not join a release in flight: it sends no second disconnect once the first has gone out, but it closes the connection, which can be before the adapter has answered.

The close sends that release once the attach has put the session in running or paused, which can be before attach_to_process has returned (it may still be verifying threads or re-sending breakpoints): what the port depends on is the live connection, and a target slow to answer the attach's own requests is a busy one. That attach call can answer before the close does, failed or successful; either way the close removes the session, and until it returns, start_debugging, restart_debugging and attach_to_process on it are refused.

A target busy for longer than 10 s at the moment of a close or a detach can still lose its debug port. The answer then has no released, and its warning says the adapter did not confirm the release within 10000 ms, that the connection was closed, and that the target's debug port may have closed with it. The same goes for the closes that do not go through close_debug_session itself, which give the adapter 1 s as before: a close before the attach's handshake is done (the session still initializing), the server's own exit, and the idle policy's closes. A tree's close is not bounded by 10 s either: its children are closed first, each under its own 1 s cap, and then the root is released (see close_debug_session). Keeping the connection open past the bound is tracked in #1325. If you end sessions against a service that may be busy, end them when it is not; a client of your own that talks to the port directly must read the answer to disconnect before closing the socket.

Remote targets and path mapping

Breakpoint paths are sent verbatim to the remote debugger and resolved against the target's filesystem. For a container or pod, use debuggee-side paths (/app/app.py, as reported by get_stack_trace), or a function breakpoint, which needs no paths at all.

To address breakpoints by local-checkout path instead, pass debugpy's native mapping shape through adapterConfig (issue #450):

attach_to_process { "sessionId": "...", "host": "127.0.0.1", "port": 5678,
                    "adapterConfig": { "pathMappings": [
                      { "localRoot": "/abs/local/src", "remoteRoot": "/app" }] } }

Frames then report local paths too. Caveats:

  • The ptvsd-era bare localRoot/remoteRoot keys are not forwarded — pathMappings is the one lever. The attach response's warning names any adapterConfig keys that were ignored.
  • host and port must stay top-level; debugpy rejects a config carrying both connect and top-level host/port.
  • The attach tells debugpy which operating system the client's paths come from (clientOS, issue #1304). debugpy matches each breakpoint path against localRoot by that system's separator and writes the paths it translates back through pathMappings in that style; without the key it keeps its current setting, which is the target's own system unless an earlier attach to that process set another. mcp-debugger sends the system it runs on — "WINDOWS" on a Windows host, "UNIX" on Linux and macOS — because the paths it forwards are yours, verbatim, and normally written for that machine. Before, a Linux target took a Windows host's client for Linux: with localRoot C:\path\to\app and remoteRoot /srv/app (no trailing separators), a breakpoint at C:\path\to\app\service.py matched localRoot but kept its \ in the rest of the path, became /srv/app\service.py, which names no file on the target, and was answered "Breakpoint in file that does not exist."; a stop reached through the target's own path was reported as C:\path\to\app/service.py. (Roots that both ended in a separator already translated.) A Linux or macOS host attaching to a Windows target now sends "UNIX", so the client's paths are matched case-sensitively, and the paths translated through pathMappings come back with /; without mappings debugpy returns the target's native paths. mcp-debugger adds clientOS only when you pass none of clientOS, debugOptions and options (a null counts as not passed), and a clientOS you pass is forwarded as given. Set it yourself in two cases: when the paths you pass, localRoot and breakpoint files, are written in the other system's style than the machine mcp-debugger runs on — for example C:\… paths sent to the Docker image, which runs on Linux and forwards a path it does not find under its workspace as given — and whenever you pass debugOptions or options for any reason, since no default is added then: from a Windows host to a Linux target, { "options": "REDIRECT_OUTPUT=True", "pathMappings": [...] } needs "clientOS": "WINDOWS" beside it. debugpy accepts "windows", "unix" and "win" in any case; an empty string is forwarded and skips debugpy's set_ide_os, so it leaves pydevd's current client-system setting unchanged — the target's own system, unless an earlier attach to that process set another (pydevd keeps the setting between attaches); any other value fails the attach in the target. A launch needs none of this: its debuggee runs on the same machine.
  • "Breakpoint in file that does not exist." on an attach is debugpy's sentence about the target's file system: debugpy could not find the path you sent (after any pathMappings) there — either no file is at that path or the target process cannot reach it. set_breakpoint keeps debugpy's sentence in message and appends guidance to warning: attach with an adapterConfig.pathMappings entry whose localRoot contains the file and whose remoteRoot is the same directory on the target, or set the breakpoint by the target's own path when no pathMappings entry rewrites it (issue #1320).

For the Kubernetes port-forward pattern and per-language presets, see the Kubernetes debugging recipe and the attach presets.

Secret Redaction

Variable values, captured output, and evaluate results are scanned for credentials before they reach the transcript: values with a recognizable secret shape, and variables whose name exactly matches a known sensitive name (password, api_key, ...), come back masked and flagged redacted: true. Only the display is masked — program state is untouched. Start the server with DEBUG_MCP_NO_REDACT=1 to disable it (for example when debugging credential-handling code itself). Full rules and limitations: Secret redaction.

Known Limitations

Logpoint lines lost at program exit

When a Python logpoint fires faster than debugpy delivers messages (a few thousand lines a second), lines still queued in the debuggee when the program exits are dropped. The session's end answer reports a normal exit with no indication that lines were lost (issue #1265). See Logpoints for the full measurement.

Steps lost during exception unwinding (Python 3.12+)

With debugpy 1.8.22 on Python 3.12, 3.13 and 3.14, a step_over or step_out taken where an exception leaves the function never stops: the program runs on. This happens at a raise, on a line that raises out of its function, and from a finally block while the exception unwinds. step_into from the same place does stop. Since #1217 the step answer says the step was lost. This is debugpy #2100, reported upstream on 2026-11-26 (our issue #1194).

To keep these steps, opt in by setting the variable in the debuggee's launch environment:

start_debugging { "sessionId": "your-session-id", "scriptPath": "/abs/path/script.py",
                  "dapLaunchArgs": { "env": { "PYDEVD_USE_SYS_MONITORING": "0" } } }

The launch passes dapLaunchArgs.env through the Python adapter to debugpy. mcp-debugger does not set this variable by default: it costs 6 to 7 times on call-heavy code (10 million calls to a small function on Python 3.13: 2.26 s versus 0.38 s by default and 0.37 s without a debugger), and 1.6 to 1.8 times on a loop with no calls.

Debugging Tips

  1. "verified": false at set time is expected — debugpy binds breakpoints when it loads the module, not when you set them
  2. If the debugger doesn't stop at a breakpoint, ensure the file path is correct and absolute, and that the line is an executable statement (not a comment, a blank line, or a bare def/class line)
  3. Use source context to see code around your current position
  4. The stack trace shows the call hierarchy that led to the current position
  5. Expressions are evaluated against the current paused debug context (current frame when available), with the evaluation context defaulting to 'variables' — reads and arithmetic are reliable, but verify a mutation such as x = 5 with a follow-up evaluate before relying on it
  6. Child processes are debug sessions by default: debugpy's sub-process debugging is on (the last step of #1081), so every Python child the program starts (subprocess, multiprocessing, pytest-xdist workers, an autoreloader, a script that shells out to Python) becomes a child debug session of its own: list_debug_sessions lists it with parentSessionId naming this session, it stops on the breakpoints set on this session before launch (re-sent to it before it runs), and it has its own get_output and close_debug_session; closing the parent closes its children first. A wait_for_stop on this session is a wait on the tree: it reports a child's stop with sessionId naming the child (inspect, step and continue with that id) and children listing every child session with its state; a child can still be waited on by its own id. Each child parks until it is adopted (about 110 ms from report to its first stop), is a session row, and counts against DEBUG_MCP_MAX_CHILD_SESSIONS (default 32 live children per tree; beyond it a child is released and runs undebugged). Opt out per launch with dapLaunchArgs: { subProcess: false } (the children run undebugged and the launch answer's warning says so), per attach target with python -m debugpy --listen … --configure-subProcess false (or debugpy.configure(subProcess=False) in code — the attach request's subProcess is inert), or server-wide with DEBUG_MCP_MAX_CHILD_SESSIONS=0. The design is the session tree, built on the handshake measured in spike-notes-subprocess.md
  7. debugpy's own logs (debugpy.*.log) are off by default. To turn them on for launched sessions, set DEBUGPY_LOG_DIR to a directory in the server's environment (for an attach target, pass --log-to <dir> or set DEBUGPY_LOG_DIR when starting the target). Either switch also turns pydevd's debug log on inside the debugged program, which slows it: leave them off unless you are diagnosing debugpy itself (issue #1264).