server.py (4388B)
1 """MCP server for dbgeng dynamic analysis. 2 3 The server holds no debugger state itself. It spawns worker.py under Windows Python and 4 proxies each tool call to it over line-delimited JSON. One worker, one target at a time. 5 6 Run it as an MCP stdio server (what an MCP client launches): python -m dbgeng_mcp.server 7 The server runs fine under WSL Python; the worker it spawns must be Windows Python with the 8 Debugging Tools installed. Override either with DBGENG_MCP_PYTHON / DBGENG_MCP_WORKER. 9 """ 10 11 from __future__ import annotations 12 13 import itertools 14 import json 15 import os 16 import subprocess 17 import threading 18 19 from mcp.server.mcpserver import MCPServer 20 21 INSTRUCTIONS = """Drive the Windows debugger engine (dbgeng) for dynamic analysis. 22 Open one target (launch an executable, attach to a pid, or load a crash dump), then inspect 23 it: run raw debugger commands, continue, single-step, read memory, and read registers. The 24 target stops at its first instruction when launched. `execute` is the escape hatch for any 25 WinDbg command (bp, dx, k, lm, ...). Only one target is open at a time; open replaces it.""" 26 27 28 def _to_windows_path(path: str) -> str: 29 """worker.py lives on the WSL filesystem; Windows Python needs its \\\\wsl.localhost path.""" 30 try: 31 return subprocess.check_output(["wslpath", "-w", path], text=True).strip() 32 except (FileNotFoundError, subprocess.CalledProcessError): 33 return path # already a Windows path, e.g. when the server itself runs on Windows 34 35 36 class Worker: 37 """Owns the worker subprocess and serializes request/response pairs with it.""" 38 39 def __init__(self): 40 self._lock = threading.Lock() 41 self._ids = itertools.count(1) 42 self._proc: subprocess.Popen | None = None 43 self._python = os.environ.get("DBGENG_MCP_PYTHON", "python.exe") 44 worker = os.environ.get("DBGENG_MCP_WORKER") or os.path.join(os.path.dirname(__file__), "worker.py") 45 self._worker = _to_windows_path(worker) 46 47 def _ensure(self): 48 if self._proc is None or self._proc.poll() is not None: 49 self._proc = subprocess.Popen( 50 [self._python, self._worker], 51 stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, bufsize=1) 52 53 def call(self, cmd: str, **args) -> dict: 54 with self._lock: 55 self._ensure() 56 request = {"id": next(self._ids), "cmd": cmd, "args": args} 57 self._proc.stdin.write(json.dumps(request) + "\n") 58 self._proc.stdin.flush() 59 line = self._proc.stdout.readline() 60 if not line: 61 self._proc = None 62 raise RuntimeError("the debugger worker exited unexpectedly") 63 reply = json.loads(line) 64 if not reply.get("ok"): 65 raise RuntimeError(reply.get("error", "debugger worker error")) 66 return reply["result"] 67 68 69 worker = Worker() 70 server = MCPServer(name="dbgeng", instructions=INSTRUCTIONS) 71 72 73 @server.tool() 74 def open_target(mode: str, target: str) -> dict: 75 """Open a target and stop at its first instruction. 76 77 mode: "launch" (target is a command line), "attach" (target is a process id), or 78 "dump" (target is a path to a crash dump). Returns the stop status and location. 79 """ 80 return worker.call("open", mode=mode, target=target) 81 82 83 @server.tool() 84 def execute(command: str) -> dict: 85 """Run any debugger (WinDbg) command and return its text output, e.g. lm, k, bp, dx, !peb.""" 86 return worker.call("execute", command=command) 87 88 89 @server.tool() 90 def go() -> dict: 91 """Continue the target until it next stops (breakpoint, exception, or exit).""" 92 return worker.call("go") 93 94 95 @server.tool() 96 def step(kind: str = "into") -> dict: 97 """Single-step one instruction. kind: "into" or "over".""" 98 return worker.call("step", kind=kind) 99 100 101 @server.tool() 102 def read_memory(address: str, size: int) -> dict: 103 """Read `size` bytes of target memory at `address` (a hex string like 0x7ff...), as hex.""" 104 return worker.call("read_memory", address=address, size=size) 105 106 107 @server.tool() 108 def registers() -> dict: 109 """Return the target's register values.""" 110 return worker.call("registers") 111 112 113 @server.tool() 114 def close() -> dict: 115 """Close the current target and end the debug session.""" 116 return worker.call("close") 117 118 119 def main(): 120 server.run("stdio") 121 122 123 if __name__ == "__main__": 124 main()