dbgeng-mcp

An MCP server that drives the Windows debugger engine (dbgeng) for dynamic analysis.
git clone https://dittus.dev/git/dbgeng-mcp.git
Log | Files | Refs | README

commit 994665e8ebb15c28256e3c44506ff623c4ac5efd
Author: dittus <dittus@pm.me>
Date:   Tue, 27 Oct 2026 17:47:06 -0400

Initial commit

Diffstat:
A.gitignore | 6++++++
AREADME.md | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Apyproject.toml | 17+++++++++++++++++
Asrc/dbgeng_mcp/__init__.py | 3+++
Asrc/dbgeng_mcp/_abi.py | 44++++++++++++++++++++++++++++++++++++++++++++
Asrc/dbgeng_mcp/_engine.py | 258+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/dbgeng_mcp/server.py | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/dbgeng_mcp/worker.py | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/diag.py | 45+++++++++++++++++++++++++++++++++++++++++++++
Atools/gen_abi.py | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/smoke.py | 45+++++++++++++++++++++++++++++++++++++++++++++
Atools/test_worker.py | 45+++++++++++++++++++++++++++++++++++++++++++++
12 files changed, 854 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1,6 @@ +.venv/ +__pycache__/ +*.pyc +*.egg-info/ +build/ +dist/ diff --git a/README.md b/README.md @@ -0,0 +1,96 @@ +# dbgeng-mcp + +An MCP server for dynamic analysis on Windows. It drives dbgeng, the engine behind WinDbg and cdb, so an MCP client can launch a program, attach to a process, or open a crash dump, then step, read memory and registers, set breakpoints, and run any WinDbg command. + +## How it is built + +Three layers: + +``` +MCP client <--stdio--> server.py <--JSON over a pipe--> worker.py --ctypes--> dbgeng.dll + (MCP) (WSL or Win) (Windows Python) +``` + +- `server.py` holds no debugger state. It exposes the MCP tools and forwards each call to the worker. +- `worker.py` owns one dbgeng engine and runs one target at a time. It lives in its own process because dbgeng is stateful and blocking, and because a target under analysis is code that runs. A separate process is one the server can kill and respawn. +- `_engine.py` binds dbgeng directly through ctypes. No pykd, no compiled extension. + +### Why a direct ctypes binding and not pykd + +pykd is the usual way to script dbgeng from Python, but its newest published build targets Python 3.7. On a current Python it is not an option. A direct binding has no such constraint: it runs on whatever Python is installed and needs nothing beyond the Debugging Tools. + +The cost is that the COM vtable layout is written out by hand. To keep that honest, `_abi.py` is generated from the Windows SDK's `DbgEng.h` by `tools/gen_abi.py`, so the method order and interface IDs match the dll that ships with that SDK. Regenerate it against your own header if the SDK moves: + +```bash +python3 tools/gen_abi.py "/mnt/c/Program Files (x86)/Windows Kits/10/Include/<ver>/um/DbgEng.h" +``` + +## Requirements + +- Windows 10 or 11, 64 bit. +- The Debugging Tools for Windows, which provide `dbgeng.dll`. Install the WinDbg package (`winget install Microsoft.WinDbg`) or the Windows SDK's Debugging Tools component. The engine is found under `C:\Program Files (x86)\Windows Kits\10\Debuggers\x64`, or set `DBGENG_DIR`. +- Python 3.10 or newer on the Windows side for the worker. Pure standard library, no packages. +- The `mcp` package (2.3 or newer) for the server. The server runs under WSL Python or Windows Python. + +The Debugging Tools binaries are not redistributed here. Install them separately. + +## Install + +```bash +python3 -m venv .venv && . .venv/bin/activate +pip install -e . +``` + +## Run + +As a standalone MCP stdio server: + +```bash +python -m dbgeng_mcp.server +``` + +From WSL the server spawns the worker with `python.exe` (Windows Python) and translates the worker path to its `\\wsl.localhost` form on its own. Override the interpreter or the worker path if needed: + +- `DBGENG_MCP_PYTHON` the Windows Python to run the worker (default `python.exe`). +- `DBGENG_MCP_WORKER` the worker script path (default the installed `worker.py`). + +### Wire it into an MCP client + +Point the client at the server command. Most clients take a command and its arguments, for example: + +```json +{ + "command": "/home/you/dev/dbgeng-mcp/.venv/bin/python", + "args": ["-m", "dbgeng_mcp.server"] +} +``` + +## Tools + +| Tool | What it does | +|---|---| +| `open_target` | Launch a command line, attach to a pid, or open a dump. Stops at the first instruction | +| `execute` | Run any WinDbg command and return its text (`lm`, `k`, `bp`, `dx`, `!peb`, ...) | +| `go` | Continue until the next breakpoint, exception, or exit | +| `step` | Single step one instruction, into or over | +| `read_memory` | Read bytes at an address, returned as hex | +| `registers` | The target's register values | +| `close` | End the session | + +`execute` is the escape hatch. Anything the structured tools do not cover, a raw command does. + +## Checking the binding + +`tools/smoke.py` launches a throwaway target and exercises the engine directly. `tools/test_worker.py` drives the worker over the same JSON protocol the server uses. Both run against the live engine: + +```bash +python.exe tools/smoke.py # engine, Windows Python +python3 tools/test_worker.py # worker over its pipe +``` + +## Limits + +- One target at a time. Opening a new one replaces the current. +- `registers` returns the engine's register text. Structured per register values are not exposed yet. +- Symbols follow `_NT_SYMBOL_PATH`. Set it to a local cache plus the Microsoft symbol server for names. +- Running an untrusted target runs its code. For real samples, run the worker in a disposable VM. diff --git a/pyproject.toml b/pyproject.toml @@ -0,0 +1,17 @@ +[project] +name = "dbgeng-mcp" +version = "0.1.0" +description = "An MCP server that drives the Windows debugger engine (dbgeng) for dynamic analysis" +readme = "README.md" +requires-python = ">=3.10" +dependencies = ["mcp>=2.3"] + +[project.scripts] +dbgeng-mcp = "dbgeng_mcp.server:main" + +[build-system] +requires = ["setuptools>=68"] +build-backend = "setuptools.build_meta" + +[tool.setuptools.packages.find] +where = ["src"] diff --git a/src/dbgeng_mcp/__init__.py b/src/dbgeng_mcp/__init__.py @@ -0,0 +1,3 @@ +"""dbgeng-mcp: an MCP server that drives the Windows debugger engine for dynamic analysis.""" + +__version__ = "0.1.0" diff --git a/src/dbgeng_mcp/_abi.py b/src/dbgeng_mcp/_abi.py @@ -0,0 +1,44 @@ +"""Generated by tools/gen_abi.py from the Windows SDK DbgEng.h. Do not edit by hand.""" + +INTERFACES = { + "IDebugClient": { + "iid": (670979641, 33799, 20295, 131, 100, 238, 17, 143, 176, 138, 200), # {27fe5639-8407-4f47-8364-ee118fb08ac8} + "guid_str": "{27fe5639-8407-4f47-8364-ee118fb08ac8}", + "methods": ['QueryInterface', 'AddRef', 'Release', 'AttachKernel', 'GetKernelConnectionOptions', 'SetKernelConnectionOptions', 'StartProcessServer', 'ConnectProcessServer', 'DisconnectProcessServer', 'GetRunningProcessSystemIds', 'GetRunningProcessSystemIdByExecutableName', 'GetRunningProcessDescription', 'AttachProcess', 'CreateProcess', 'CreateProcessAndAttach', 'GetProcessOptions', 'AddProcessOptions', 'RemoveProcessOptions', 'SetProcessOptions', 'OpenDumpFile', 'WriteDumpFile', 'ConnectSession', 'StartServer', 'OutputServers', 'TerminateProcesses', 'DetachProcesses', 'EndSession', 'GetExitCode', 'DispatchCallbacks', 'ExitDispatch', 'CreateClient', 'GetInputCallbacks', 'SetInputCallbacks', 'GetOutputCallbacks', 'SetOutputCallbacks', 'GetOutputMask', 'SetOutputMask', 'GetOtherOutputMask', 'SetOtherOutputMask', 'GetOutputWidth', 'SetOutputWidth', 'GetOutputLinePrefix', 'SetOutputLinePrefix', 'GetIdentity', 'OutputIdentity', 'GetEventCallbacks', 'SetEventCallbacks', 'FlushCallbacks'], + }, + "IDebugControl": { + "iid": (1367533160, 4190, 16750, 173, 146, 36, 239, 128, 4, 36, 186), # {5182e668-105e-416e-ad92-24ef800424ba} + "guid_str": "{5182e668-105e-416e-ad92-24ef800424ba}", + "methods": ['QueryInterface', 'AddRef', 'Release', 'GetInterrupt', 'SetInterrupt', 'GetInterruptTimeout', 'SetInterruptTimeout', 'GetLogFile', 'OpenLogFile', 'CloseLogFile', 'GetLogMask', 'SetLogMask', 'Input', 'ReturnInput', 'Output', 'OutputVaList', 'ControlledOutput', 'ControlledOutputVaList', 'OutputPrompt', 'OutputPromptVaList', 'GetPromptText', 'OutputCurrentState', 'OutputVersionInformation', 'GetNotifyEventHandle', 'SetNotifyEventHandle', 'Assemble', 'Disassemble', 'GetDisassembleEffectiveOffset', 'OutputDisassembly', 'OutputDisassemblyLines', 'GetNearInstruction', 'GetStackTrace', 'GetReturnOffset', 'OutputStackTrace', 'GetDebuggeeType', 'GetActualProcessorType', 'GetExecutingProcessorType', 'GetNumberPossibleExecutingProcessorTypes', 'GetPossibleExecutingProcessorTypes', 'GetNumberProcessors', 'GetSystemVersion', 'GetPageSize', 'IsPointer64Bit', 'ReadBugCheckData', 'GetNumberSupportedProcessorTypes', 'GetSupportedProcessorTypes', 'GetProcessorTypeNames', 'GetEffectiveProcessorType', 'SetEffectiveProcessorType', 'GetExecutionStatus', 'SetExecutionStatus', 'GetCodeLevel', 'SetCodeLevel', 'GetEngineOptions', 'AddEngineOptions', 'RemoveEngineOptions', 'SetEngineOptions', 'GetSystemErrorControl', 'SetSystemErrorControl', 'GetTextMacro', 'SetTextMacro', 'GetRadix', 'SetRadix', 'Evaluate', 'CoerceValue', 'CoerceValues', 'Execute', 'ExecuteCommandFile', 'GetNumberBreakpoints', 'GetBreakpointByIndex', 'GetBreakpointById', 'GetBreakpointParameters', 'AddBreakpoint', 'RemoveBreakpoint', 'AddExtension', 'RemoveExtension', 'GetExtensionByPath', 'CallExtension', 'GetExtensionFunction', 'GetWindbgExtensionApis32', 'GetWindbgExtensionApis64', 'GetNumberEventFilters', 'GetEventFilterText', 'GetEventFilterCommand', 'SetEventFilterCommand', 'GetSpecificFilterParameters', 'SetSpecificFilterParameters', 'GetSpecificFilterArgument', 'SetSpecificFilterArgument', 'GetExceptionFilterParameters', 'SetExceptionFilterParameters', 'GetExceptionFilterSecondCommand', 'SetExceptionFilterSecondCommand', 'WaitForEvent', 'GetLastEventInformation'], + }, + "IDebugRegisters": { + "iid": (3458765094, 40580, 17831, 147, 126, 103, 187, 24, 105, 20, 147), # {ce289126-9e84-45a7-937e-67bb18691493} + "guid_str": "{ce289126-9e84-45a7-937e-67bb18691493}", + "methods": ['QueryInterface', 'AddRef', 'Release', 'GetNumberRegisters', 'GetDescription', 'GetIndexByName', 'GetValue', 'SetValue', 'GetValues', 'SetValues', 'OutputRegisters', 'GetInstructionOffset', 'GetStackOffset', 'GetFrameOffset'], + }, + "IDebugDataSpaces": { + "iid": (2297946027, 16039, 19514, 174, 251, 196, 232, 16, 97, 115, 170), # {88f7dfab-3ea7-4c3a-aefb-c4e8106173aa} + "guid_str": "{88f7dfab-3ea7-4c3a-aefb-c4e8106173aa}", + "methods": ['QueryInterface', 'AddRef', 'Release', 'ReadVirtual', 'WriteVirtual', 'SearchVirtual', 'ReadVirtualUncached', 'WriteVirtualUncached', 'ReadPointersVirtual', 'WritePointersVirtual', 'ReadPhysical', 'WritePhysical', 'ReadControl', 'WriteControl', 'ReadIo', 'WriteIo', 'ReadMsr', 'WriteMsr', 'ReadBusData', 'WriteBusData', 'CheckLowMemory', 'ReadDebuggerData', 'ReadProcessorSystemData'], + }, + "IDebugSymbols": { + "iid": (2352081292, 38970, 18597, 144, 22, 111, 229, 214, 103, 169, 80), # {8c31e98c-983a-48a5-9016-6fe5d667a950} + "guid_str": "{8c31e98c-983a-48a5-9016-6fe5d667a950}", + "methods": ['QueryInterface', 'AddRef', 'Release', 'GetSymbolOptions', 'AddSymbolOptions', 'RemoveSymbolOptions', 'SetSymbolOptions', 'GetNameByOffset', 'GetOffsetByName', 'GetNearNameByOffset', 'GetLineByOffset', 'GetOffsetByLine', 'GetNumberModules', 'GetModuleByIndex', 'GetModuleByModuleName', 'GetModuleByOffset', 'GetModuleNames', 'GetModuleParameters', 'GetSymbolModule', 'GetTypeName', 'GetTypeId', 'GetTypeSize', 'GetFieldOffset', 'GetSymbolTypeId', 'GetOffsetTypeId', 'ReadTypedDataVirtual', 'WriteTypedDataVirtual', 'OutputTypedDataVirtual', 'ReadTypedDataPhysical', 'WriteTypedDataPhysical', 'OutputTypedDataPhysical', 'GetScope', 'SetScope', 'ResetScope', 'GetScopeSymbolGroup', 'CreateSymbolGroup', 'StartSymbolMatch', 'GetNextSymbolMatch', 'EndSymbolMatch', 'Reload', 'GetSymbolPath', 'SetSymbolPath', 'AppendSymbolPath', 'GetImagePath', 'SetImagePath', 'AppendImagePath', 'GetSourcePath', 'GetSourcePathElement', 'SetSourcePath', 'AppendSourcePath', 'FindSourceFile', 'GetSourceFileLineOffsets'], + }, + "IDebugSystemObjects": { + "iid": (1804009004, 11343, 20236, 157, 162, 23, 67, 17, 172, 195, 39), # {6b86fe2c-2c4f-4f0c-9da2-174311acc327} + "guid_str": "{6b86fe2c-2c4f-4f0c-9da2-174311acc327}", + "methods": ['QueryInterface', 'AddRef', 'Release', 'GetEventThread', 'GetEventProcess', 'GetCurrentThreadId', 'SetCurrentThreadId', 'GetCurrentProcessId', 'SetCurrentProcessId', 'GetNumberThreads', 'GetTotalNumberThreads', 'GetThreadIdsByIndex', 'GetThreadIdByProcessor', 'GetCurrentThreadDataOffset', 'GetThreadIdByDataOffset', 'GetCurrentThreadTeb', 'GetThreadIdByTeb', 'GetCurrentThreadSystemId', 'GetThreadIdBySystemId', 'GetCurrentThreadHandle', 'GetThreadIdByHandle', 'GetNumberProcesses', 'GetProcessIdsByIndex', 'GetCurrentProcessDataOffset', 'GetProcessIdByDataOffset', 'GetCurrentProcessPeb', 'GetProcessIdByPeb', 'GetCurrentProcessSystemId', 'GetProcessIdBySystemId', 'GetCurrentProcessHandle', 'GetProcessIdByHandle', 'GetCurrentProcessExecutableName'], + }, + "IDebugOutputCallbacks": { + "iid": (1274380357, 54868, 19520, 176, 175, 104, 48, 144, 243, 86, 220), # {4bf58045-d654-4c40-b0af-683090f356dc} + "guid_str": "{4bf58045-d654-4c40-b0af-683090f356dc}", + "methods": ['QueryInterface', 'AddRef', 'Release', 'Output'], + }, + "IDebugOutputCallbacksWide": { + "iid": (1283446371, 50068, 20006, 142, 241, 52, 173, 94, 211, 118, 76), # {4c7fd663-c394-4e26-8ef1-34ad5ed3764c} + "guid_str": "{4c7fd663-c394-4e26-8ef1-34ad5ed3764c}", + "methods": ['QueryInterface', 'AddRef', 'Release', 'Output'], + }, +} diff --git a/src/dbgeng_mcp/_engine.py b/src/dbgeng_mcp/_engine.py @@ -0,0 +1,258 @@ +"""Direct ctypes binding to dbgeng.dll, the Windows debugger engine. + +No pykd, no compiled extension. The vtable layout and interface IDs come from _abi.py, +which is generated from the Windows SDK's DbgEng.h, so the method indices match the +installed dll. See the README for why this route instead of pykd. + +This module is Windows only. It loads dbgeng.dll and its neighbours (dbghelp, symsrv) +from the Debugging Tools directory. +""" + +from __future__ import annotations + +import ctypes +import os +from ctypes import POINTER, byref, c_char_p, c_uint32, c_ulong, c_ulonglong, c_void_p + +from . import _abi + +# dbgeng constants (from DbgEng.h). +DEBUG_OUTCTL_THIS_CLIENT = 0x00000000 +DEBUG_OUTPUT_NORMAL = 0x00000001 +DEBUG_EXECUTE_DEFAULT = 0x00000000 +DEBUG_ONLY_THIS_PROCESS = 0x00000002 +CREATE_NO_WINDOW = 0x08000000 + +# Without this the engine lets a new process run free instead of stopping at its first +# instruction, so there is nothing to inspect and WaitForEvent blocks until the process exits. +DEBUG_ENGOPT_INITIAL_BREAK = 0x00000020 +DEBUG_WAIT_DEFAULT = 0x00000000 +INFINITE = 0xFFFFFFFF +DEBUG_END_ACTIVE_TERMINATE = 0x00000001 + +# Execution status values the engine reports and takes. +DEBUG_STATUS_GO = 1 +DEBUG_STATUS_STEP_OVER = 4 +DEBUG_STATUS_STEP_INTO = 5 +DEBUG_STATUS_BREAK = 6 +DEBUG_STATUS_NO_DEBUGGEE = 7 + +S_OK = 0 +E_NOINTERFACE = ctypes.c_long(0x80004002).value + + +class GUID(ctypes.Structure): + _fields_ = [("Data1", c_uint32), ("Data2", ctypes.c_uint16), + ("Data3", ctypes.c_uint16), ("Data4", ctypes.c_ubyte * 8)] + + +def _guid(parts) -> GUID: + g = GUID() + g.Data1, g.Data2, g.Data3 = parts[0], parts[1], parts[2] + for i in range(8): + g.Data4[i] = parts[3 + i] + return g + + +class DbgEngError(Exception): + def __init__(self, where: str, hresult: int): + self.hresult = hresult & 0xFFFFFFFF + super().__init__(f"{where} failed: 0x{self.hresult:08X}") + + +def _load_dbgeng() -> ctypes.WinDLL: + """Loads dbgeng.dll from the Debugging Tools, so its matching dbghelp/symsrv load too.""" + candidates = [ + os.environ.get("DBGENG_DIR"), + r"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64", + r"C:\Program Files\Windows Kits\10\Debuggers\x64", + ] + for folder in candidates: + if folder and os.path.isfile(os.path.join(folder, "dbgeng.dll")): + os.add_dll_directory(folder) + return ctypes.WinDLL(os.path.join(folder, "dbgeng.dll")) + # Fall back to the copy in System32. It works but may lag the SDK's dbghelp. + return ctypes.WinDLL("dbgeng.dll") + + +_dbgeng = _load_dbgeng() +_DebugCreate = _dbgeng.DebugCreate +_DebugCreate.restype = ctypes.c_long +_DebugCreate.argtypes = [POINTER(GUID), POINTER(c_void_p)] + + +def _method(interface: str, name: str): + """(vtable index, ) for a method, looked up by name in the generated table.""" + return _abi.INTERFACES[interface]["methods"].index(name) + + +def _call(this: int, interface: str, name: str, restype, argtypes, *args): + """Calls a COM method through the object's vtable. `this` is the interface pointer.""" + index = _method(interface, name) + vtbl = ctypes.cast(this, POINTER(c_void_p))[0] + func_addr = ctypes.cast(vtbl, POINTER(c_void_p))[index] + proto = ctypes.WINFUNCTYPE(restype, c_void_p, *argtypes) + return proto(func_addr)(this, *args) + + +def _check(where: str, hr: int): + if hr < 0: + raise DbgEngError(where, hr) + return hr + + +def _query_interface(this: int, interface: str) -> int: + out = c_void_p() + iid = _guid(_abi.INTERFACES[interface]["iid"]) + _check(f"QueryInterface({interface})", + _call(this, "IDebugClient", "QueryInterface", ctypes.c_long, + [POINTER(GUID), POINTER(c_void_p)], byref(iid), byref(out))) + return out.value + + +# Function prototypes for the output-callback object we hand to the engine. +_QIType = ctypes.WINFUNCTYPE(ctypes.c_long, c_void_p, POINTER(GUID), POINTER(c_void_p)) +_RefType = ctypes.WINFUNCTYPE(c_ulong, c_void_p) +_OutputType = ctypes.WINFUNCTYPE(ctypes.c_long, c_void_p, c_ulong, c_char_p) + + +class _OutputSink: + """A COM IDebugOutputCallbacks object, built by hand, that appends engine text to a buffer.""" + + def __init__(self): + self._chunks: list[str] = [] + self._output_iid = _guid(_abi.INTERFACES["IDebugOutputCallbacks"]["iid"]) + + # Keep every callable and the vtable alive for as long as the sink exists. + self._qi = _QIType(self._query_interface) + self._addref = _RefType(lambda this: 1) + self._release = _RefType(lambda this: 1) + self._output = _OutputType(self._on_output) + + VtblArray = c_void_p * 4 + self._vtbl = VtblArray( + ctypes.cast(self._qi, c_void_p), ctypes.cast(self._addref, c_void_p), + ctypes.cast(self._release, c_void_p), ctypes.cast(self._output, c_void_p)) + self._obj = c_void_p(ctypes.cast(self._vtbl, c_void_p).value) + + @property + def pointer(self) -> c_void_p: + """The address to pass to SetOutputCallbacks: &object, object[0] == &vtable.""" + return ctypes.cast(byref(self._obj), c_void_p) + + def take(self) -> str: + text = "".join(self._chunks) + self._chunks.clear() + return text + + def _query_interface(self, this, iid_ptr, out_ptr): + want = iid_ptr.contents + if bytes(want) == bytes(self._output_iid): + out_ptr[0] = this + return S_OK + out_ptr[0] = None + return E_NOINTERFACE + + def _on_output(self, this, mask, text): + if text: + self._chunks.append(text.decode("utf-8", "replace")) + return S_OK + + +class Engine: + """One debugger engine instance. Drives one target at a time.""" + + def __init__(self): + client = c_void_p() + iid = _guid(_abi.INTERFACES["IDebugClient"]["iid"]) + _check("DebugCreate", _DebugCreate(byref(iid), byref(client))) + self._client = client.value + self._control = _query_interface(self._client, "IDebugControl") + self._data = _query_interface(self._client, "IDebugDataSpaces") + + self._sink = _OutputSink() + _check("SetOutputCallbacks", + _call(self._client, "IDebugClient", "SetOutputCallbacks", ctypes.c_long, + [c_void_p], self._sink.pointer)) + + # Stop a freshly created process at its first instruction so there is state to inspect. + _check("AddEngineOptions", + _call(self._control, "IDebugControl", "AddEngineOptions", ctypes.c_long, + [c_ulong], DEBUG_ENGOPT_INITIAL_BREAK)) + + def create_process(self, command_line: str, show_window: bool = False): + flags = DEBUG_ONLY_THIS_PROCESS | (0 if show_window else CREATE_NO_WINDOW) + buffer = ctypes.create_string_buffer(command_line.encode("utf-8")) + _check("CreateProcess", + _call(self._client, "IDebugClient", "CreateProcess", ctypes.c_long, + [c_ulonglong, c_char_p, c_ulong], 0, ctypes.cast(buffer, c_char_p), flags)) + + def attach(self, pid: int, flags: int = 0): + _check("AttachProcess", + _call(self._client, "IDebugClient", "AttachProcess", ctypes.c_long, + [c_ulonglong, c_ulong, c_ulong], 0, pid, flags)) + + def open_dump(self, path: str): + _check("OpenDumpFile", + _call(self._client, "IDebugClient", "OpenDumpFile", ctypes.c_long, + [c_char_p], path.encode("utf-8"))) + + def wait_for_event(self, timeout_ms: int = INFINITE) -> int: + return _check("WaitForEvent", + _call(self._control, "IDebugControl", "WaitForEvent", ctypes.c_long, + [c_ulong, c_ulong], DEBUG_WAIT_DEFAULT, timeout_ms)) + + def execute(self, command: str) -> str: + """Runs a debugger command and returns everything it printed.""" + self._sink.take() # drop anything buffered + _check("Execute", + _call(self._control, "IDebugControl", "Execute", ctypes.c_long, + [c_ulong, c_char_p, c_ulong], + DEBUG_OUTCTL_THIS_CLIENT, command.encode("utf-8"), DEBUG_EXECUTE_DEFAULT)) + return self._sink.take() + + def execution_status(self) -> int: + status = c_ulong() + _check("GetExecutionStatus", + _call(self._control, "IDebugControl", "GetExecutionStatus", ctypes.c_long, + [POINTER(c_ulong)], byref(status))) + return status.value + + def set_execution_status(self, status: int): + _check("SetExecutionStatus", + _call(self._control, "IDebugControl", "SetExecutionStatus", ctypes.c_long, + [c_ulong], status)) + + def resume(self, status: int, timeout_ms: int = INFINITE) -> int: + """Sets execution going (go or a step), waits for the next stop, returns the new status.""" + self.set_execution_status(status) + try: + self.wait_for_event(timeout_ms) + except DbgEngError: + # A target that runs to exit leaves no event to wait for. Report that rather than raise. + if self.execution_status() == DEBUG_STATUS_NO_DEBUGGEE: + return DEBUG_STATUS_NO_DEBUGGEE + raise + return self.execution_status() + + def go(self, timeout_ms: int = INFINITE) -> int: + return self.resume(DEBUG_STATUS_GO, timeout_ms) + + def step_into(self, timeout_ms: int = INFINITE) -> int: + return self.resume(DEBUG_STATUS_STEP_INTO, timeout_ms) + + def step_over(self, timeout_ms: int = INFINITE) -> int: + return self.resume(DEBUG_STATUS_STEP_OVER, timeout_ms) + + def read_virtual(self, address: int, size: int) -> bytes: + buffer = (ctypes.c_ubyte * size)() + read = c_ulong() + _check("ReadVirtual", + _call(self._data, "IDebugDataSpaces", "ReadVirtual", ctypes.c_long, + [c_ulonglong, c_void_p, c_ulong, POINTER(c_ulong)], + address, ctypes.cast(buffer, c_void_p), size, byref(read))) + return bytes(buffer[:read.value]) + + def end_session(self): + _call(self._client, "IDebugClient", "EndSession", ctypes.c_long, + [c_ulong], DEBUG_END_ACTIVE_TERMINATE) diff --git a/src/dbgeng_mcp/server.py b/src/dbgeng_mcp/server.py @@ -0,0 +1,124 @@ +"""MCP server for dbgeng dynamic analysis. + +The server holds no debugger state itself. It spawns worker.py under Windows Python and +proxies each tool call to it over line-delimited JSON. One worker, one target at a time. + +Run it as an MCP stdio server (what an MCP client launches): python -m dbgeng_mcp.server +The server runs fine under WSL Python; the worker it spawns must be Windows Python with the +Debugging Tools installed. Override either with DBGENG_MCP_PYTHON / DBGENG_MCP_WORKER. +""" + +from __future__ import annotations + +import itertools +import json +import os +import subprocess +import threading + +from mcp.server.mcpserver import MCPServer + +INSTRUCTIONS = """Drive the Windows debugger engine (dbgeng) for dynamic analysis. +Open one target (launch an executable, attach to a pid, or load a crash dump), then inspect +it: run raw debugger commands, continue, single-step, read memory, and read registers. The +target stops at its first instruction when launched. `execute` is the escape hatch for any +WinDbg command (bp, dx, k, lm, ...). Only one target is open at a time; open replaces it.""" + + +def _to_windows_path(path: str) -> str: + """worker.py lives on the WSL filesystem; Windows Python needs its \\\\wsl.localhost path.""" + try: + return subprocess.check_output(["wslpath", "-w", path], text=True).strip() + except (FileNotFoundError, subprocess.CalledProcessError): + return path # already a Windows path, e.g. when the server itself runs on Windows + + +class Worker: + """Owns the worker subprocess and serializes request/response pairs with it.""" + + def __init__(self): + self._lock = threading.Lock() + self._ids = itertools.count(1) + self._proc: subprocess.Popen | None = None + self._python = os.environ.get("DBGENG_MCP_PYTHON", "python.exe") + worker = os.environ.get("DBGENG_MCP_WORKER") or os.path.join(os.path.dirname(__file__), "worker.py") + self._worker = _to_windows_path(worker) + + def _ensure(self): + if self._proc is None or self._proc.poll() is not None: + self._proc = subprocess.Popen( + [self._python, self._worker], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, bufsize=1) + + def call(self, cmd: str, **args) -> dict: + with self._lock: + self._ensure() + request = {"id": next(self._ids), "cmd": cmd, "args": args} + self._proc.stdin.write(json.dumps(request) + "\n") + self._proc.stdin.flush() + line = self._proc.stdout.readline() + if not line: + self._proc = None + raise RuntimeError("the debugger worker exited unexpectedly") + reply = json.loads(line) + if not reply.get("ok"): + raise RuntimeError(reply.get("error", "debugger worker error")) + return reply["result"] + + +worker = Worker() +server = MCPServer(name="dbgeng", instructions=INSTRUCTIONS) + + +@server.tool() +def open_target(mode: str, target: str) -> dict: + """Open a target and stop at its first instruction. + + mode: "launch" (target is a command line), "attach" (target is a process id), or + "dump" (target is a path to a crash dump). Returns the stop status and location. + """ + return worker.call("open", mode=mode, target=target) + + +@server.tool() +def execute(command: str) -> dict: + """Run any debugger (WinDbg) command and return its text output, e.g. lm, k, bp, dx, !peb.""" + return worker.call("execute", command=command) + + +@server.tool() +def go() -> dict: + """Continue the target until it next stops (breakpoint, exception, or exit).""" + return worker.call("go") + + +@server.tool() +def step(kind: str = "into") -> dict: + """Single-step one instruction. kind: "into" or "over".""" + return worker.call("step", kind=kind) + + +@server.tool() +def read_memory(address: str, size: int) -> dict: + """Read `size` bytes of target memory at `address` (a hex string like 0x7ff...), as hex.""" + return worker.call("read_memory", address=address, size=size) + + +@server.tool() +def registers() -> dict: + """Return the target's register values.""" + return worker.call("registers") + + +@server.tool() +def close() -> dict: + """Close the current target and end the debug session.""" + return worker.call("close") + + +def main(): + server.run("stdio") + + +if __name__ == "__main__": + main() diff --git a/src/dbgeng_mcp/worker.py b/src/dbgeng_mcp/worker.py @@ -0,0 +1,111 @@ +"""Debugger worker. Runs under Windows Python, owns one dbgeng engine, and speaks +line-delimited JSON on stdin/stdout. The MCP server spawns one of these per session. + +Kept in its own process on purpose: dbgeng is stateful and blocking, and running an +untrusted target under it is safer behind a process boundary the server can kill. + +Protocol: one JSON object per line in, one per line out. + in: {"id": 1, "cmd": "open", "args": {"mode": "launch", "target": "ping -n 2 127.0.0.1"}} + out: {"id": 1, "ok": true, "result": {...}} + {"id": 1, "ok": false, "error": "..."} +""" + +import json +import sys + +# Allow `python.exe worker.py` to find the package when run straight from the source tree. +if __package__ in (None, ""): + import os + sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from dbgeng_mcp._engine import Engine # noqa: E402 + +STATUS_NAMES = {0: "no_change", 1: "go", 4: "step_over", 5: "step_into", + 6: "break", 7: "no_debuggee"} + + +class Worker: + def __init__(self): + self.engine: Engine | None = None + + def handle(self, cmd: str, args: dict): + return getattr(self, f"cmd_{cmd}")(**args) + + def _require(self) -> Engine: + if self.engine is None: + raise RuntimeError("No target is open. Call open first.") + return self.engine + + def _stop_state(self, status: int) -> dict: + """Where the target is after a stop: status name and the current instruction.""" + name = STATUS_NAMES.get(status, status) + if status == 7: # no_debuggee: the target exited, so there is nothing to disassemble + return {"status": name, "location": "target has exited"} + where = self._require().execute("u @rip L1").strip().splitlines() + return {"status": name, "location": where[-1].strip() if where else ""} + + def cmd_open(self, mode: str, target) -> dict: + if self.engine is not None: + self.engine.end_session() + self.engine = None + engine = Engine() + if mode == "launch": + engine.create_process(str(target)) + elif mode == "attach": + engine.attach(int(target)) + elif mode == "dump": + engine.open_dump(str(target)) + else: + raise ValueError(f"unknown mode {mode!r} (launch, attach, or dump)") + engine.wait_for_event() + self.engine = engine + return self._stop_state(engine.execution_status()) + + def cmd_execute(self, command: str) -> dict: + return {"output": self._require().execute(command)} + + def cmd_go(self) -> dict: + return self._stop_state(self._require().go()) + + def cmd_step(self, kind: str = "into") -> dict: + engine = self._require() + status = engine.step_over() if kind == "over" else engine.step_into() + return self._stop_state(status) + + def cmd_read_memory(self, address, size: int) -> dict: + data = self._require().read_virtual(int(address, 0) if isinstance(address, str) else address, size) + return {"address": address, "size": len(data), "hex": data.hex()} + + def cmd_registers(self) -> dict: + return {"output": self._require().execute("r")} + + def cmd_close(self) -> dict: + if self.engine is not None: + self.engine.end_session() + self.engine = None + return {"closed": True} + + def cmd_ping(self) -> dict: + return {"pong": True} + + +def main(): + worker = Worker() + for line in sys.stdin: + line = line.strip() + if not line: + continue + request = json.loads(line) + response = {"id": request.get("id")} + try: + response["ok"] = True + response["result"] = worker.handle(request["cmd"], request.get("args", {})) + except Exception as error: + response["ok"] = False + response["error"] = f"{type(error).__name__}: {error}" + sys.stdout.write(json.dumps(response) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/tools/diag.py b/tools/diag.py @@ -0,0 +1,45 @@ +"""Low-level diagnostics: print the raw HRESULT of each engine call, no exceptions.""" +import ctypes +import os +import sys +from ctypes import POINTER, byref, c_char_p, c_ulong, c_ulonglong, c_void_p + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src")) +from dbgeng_mcp import _engine as E # noqa: E402 + + +def h(x): + return f"0x{x & 0xFFFFFFFF:08X}" + + +client = c_void_p() +iid = E._guid(E._abi.INTERFACES["IDebugClient"]["iid"]) +print("DebugCreate:", h(E._DebugCreate(byref(iid), byref(client)))) +client = client.value +control = E._query_interface(client, "IDebugControl") +print("have control:", control is not None) + +sink = E._OutputSink() +print("SetOutputCallbacks:", h(E._call(client, "IDebugClient", "SetOutputCallbacks", + ctypes.c_long, [c_void_p], sink.pointer))) + +buf = ctypes.create_string_buffer(b"cmd.exe") +hr = E._call(client, "IDebugClient", "CreateProcess", ctypes.c_long, + [c_ulonglong, c_char_p, c_ulong], 0, ctypes.cast(buf, c_char_p), + E.DEBUG_ONLY_THIS_PROCESS | E.CREATE_NO_WINDOW) +print("CreateProcess:", h(hr)) + +hr = E._call(control, "IDebugControl", "WaitForEvent", ctypes.c_long, + [c_ulong, c_ulong], 0, E.INFINITE) +print("WaitForEvent:", h(hr), "(S_OK means an event arrived, S_FALSE=0x1 means none)") + +status = c_ulong(0xDEAD) +hr = E._call(control, "IDebugControl", "GetExecutionStatus", ctypes.c_long, + [POINTER(c_ulong)], byref(status)) +print("GetExecutionStatus:", h(hr), "status=", h(status.value)) + +for outctl in (E.DEBUG_OUTCTL_THIS_CLIENT, 0x1, 0x2): + sink.take() + hr = E._call(control, "IDebugControl", "Execute", ctypes.c_long, + [c_ulong, c_char_p, c_ulong], outctl, b".echo hi", 0) + print(f"Execute(.echo, outctl={outctl}):", h(hr), "captured=", repr(sink.take()[:60])) diff --git a/tools/gen_abi.py b/tools/gen_abi.py @@ -0,0 +1,60 @@ +"""Generate src/dbgeng_mcp/_abi.py from a Windows SDK DbgEng.h. + + python3 tools/gen_abi.py "/mnt/c/Program Files (x86)/Windows Kits/10/Include/<ver>/um/DbgEng.h" + +The vtable order and interface IDs are read straight from the header, so the binding +matches whatever dbgeng.dll ships with that SDK. Method declarations come in three forms, +all of which take a vtable slot: STDMETHOD (HRESULT), STDMETHOD_ (other return type), and +STDMETHODV (variadic, e.g. Output). Missing any of them shifts every later index. +""" + +import os +import re +import sys + +INTERFACES = ["IDebugClient", "IDebugControl", "IDebugRegisters", "IDebugDataSpaces", + "IDebugSymbols", "IDebugSystemObjects", "IDebugOutputCallbacks", + "IDebugOutputCallbacksWide"] + +# STDMETHOD(Name) / STDMETHOD_(ret, Name) / STDMETHODV(Name) / STDMETHODV_(ret, Name). +METHOD = re.compile(r"STDMETHODV?(?:_)?\(\s*(?:[A-Za-z0-9_ \t\*]+,\s*)?(\w+)\s*\)") + + +def guid_tuple(text, name): + m = re.search(r"DEFINE_GUID\(\s*IID_%s\s*,(.*?)\);" % name, text, re.S) + return [int(x, 16) for x in re.findall(r"0x[0-9A-Fa-f]+", m.group(1))] + + +def guid_str(n): + return "{%08x-%04x-%04x-%02x%02x-%s}" % ( + n[0], n[1], n[2], n[3], n[4], "".join("%02x" % b for b in n[5:11])) + + +def methods(text, name): + m = re.search(r"DECLARE_INTERFACE_\(\s*%s\s*,\s*\w+\s*\)(.*?)\n\s*\};" % name, text, re.S) + return METHOD.findall(m.group(1)) + + +def main(header_path): + text = open(header_path, encoding="utf-8", errors="replace").read() + out = ['"""Generated by tools/gen_abi.py from the Windows SDK DbgEng.h. Do not edit by hand."""', + "", "INTERFACES = {"] + for iface in INTERFACES: + ms = methods(text, iface) + assert ms[:3] == ["QueryInterface", "AddRef", "Release"], (iface, ms[:4]) + g = guid_tuple(text, iface) + assert len(g) == 11 + out += [f' "{iface}": {{', + f' "iid": {tuple(g)}, # {guid_str(g)}', + f' "guid_str": "{guid_str(g)}",', + f' "methods": {ms},', + " },"] + out.append("}") + dest = os.path.join(os.path.dirname(__file__), "..", "src", "dbgeng_mcp", "_abi.py") + with open(dest, "w") as f: + f.write("\n".join(out) + "\n") + print(f"wrote {os.path.normpath(dest)} ({len(INTERFACES)} interfaces)") + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/tools/smoke.py b/tools/smoke.py @@ -0,0 +1,45 @@ +"""Live check of the dbgeng binding. Launches a throwaway target, runs a few commands, +reads memory, and tears down. Run with Windows Python: + + python.exe tools/smoke.py +""" + +import os +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src")) +from dbgeng_mcp import _engine as E # noqa: E402 +from dbgeng_mcp._engine import Engine # noqa: E402 + +STATUS_NAMES = {0: "NO_CHANGE", 1: "GO", 4: "STEP_OVER", 5: "STEP_INTO", + 6: "BREAK", 7: "NO_DEBUGGEE"} + +eng = Engine() +# A windowless, short target. The initial-break option stops it at its first instruction, +# so it never actually pings and nothing shows on screen. +eng.create_process("ping -n 2 127.0.0.1") +hr_event = eng.wait_for_event() +status = eng.execution_status() +print(f"wait_for_event hr=0x{hr_event & 0xFFFFFFFF:08X} status={STATUS_NAMES.get(status, status)}") + +print("\n== version"); print(" " + "\n ".join(eng.execute("version").splitlines()[:2])) +print("\n== lm1m (first 6 modules)") +for line in eng.execute("lm1m").splitlines()[:6]: + print(" ", line) +print("\n== registers (first 3 lines)") +for line in eng.execute("r").splitlines()[:3]: + print(" ", line) + +rip = eng.execute("? @rip") +print("\n== ? @rip:", rip.strip()) +try: + address = int(rip.split("=")[-1].strip().replace("`", ""), 16) + print(f"== read 16 bytes at {address:#x}:", eng.read_virtual(address, 16).hex()) + print("== disassemble:") + for line in eng.execute(f"u {address:#x} L3").splitlines(): + print(" ", line) +except ValueError: + print(" (could not parse @rip, no debuggee context)") + +eng.end_session() +print("\n== session ended") diff --git a/tools/test_worker.py b/tools/test_worker.py @@ -0,0 +1,45 @@ +"""Drives the worker the way the MCP server will: spawn Windows Python on worker.py and +exchange line-delimited JSON. Run under WSL Python: python3 tools/test_worker.py +""" + +import json +import re +import subprocess +import os + +HERE = os.path.dirname(os.path.abspath(__file__)) +WORKER = os.path.join(HERE, "..", "src", "dbgeng_mcp", "worker.py") +WORKER_WIN = subprocess.check_output(["wslpath", "-w", WORKER], text=True).strip() + +proc = subprocess.Popen(["python.exe", WORKER_WIN], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, text=True, bufsize=1) + +counter = iter(range(1, 1000)) + + +def call(cmd, **args): + proc.stdin.write(json.dumps({"id": next(counter), "cmd": cmd, "args": args}) + "\n") + proc.stdin.flush() + reply = json.loads(proc.stdout.readline()) + assert reply["ok"], f"{cmd} failed: {reply.get('error')}" + return reply["result"] + + +print("ping:", call("ping")) +print("open:", call("open", mode="launch", target="ping -n 2 127.0.0.1")) + +regs = call("registers")["output"] +rip = int(re.search(r"rip=([0-9a-f]+)", regs).group(1), 16) +print(f"rip = {rip:#018x}") + +mem = call("read_memory", address=rip, size=8) +print("read_memory @rip:", mem["hex"]) + +print("disasm:", call("execute", command=f"u {rip:#x} L1")["output"].strip().splitlines()[-1].strip()) +print("step into:", call("step", kind="into")) +print("step into:", call("step", kind="into")) +print("close:", call("close")) + +proc.stdin.close() +proc.wait(timeout=10) +print("worker exited", proc.returncode)