Skip to main content
Glama
README.md
# GDB MCP Server

An MCP (Model Context Protocol) server that provides AI assistants with programmatic access to GDB debugging sessions. This allows AI models to interact with debuggers in the same way IDEs like VS Code and CLion do, using the GDB/MI (Machine Interface) protocol.

## Features

- **Full GDB Control**: Start sessions, execute commands, control program execution
- **Thread Analysis**: Inspect threads, get backtraces, analyze thread states
- **Breakpoint Management**: Set conditional breakpoints, temporary breakpoints
- **Hardware Breakpoints**: Use CPU debug registers when software breakpoints are not suitable
- **Multi-line Commands**: Send `commands`, `define`, `python`, and other GDB command blocks
- **Blocking Execution Control**: `run`, `continue`, `step`, `next`, and `finish` wait until the target stops
- **Variable Inspection**: Evaluate expressions, inspect variables and registers
- **Core Dump Analysis**: Load and analyze core dumps with custom initialization
- **Flexible Initialization**: Run GDB scripts or commands on startup

## Fixes in This Fork

This fork focuses on making GDB MCP easier for AI agents to use in real debugging sessions:

- Fixed execution commands returning too early. `run`, `continue`, `step`, `next`, and `finish` now wait until GDB reports `*stopped`, so breakpoint hits and crashes are returned with the same command.
- Added a top-level `stopped` object to execution results, including stop reason, frame, thread, and breakpoint number when GDB provides them.
- Fixed multi-line GDB command blocks. `commands ... end`, `define ... end`, `python ... end`, `if ... end`, and `while ... end` no longer deadlock.
- Added per-command `timeout_sec` for long-running debug operations.
- Added hardware breakpoint support with `hardware=true`.
- Added an SSH stdio bridge example for running the MCP server on a remote VM while the MCP client runs locally.

## Architecture

This server uses the **GDB/MI (Machine Interface)** protocol, which is the same interface used by professional IDEs. It provides:

- Structured, machine-parseable output
- Full access to GDB's debugging capabilities
- Reliable command execution and response handling

## Installation

### Prerequisites

- Python 3.10 or higher
- GDB installed and available in PATH

### Quick Start

```bash
# Install pipx if needed
python3 -m pip install --user pipx
python3 -m pipx ensurepath

# Install gdb-mcp-server
cd /path/to/gdb-mcp
pipx install .
```

**For alternative installation methods (virtual environment, manual setup), see [INSTALL.md](INSTALL.md).**

## Configuration

### Claude Desktop

Add this to your Claude Desktop configuration file:

**Location:**
- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Linux**: `~/.config/Claude/claude_desktop_config.json`
- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`

**Configuration:**
```json
{
  "mcpServers": {
    "gdb": {
      "command": "gdb-mcp-server"
    }
  }
}
```

**For other installation methods and MCP clients, see [INSTALL.md](INSTALL.md#step-5-configure-your-mcp-client).**

### opencode

Add a project-level `opencode.json`:

```json
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "gdb": {
      "type": "local",
      "command": ["gdb-mcp-server"],
      "enabled": true,
      "timeout": 20000
    }
  }
}
```

For remote VM debugging, run the MCP server over SSH with the bridge example:

```json
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "gdb_remote": {
      "type": "local",
      "command": ["python", "examples/gdb_mcp_ssh_bridge.py"],
      "enabled": true,
      "timeout": 20000,
      "env": {
        "GDB_MCP_SSH_HOST": "your-vm-host",
        "GDB_MCP_SSH_USER": "root",
        "GDB_MCP_REMOTE_COMMAND": "cd /path/to/gdb-mcp && GDB_MCP_LOG_LEVEL=ERROR exec ./venv/bin/python -m gdb_mcp"
      }
    }
  }
}
```

Use SSH keys when possible. If password auth is required, set `GDB_MCP_SSH_PASSWORD` in your shell environment instead of committing it to `opencode.json`.

Start opencode from the project directory and tell the agent:

```text
use gdb_remote
```

## Environment Variables

The GDB MCP Server supports the following environment variables:

### `GDB_PATH`

Specify the path to the GDB executable to use. This is useful when:
- You have multiple GDB versions installed
- GDB is installed in a non-standard location
- You want to use a custom or patched GDB build

**Default**: `gdb` (resolved via system PATH)

**Example**:
```bash
export GDB_PATH=/usr/local/bin/gdb-13.2
gdb-mcp-server
```

**Note**: The `gdb_path` parameter in the `gdb_start_session` tool overrides this environment variable if both are specified.

### `GDB_MCP_LOG_LEVEL`

Set the logging level for the server.

**Default**: `INFO`
**Options**: `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`

**Example**:
```bash
export GDB_MCP_LOG_LEVEL=DEBUG
gdb-mcp-server
```

## Available Tools

The GDB MCP Server provides 22 tools for controlling GDB debugging sessions:

**Session Management:**
- `gdb_start_session` - Start a new GDB session with optional initialization
- `gdb_execute_command` - Execute GDB commands (CLI or MI format)
- `gdb_call_function` - Call a function in the target process (dedicated tool for separate permissioning)
- `gdb_get_status` - Get current session status
- `gdb_stop_session` - Stop the current session

**Thread & Frame Navigation:**
- `gdb_get_threads` - List all threads
- `gdb_select_thread` - Select a specific thread
- `gdb_get_backtrace` - Get stack trace for a thread
- `gdb_select_frame` - Select a specific stack frame
- `gdb_get_frame_info` - Get information about the current frame

**Breakpoint Management:**
- `gdb_set_breakpoint` - Set breakpoints with optional conditions, temporary mode, or hardware mode
- `gdb_list_breakpoints` - List all breakpoints with structured data
- `gdb_delete_breakpoint` - Delete a breakpoint by number
- `gdb_enable_breakpoint` - Enable a breakpoint
- `gdb_disable_breakpoint` - Disable a breakpoint

**Execution Control:**
- `gdb_continue` - Continue execution
- `gdb_step` - Step into functions
- `gdb_next` - Step over functions
- `gdb_interrupt` - Pause a running program

**Data Inspection:**
- `gdb_evaluate_expression` - Evaluate expressions
- `gdb_get_variables` - Get local variables
- `gdb_get_registers` - Get CPU registers

**For detailed documentation of each tool including parameters, return values, and examples, see [TOOLS.md](TOOLS.md).**

## Usage Examples

### Example 1: Analyzing a Core Dump

**User**: "Load the core dump at /tmp/core.12345, set the sysroot to /opt/sysroot, and tell me how many threads there were when it crashed."

**AI Actions**:
1. Start session with init commands:
```json
{
  "init_commands": [
    "file /path/to/executable",
    "core-file /tmp/core.12345",
    "set sysroot /opt/sysroot"
  ]
}
```
2. Get threads: `gdb_get_threads`
3. Report: "There were 8 threads when the program crashed."

### Example 2: Conditional Breakpoint Investigation

**User**: "Set a breakpoint at process_data but only when the count variable is greater than 100, then continue execution."

**AI Actions**:
1. Set conditional breakpoint:
```json
{
  "location": "process_data",
  "condition": "count > 100"
}
```
2. Continue execution: `gdb_continue`
3. When hit, inspect state

**For more detailed usage examples and workflows, see [examples/USAGE_GUIDE.md](examples/USAGE_GUIDE.md) and [examples/README.md](examples/README.md).**

## Advanced Usage

### Custom GDB Initialization Scripts

Create a `.gdb` file with your setup commands:

```gdb
# setup.gdb
file /path/to/myprogram
core-file /path/to/core

# Set up symbol paths
set sysroot /opt/sysroot
set solib-search-path /opt/libs:/usr/local/lib

# Convenience settings
set print pretty on
set print array on
set pagination off
```

Then use it:
```json
{
  "init_commands": ["source setup.gdb"]
}
```

### Python Initialization Scripts

You can also use GDB's Python API:

```python
# init.py
import gdb
gdb.execute("file /path/to/program")
gdb.execute("core-file /path/to/core")
# Custom analysis
```

Use with:
```json
{
  "init_commands": ["source init.py"]
}
```

### Working with Running Processes

While this server primarily works with core dumps and executables, you can attach to running processes:

```json
{
  "init_commands": [
    "attach 12345"  // PID of running process
  ]
}
```

Note: This requires appropriate permissions (usually root or same user).

## Troubleshooting

### Common Issues

**GDB Not Found**
```bash
which gdb
gdb --version
```

**Long-running Execution**

Execution commands block until the target stops, exits, crashes, or times out. For long-running programs, pass a larger `timeout_sec` to `gdb_execute_command`, `gdb_continue`, `gdb_step`, or `gdb_next`.

If the target is still running after the timeout, use `gdb_interrupt` to pause it.

**Program States:**
- **Not started**: Use `gdb_execute_command` with "run" or "start"
- **Running**: Program is executing - use `gdb_interrupt` to pause it
- **Paused** (at breakpoint): Use `gdb_continue`, `gdb_step`, `gdb_next`, inspect variables
- **Finished**: Program has exited - restart with "run" if needed

**Missing Debug Symbols**

Always check the `warnings` field in `gdb_start_session` response! Compile your programs with the `-g` flag.

**For detailed troubleshooting, installation issues, and more solutions, see [INSTALL.md](INSTALL.md#troubleshooting).**

## How It Works

1. **GDB/MI Protocol**: The server communicates with GDB using the Machine Interface (MI) protocol, the same interface used by IDEs.

2. **pygdbmi Library**: We use the excellent `pygdbmi` library to handle the low-level protocol details and response parsing.

3. **MCP Integration**: The server exposes GDB functionality as MCP tools, allowing AI assistants to:
   - Understand the available debugging operations
   - Execute commands with proper parameters
   - Interpret structured responses

4. **Session Management**: A single GDB session is maintained per server instance, allowing stateful debugging across multiple tool calls.

## Contributing

Contributions welcome! Areas for improvement:
- Additional GDB commands (e.g., watchpoints, memory inspection)
- Better error handling and recovery
- Enhanced output formatting

## License

MIT

## References

- [GDB Machine Interface (MI)](https://sourceware.org/gdb/current/onlinedocs/gdb/GDB_002fMI.html)
- [pygdbmi Documentation](https://github.com/cs01/pygdbmi)
- [Model Context Protocol](https://modelcontextprotocol.io/)

TDQS

A4.2/5.0

Scored across 22 tools

Disambiguation5/5

Each tool has a distinct purpose: session management, breakpoint operations, execution control, state inspection, and selection. There is no overlap; even stepping and continuing are clearly differentiated.

Naming Consistency5/5

All tool names follow the consistent pattern gdb_<verb> or gdb_<verb>_<noun> (e.g., gdb_set_breakpoint, gdb_get_backtrace). The prefix and naming style are uniform.

Tool Count5/5

22 tools cover the essential GDB debugging workflow without being excessive. Each tool serves a necessary function, and the count is well-scoped for a debugger server.

Completeness5/5

The tool surface covers the full debugging lifecycle: session start/stop, breakpoint management, execution control, thread/stack inspection, variable/register access, and expression evaluation. Any missing features can be accessed via gdb_execute_command, making the set comprehensive.

Maintenance

ActivityInactive
ResponsivenessNo issues