cpp-debug-mcp 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,265 @@
1
+ """LSP/clangd MCP tool definitions."""
2
+
3
+ from pathlib import Path
4
+
5
+ from fastmcp import Context
6
+
7
+ from ..lsp.protocol import (
8
+ file_uri,
9
+ make_did_open,
10
+ make_text_document_position,
11
+ make_reference_params,
12
+ parse_diagnostic,
13
+ parse_hover,
14
+ parse_location,
15
+ parse_document_symbol,
16
+ )
17
+ from . import fmt
18
+
19
+
20
+ async def _ensure_file_open(session_id: str, file_path: str, ctx: Context) -> None:
21
+ """Open a file in clangd if not already opened."""
22
+ lsp_mgr = ctx.request_context.lifespan_context["lsp"]
23
+ client = lsp_mgr.get_session(session_id)
24
+ uri = file_uri(file_path)
25
+
26
+ if uri not in lsp_mgr.get_opened_files(session_id):
27
+ content = Path(file_path).resolve().read_text()
28
+ lang = "cpp"
29
+ if file_path.endswith(".c"):
30
+ lang = "c"
31
+ elif file_path.endswith(".h"):
32
+ lang = "c"
33
+ await client.send_notification(
34
+ "textDocument/didOpen",
35
+ make_did_open(file_path, content, lang),
36
+ )
37
+ lsp_mgr.mark_file_opened(session_id, uri)
38
+
39
+
40
+ def register_lsp_tools(mcp):
41
+ """Register all LSP tools on the FastMCP server instance."""
42
+
43
+ @mcp.tool()
44
+ async def lsp_start_session(
45
+ project_root: str,
46
+ compile_commands_dir: str = "",
47
+ ctx: Context = None,
48
+ ) -> str:
49
+ """Start a clangd LSP session for static analysis of C++ code.
50
+
51
+ Args:
52
+ project_root: Root directory of the C++ project.
53
+ compile_commands_dir: Directory containing compile_commands.json (optional, improves accuracy).
54
+ """
55
+ manager = ctx.request_context.lifespan_context["lsp"]
56
+ session_id, capabilities = await manager.create_session(
57
+ project_root, compile_commands_dir
58
+ )
59
+ return fmt.fmt_session_start("LSP/clangd", session_id)
60
+
61
+ @mcp.tool()
62
+ async def lsp_end_session(session_id: str, ctx: Context = None) -> str:
63
+ """End a clangd LSP session.
64
+
65
+ Args:
66
+ session_id: The session identifier returned by lsp_start_session.
67
+ """
68
+ manager = ctx.request_context.lifespan_context["lsp"]
69
+ await manager.destroy_session(session_id)
70
+ return fmt.fmt_session_end("LSP/clangd", session_id)
71
+
72
+ @mcp.tool()
73
+ async def lsp_diagnostics(
74
+ session_id: str,
75
+ file_path: str,
76
+ ctx: Context = None,
77
+ ) -> str:
78
+ """Get compile errors and warnings for a C++ file from clangd.
79
+
80
+ Args:
81
+ session_id: The LSP session identifier.
82
+ file_path: Absolute path to the C++ source file.
83
+ """
84
+ manager = ctx.request_context.lifespan_context["lsp"]
85
+ client = manager.get_session(session_id)
86
+
87
+ await _ensure_file_open(session_id, file_path, ctx)
88
+
89
+ notif = await client.wait_for_notification(
90
+ "textDocument/publishDiagnostics", timeout=15.0
91
+ )
92
+
93
+ if notif and "diagnostics" in notif:
94
+ diagnostics = [
95
+ parse_diagnostic(d, file_path).to_dict()
96
+ for d in notif["diagnostics"]
97
+ ]
98
+ return fmt.fmt_diagnostics(diagnostics)
99
+ return fmt.fmt_diagnostics([])
100
+
101
+ @mcp.tool()
102
+ async def lsp_hover(
103
+ session_id: str,
104
+ file_path: str,
105
+ line: int,
106
+ column: int,
107
+ ctx: Context = None,
108
+ ) -> str:
109
+ """Get type and documentation info at a specific code position.
110
+
111
+ Args:
112
+ session_id: The LSP session identifier.
113
+ file_path: Absolute path to the C++ source file.
114
+ line: 0-indexed line number.
115
+ column: 0-indexed column number.
116
+ """
117
+ manager = ctx.request_context.lifespan_context["lsp"]
118
+ client = manager.get_session(session_id)
119
+
120
+ await _ensure_file_open(session_id, file_path, ctx)
121
+
122
+ result = await client.send_request(
123
+ "textDocument/hover",
124
+ make_text_document_position(file_path, line, column),
125
+ )
126
+
127
+ hover = parse_hover(result)
128
+ if hover:
129
+ return fmt.fmt_hover(hover.to_dict())
130
+ return "No hover information."
131
+
132
+ @mcp.tool()
133
+ async def lsp_goto_definition(
134
+ session_id: str,
135
+ file_path: str,
136
+ line: int,
137
+ column: int,
138
+ ctx: Context = None,
139
+ ) -> str:
140
+ """Find where a symbol is defined.
141
+
142
+ Args:
143
+ session_id: The LSP session identifier.
144
+ file_path: Absolute path to the C++ source file.
145
+ line: 0-indexed line number.
146
+ column: 0-indexed column number.
147
+ """
148
+ manager = ctx.request_context.lifespan_context["lsp"]
149
+ client = manager.get_session(session_id)
150
+
151
+ await _ensure_file_open(session_id, file_path, ctx)
152
+
153
+ result = await client.send_request(
154
+ "textDocument/definition",
155
+ make_text_document_position(file_path, line, column),
156
+ )
157
+
158
+ if isinstance(result, list):
159
+ locations = [parse_location(loc).to_dict() for loc in result]
160
+ return fmt.fmt_locations(locations, "Definition")
161
+ elif isinstance(result, dict) and "uri" in result:
162
+ return fmt.fmt_locations([parse_location(result).to_dict()], "Definition")
163
+ return "No definition found."
164
+
165
+ @mcp.tool()
166
+ async def lsp_find_references(
167
+ session_id: str,
168
+ file_path: str,
169
+ line: int,
170
+ column: int,
171
+ ctx: Context = None,
172
+ ) -> str:
173
+ """Find all references to a symbol.
174
+
175
+ Args:
176
+ session_id: The LSP session identifier.
177
+ file_path: Absolute path to the C++ source file.
178
+ line: 0-indexed line number.
179
+ column: 0-indexed column number.
180
+ """
181
+ manager = ctx.request_context.lifespan_context["lsp"]
182
+ client = manager.get_session(session_id)
183
+
184
+ await _ensure_file_open(session_id, file_path, ctx)
185
+
186
+ result = await client.send_request(
187
+ "textDocument/references",
188
+ make_reference_params(file_path, line, column),
189
+ )
190
+
191
+ if isinstance(result, list):
192
+ locations = [parse_location(loc).to_dict() for loc in result]
193
+ return fmt.fmt_locations(locations, "References")
194
+ return "No references found."
195
+
196
+ @mcp.tool()
197
+ async def lsp_document_symbols(
198
+ session_id: str,
199
+ file_path: str,
200
+ ctx: Context = None,
201
+ ) -> str:
202
+ """List all symbols (functions, classes, variables) in a file.
203
+
204
+ Args:
205
+ session_id: The LSP session identifier.
206
+ file_path: Absolute path to the C++ source file.
207
+ """
208
+ manager = ctx.request_context.lifespan_context["lsp"]
209
+ client = manager.get_session(session_id)
210
+
211
+ await _ensure_file_open(session_id, file_path, ctx)
212
+
213
+ result = await client.send_request(
214
+ "textDocument/documentSymbol",
215
+ {"textDocument": {"uri": file_uri(file_path)}},
216
+ )
217
+
218
+ if isinstance(result, list):
219
+ symbols = [parse_document_symbol(s).to_dict() for s in result]
220
+ return fmt.fmt_symbols(symbols)
221
+ return "No symbols found."
222
+
223
+ @mcp.tool()
224
+ async def lsp_signature_help(
225
+ session_id: str,
226
+ file_path: str,
227
+ line: int,
228
+ column: int,
229
+ ctx: Context = None,
230
+ ) -> str:
231
+ """Get function signature help at a call site.
232
+
233
+ Args:
234
+ session_id: The LSP session identifier.
235
+ file_path: Absolute path to the C++ source file.
236
+ line: 0-indexed line number.
237
+ column: 0-indexed column number (should be inside the parentheses of a function call).
238
+ """
239
+ manager = ctx.request_context.lifespan_context["lsp"]
240
+ client = manager.get_session(session_id)
241
+
242
+ await _ensure_file_open(session_id, file_path, ctx)
243
+
244
+ result = await client.send_request(
245
+ "textDocument/signatureHelp",
246
+ make_text_document_position(file_path, line, column),
247
+ )
248
+
249
+ if result and "signatures" in result:
250
+ signatures = []
251
+ for sig in result["signatures"]:
252
+ signatures.append({
253
+ "label": sig.get("label", ""),
254
+ "documentation": sig.get("documentation", ""),
255
+ "parameters": [
256
+ {"label": p.get("label", ""), "documentation": p.get("documentation", "")}
257
+ for p in sig.get("parameters", [])
258
+ ],
259
+ })
260
+ return fmt.fmt_signature_help({
261
+ "signatures": signatures,
262
+ "active_signature": result.get("activeSignature", 0),
263
+ "active_parameter": result.get("activeParameter", 0),
264
+ })
265
+ return "No signature information."
@@ -0,0 +1,187 @@
1
+ Metadata-Version: 2.4
2
+ Name: cpp-debug-mcp
3
+ Version: 0.1.1
4
+ Summary: Claude Code MCP server for C++ debugging with GDB and clangd
5
+ Author: William-An
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/William-An/cpp-debug-mcp
8
+ Project-URL: Repository, https://github.com/William-An/cpp-debug-mcp
9
+ Project-URL: Issues, https://github.com/William-An/cpp-debug-mcp/issues
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Software Development :: Debuggers
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: fastmcp>=2.0
22
+ Requires-Dist: pygdbmi>=0.11
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest>=7.0; extra == "dev"
25
+ Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
26
+ Dynamic: license-file
27
+
28
+ # cpp-debug-mcp
29
+
30
+ A [Claude Code](https://claude.ai/code) MCP server plugin for C++ debugging. Integrates **GDB** (via GDB/MI) and **clangd** (via LSP) to give Claude Code tools for stepping through code, inspecting variables, reading diagnostics, and correlating runtime state with static analysis — all from the conversation.
31
+
32
+ ## Prerequisites
33
+
34
+ - Python 3.10+
35
+ - [GDB](https://www.gnu.org/software/gdb/) (for debugging tools)
36
+ - [clangd](https://clangd.llvm.org/) (for static analysis tools)
37
+ - [uv](https://github.com/astral-sh/uv) (recommended) or pip
38
+
39
+ ## Installation
40
+
41
+ **From PyPI** (once published):
42
+
43
+ ```bash
44
+ pip install cpp-debug-mcp
45
+ ```
46
+
47
+ **From GitHub** (always available):
48
+
49
+ ```bash
50
+ pip install git+https://github.com/William-An/cpp-debug-mcp.git
51
+ ```
52
+
53
+ **From source** (for development):
54
+
55
+ ```bash
56
+ git clone https://github.com/William-An/cpp-debug-mcp.git
57
+ cd cpp-debug-mcp
58
+ uv venv .venv
59
+ source .venv/bin/activate
60
+ uv pip install -e .
61
+ ```
62
+
63
+ ## Register with Claude Code
64
+
65
+ **Option A** — CLI command:
66
+
67
+ ```bash
68
+ claude mcp add cpp-debug -- python3 -m cpp_debug_mcp
69
+ ```
70
+
71
+ **Option B** — add to your project's `.mcp.json`:
72
+
73
+ ```json
74
+ {
75
+ "mcpServers": {
76
+ "cpp-debug": {
77
+ "type": "stdio",
78
+ "command": "python3",
79
+ "args": ["-m", "cpp_debug_mcp"],
80
+ "env": {
81
+ "GDB_PATH": "gdb",
82
+ "CLANGD_PATH": "clangd"
83
+ }
84
+ }
85
+ }
86
+ }
87
+ ```
88
+
89
+ Verify with `/mcp` inside Claude Code to confirm the server is connected.
90
+
91
+ ## Tools
92
+
93
+ ### GDB Tools (14)
94
+
95
+ | Tool | Description |
96
+ |---|---|
97
+ | `gdb_start_session` | Start a GDB session for a compiled executable |
98
+ | `gdb_end_session` | End a session and clean up |
99
+ | `gdb_run` | Start execution (optionally stop at `main`) |
100
+ | `gdb_set_breakpoint` | Set a breakpoint by file:line, function, or address |
101
+ | `gdb_delete_breakpoint` | Delete a breakpoint by ID |
102
+ | `gdb_list_breakpoints` | List all active breakpoints |
103
+ | `gdb_continue` | Continue until next breakpoint or exit |
104
+ | `gdb_step` | Step into, over, or out of functions |
105
+ | `gdb_backtrace` | Get the call stack |
106
+ | `gdb_list_variables` | List local variables in a stack frame |
107
+ | `gdb_evaluate` | Evaluate a C++ expression (e.g. `*ptr`, `arr[5]`) |
108
+ | `gdb_read_memory` | Read raw memory at an address |
109
+ | `gdb_thread_info` | List all threads and their states |
110
+ | `gdb_raw_command` | Execute a raw GDB command (with safety restrictions) |
111
+
112
+ ### LSP/clangd Tools (8)
113
+
114
+ | Tool | Description |
115
+ |---|---|
116
+ | `lsp_start_session` | Start a clangd session for a project |
117
+ | `lsp_end_session` | End a clangd session |
118
+ | `lsp_diagnostics` | Get compile errors and warnings for a file |
119
+ | `lsp_hover` | Get type/documentation info at a position |
120
+ | `lsp_goto_definition` | Find where a symbol is defined |
121
+ | `lsp_find_references` | Find all references to a symbol |
122
+ | `lsp_document_symbols` | List all symbols in a file |
123
+ | `lsp_signature_help` | Get function signature help at a call site |
124
+
125
+ ### Combined Tools (3)
126
+
127
+ | Tool | Description |
128
+ |---|---|
129
+ | `inspect_variable_with_type` | GDB runtime value + clangd type info for a variable |
130
+ | `diagnose_crash_site` | Backtrace + local variables + LSP diagnostics at crash |
131
+ | `analyze_function` | Breakpoint + signature + references + locals for a function |
132
+
133
+ ## Example Usage
134
+
135
+ Compile your C++ program with debug symbols, then ask Claude Code to debug it:
136
+
137
+ ```
138
+ > Compile main.cpp with debug symbols and find why it segfaults
139
+
140
+ Claude will:
141
+ 1. Run g++ -g -O0 -o main main.cpp
142
+ 2. Call gdb_start_session with the executable
143
+ 3. Call gdb_run to execute until the crash
144
+ 4. Call diagnose_crash_site to get the full crash report
145
+ 5. Explain the root cause with backtrace, variable values, and type info
146
+ ```
147
+
148
+ ## Architecture
149
+
150
+ ```
151
+ src/cpp_debug_mcp/
152
+ ├── server.py # FastMCP entry point with lifespan management
153
+ ├── gdb/
154
+ │ ├── controller.py # Async GDB/MI subprocess wrapper (pygdbmi)
155
+ │ └── session.py # Session lifecycle (max 4, 30min timeout)
156
+ ├── lsp/
157
+ │ ├── client.py # Async JSON-RPC client for clangd over STDIO
158
+ │ ├── protocol.py # LSP message helpers and response parsers
159
+ │ └── session.py # Session lifecycle (max 2, 30min timeout)
160
+ ├── analysis/
161
+ │ └── correlator.py # Cross-references GDB runtime + LSP static info
162
+ └── tools/
163
+ ├── gdb_tools.py # 14 GDB MCP tools
164
+ ├── lsp_tools.py # 8 LSP MCP tools
165
+ └── combined_tools.py # 3 combined analysis tools
166
+ ```
167
+
168
+ ## Safety
169
+
170
+ - **Command sanitization**: `gdb_raw_command` blocks `shell`, `!`, `python`, `pipe`, and `source` commands
171
+ - **Resource limits**: Max 4 GDB sessions and 2 LSP sessions concurrently
172
+ - **Auto-cleanup**: Stale sessions are cleaned up after 30 minutes of inactivity
173
+ - **Process lifecycle**: All subprocesses are terminated on server shutdown
174
+
175
+ ## Running Tests
176
+
177
+ ```bash
178
+ source .venv/bin/activate
179
+ uv pip install -e ".[dev]"
180
+ python -m pytest tests/ -v
181
+ ```
182
+
183
+ GDB tests require `gdb` to be installed. LSP tests require `clangd`. Tests that need unavailable tools are automatically skipped.
184
+
185
+ ## License
186
+
187
+ MIT
@@ -0,0 +1,22 @@
1
+ cpp_debug_mcp/__init__.py,sha256=UiSpNom4zea1y_pAD_IwoFYIFR4OAnp_UWGYuaok43g,68
2
+ cpp_debug_mcp/__main__.py,sha256=0DMl4DjVVC0Vs7VYvFXKl6SWWmEz2LR6msJbQAdsrQ0,127
3
+ cpp_debug_mcp/server.py,sha256=8K2IL-kmMSAN18r-ORDQ8vHi2J5NkLkFcombL0pskNo,1564
4
+ cpp_debug_mcp/analysis/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ cpp_debug_mcp/analysis/correlator.py,sha256=d5bdIS32xxPULFZbfrJ6wnqOO5wGX5NlqihiqoZ8RkY,9133
6
+ cpp_debug_mcp/gdb/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ cpp_debug_mcp/gdb/controller.py,sha256=7h7xgasUFE2mVBda0NYV7Gbg7F_8CXbm4q9g1QkyYdU,4507
8
+ cpp_debug_mcp/gdb/session.py,sha256=0263h0FW1C8RMyqZZz5kr8HcaLnT8oZ7KBYPD4HB2ns,5027
9
+ cpp_debug_mcp/lsp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ cpp_debug_mcp/lsp/client.py,sha256=sMRGBJyoHAFP-TNWP65feMX7-DS6q-plT3Tk0-PJrwM,7230
11
+ cpp_debug_mcp/lsp/protocol.py,sha256=hkWEjFD99m_N1JR6AU274Mzv_dnu--aTOCztAObH-SQ,6239
12
+ cpp_debug_mcp/lsp/session.py,sha256=g6vN35796KhSInCO0CuMNLvloozRKcOvCMEPxtMw0vI,3157
13
+ cpp_debug_mcp/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ cpp_debug_mcp/tools/combined_tools.py,sha256=IA0tp2RXQE9c9riKxwZEyQKl9NLyrid3bXM5aynYUTg,3935
15
+ cpp_debug_mcp/tools/fmt.py,sha256=7fEi9xXLGn0UGMkBNq5ZNuvHvs7mFOvZzTr1ZW3WgR4,10281
16
+ cpp_debug_mcp/tools/gdb_tools.py,sha256=i-ePNKMrOQd0hUNOi-wN4YO4371n4jtO4gwfF2-2S2A,13975
17
+ cpp_debug_mcp/tools/lsp_tools.py,sha256=_HiDCETG-_DAbZrYJgyvbMaVzZ-3etIMKad0YKQBSkk,8751
18
+ cpp_debug_mcp-0.1.1.dist-info/licenses/LICENSE,sha256=YCZc_XQjWo86Yvkpbf_v_oKlkUpc0RoBenX6dLlCvXk,1067
19
+ cpp_debug_mcp-0.1.1.dist-info/METADATA,sha256=oqXKPPCX0PsA0shtxmk9cTEETPckHHAeLD1--rnvPX8,6140
20
+ cpp_debug_mcp-0.1.1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
21
+ cpp_debug_mcp-0.1.1.dist-info/top_level.txt,sha256=BEPZy7Ydu_qxYMQetwU3MREM4l8Yoi3yHYZcXJZvWi4,14
22
+ cpp_debug_mcp-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 William-An
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ cpp_debug_mcp