gdb-cli
GDB CLI для ИИ
English | 한국어 | 中文 | 日本語 | Español | Tiếng Việt | Português | Русский | Türkçe | Deutsch | Français | Italiano
Инструмент отладки GDB, разработанный для ИИ-агентов (Claude Code и др.). Использует архитектуру «тонкий клиент CLI + встроенный RPC-сервер GDB на Python», что позволяет выполнять отладку GDB с сохранением состояния через Bash.
Возможности
Анализ дампов памяти (Core Dump): Загрузка дампов с символами, находящимися в памяти, для отклика на уровне миллисекунд
Отладка при подключении к живому процессу: Подключение к запущенным процессам с поддержкой режима non-stop
Структурированный вывод JSON: Все команды выводят JSON с автоматическим усечением/пагинацией и подсказками по операциям
Механизмы безопасности: Белый список команд, автоматическая очистка по тайм-ауту heartbeat, гарантии идемпотентности
Оптимизация для баз данных: блокировка планировщика, пагинация больших объектов, усечение многопоточных данных
Related MCP server: GDB MCP Server
Требования
Python: 3.6.8+
GDB: 9.0+ с включенной поддержкой Python
ОС: Linux
Проверка поддержки Python в GDB
# Check if GDB has Python support
gdb -nx -q -batch -ex "python print('OK')"
# If system GDB lacks Python, check GCC Toolset (RHEL/CentOS)
/opt/rh/gcc-toolset-13/root/usr/bin/gdb -nx -q -batch -ex "python print('OK')"Установка
# Install from PyPI
pip install gdb-cli
# Or install from GitHub
pip install git+https://github.com/Cerdore/gdb-cli.git
# Or clone and install locally
git clone https://github.com/Cerdore/gdb-cli.git
cd gdb-cli
pip install -e .Проверка окружения
gdb-cli env-check
## Quick Start
### 1. Load Core Dump
```bash
gdb-cli load --binary ./my_program --core ./core.12345Вывод:
{
"session_id": "f465d650",
"mode": "core",
"binary": "./my_program",
"core": "./core.12345",
"gdb_pid": 12345,
"status": "loading"
}При загрузке большого бинарного файла или дампа памяти опрашивайте состояние, пока сессия не станет готова:
gdb-cli status -s f465d650{
"session_id": "f465d650",
"state": "ready",
"mode": "core",
"binary": "./my_program"
}Если в стандартном GDB вашей системы нет поддержки Python, укажите его путь с помощью
--gdb-path:gdb-cli load --binary ./my_program --core ./core.12345 \ --gdb-path /opt/rh/gcc-toolset-13/root/usr/bin/gdb
2. Операции отладки
Все операции используют --session / -s для указания ID сессии:
SESSION="f465d650"
# List threads
gdb-cli threads -s $SESSION
# Get backtrace (default: current thread)
gdb-cli bt -s $SESSION
# Get backtrace for a specific thread
gdb-cli bt -s $SESSION --thread 3
# Evaluate C/C++ expressions
gdb-cli eval-cmd -s $SESSION "my_struct->field"
# Access array elements
gdb-cli eval-element -s $SESSION "my_array" --index 5
# View local variables
gdb-cli locals-cmd -s $SESSION
# Execute raw GDB commands
gdb-cli exec -s $SESSION "info registers"
# Check session status
gdb-cli status -s $SESSION3. Управление сессиями
# List all active sessions
gdb-cli sessions
# Stop a session
gdb-cli stop -s $SESSION4. Отладка при подключении к живому процессу
# Attach to a running process (default: scheduler-locking + non-stop)
gdb-cli attach --pid 9876
# Attach with symbol file
gdb-cli attach --pid 9876 --binary ./my_program
# Allow memory modification and function calls
gdb-cli attach --pid 9876 --allow-write --allow-callПолный справочник команд
load — Загрузка дампа памяти
gdb-cli load --binary <path> --core <path> [options]
--binary, -b Executable file path (required)
--core, -c Core dump file path (required)
--sysroot sysroot path (for cross-machine debugging)
--solib-prefix Shared library prefix
--source-dir Source code directory
--timeout Heartbeat timeout in seconds (default: 600)
--gdb-path GDB executable path (default: "gdb")Команда load немедленно возвращает "status": "loading" после того, как RPC-сервер становится доступным. Используйте gdb-cli status -s <session> и дождитесь "state": "ready" перед выполнением тяжелых команд инспекции.
attach — Подключение к процессу
gdb-cli attach --pid <pid> [options]
--pid, -p Process PID (required)
--binary Executable file path (optional)
--scheduler-locking Enable scheduler-locking (default: true)
--non-stop Enable non-stop mode (default: true)
--timeout Heartbeat timeout in seconds (default: 600)
--allow-write Allow memory modification
--allow-call Allow function callsthreads — Список потоков
gdb-cli threads -s <session> [options]
--range Thread range, e.g., "3-10"
--limit Maximum return count (default: 20)
--filter-state Filter by state ("running" / "stopped")bt — Трассировка стека (Backtrace)
gdb-cli bt -s <session> [options]
--thread, -t Specify thread ID
--limit Maximum frame count (default: 30)
--full Include local variables
--range Frame range, e.g., "5-15"eval-cmd — Вычисление выражения
gdb-cli eval-cmd -s <session> <expr> [options]
--max-depth Recursion depth limit (default: 3)
--max-elements Array element limit (default: 50)eval-element — Доступ к элементам массива/контейнера
gdb-cli eval-element -s <session> <expr> --index <N>exec — Выполнение произвольной команды GDB
gdb-cli exec -s <session> <command>
--safety-level Safety level (readonly / readwrite / full)thread-apply — Пакетные операции с потоками
gdb-cli thread-apply -s <session> <command> --all
gdb-cli thread-apply -s <session> <command> --threads "1,3,5"Примеры вывода
threads
{
"threads": [
{"id": 1, "global_id": 1, "state": "stopped"},
{"id": 2, "global_id": 2, "state": "stopped"}
],
"total_count": 5,
"truncated": true,
"current_thread": {"id": 1, "global_id": 1, "state": "stopped"},
"hint": "use 'threads --range START-END' for specific threads"
}eval-cmd
{
"expression": "(int)5+3",
"value": 8,
"type": "int",
"size": 4
}bt
{
"frames": [
{"number": 0, "function": "crash_thread", "address": "0x400a1c", "file": "test.c", "line": 42},
{"number": 1, "function": "start_thread", "address": "0x7f3fa2e13fa"}
],
"total_count": 2,
"truncated": false
}Механизмы безопасности
Белый список команд (режим attach)
Уровень безопасности | Разрешенные команды |
| bt, info, print, threads, locals, frame |
| + set variable |
| + call, continue, step, next |
Команды quit, kill, shell, signal всегда заблокированы.
Тайм-аут Heartbeat
Автоматически отключается и завершает работу после 10 минут бездействия по умолчанию. Настраивается через --timeout.
Идемпотентность
Разрешена только одна сессия на PID / файл дампа. Повторный вызов load/attach возвращает существующий session_id.
Отладка дампов памяти с других машин
При анализе дампов памяти с других машин пути к общим библиотекам могут отличаться:
# Set sysroot (path prefix replacement)
gdb-cli load --binary ./my_program --core ./core.1234 \
--sysroot /path/to/target/rootfs
# Set source directory (for source-level debugging)
gdb-cli load --binary ./my_program --core ./core.1234 \
--source-dir /path/to/sourceРазработка
Структура проекта
src/gdb_cli/
├── cli.py # CLI entry point (Click)
├── client.py # Unix Socket client
├── launcher.py # GDB process launcher
├── session.py # Session metadata management
├── safety.py # Command whitelist filter
├── formatters.py # JSON output formatting
├── env_check.py # Environment check
├── errors.py # Error classification
└── gdb_server/
├── gdb_rpc_server.py # RPC Server core
├── handlers.py # Command handlers
├── value_formatter.py # gdb.Value serialization
└── heartbeat.py # Heartbeat timeout management
skills/
└── gdb-cli/ # Claude Code skill for intelligent debugging
├── SKILL.md # Skill definition
└── evals/ # Test cases for skill evaluationЗапуск тестов
pip install -e ".[dev]"
pytest tests/ -vСквозное тестирование (End-to-End)
Требуется GDB с поддержкой Python. Используйте программу для краш-тестов в tests/crash_test/:
# Compile test program
cd tests/crash_test
gcc -g -pthread -o crash_test crash_test_c.c
# Generate coredump
ulimit -c unlimited
./crash_test # Will SIGSEGV
# Find core file
ls /path/to/core_dumps/core-crash_test-*
# Run E2E test
gdb-cli load --binary ./crash_test --core /path/to/core \
--gdb-path /opt/rh/gcc-toolset-13/root/usr/bin/gdbИзвестные ограничения
Нет поддержки
target remote(используйте SSH для удаленной отладки, см. ниже)Нет поддержки отладки нескольких подчиненных процессов (inferiors)
Pretty-принтеры Guile в GDB 12.x не являются потокобезопасными, обходной путь через
format_string(raw=True)Встроенная версия Python в GDB может быть устаревшей (например, 3.6.8), в коде предусмотрена обработка совместимости
Удаленная отладка через SSH
Установите и запустите на удаленной машине одной командой:
ssh user@remote-host "pip install git+https://github.com/Cerdore/gdb-cli.git && gdb-cli load --binary ./my_program --core ./core.12345"Или сначала установите, затем отлаживайте:
# Install on remote
ssh user@remote-host "pip install git+https://github.com/Cerdore/gdb-cli.git"
# Run debugging
ssh user@remote-host "gdb-cli load --binary ./my_program --core ./core.12345"Навыки Claude Code
Этот проект включает навык gdb-cli для Claude Code, который обеспечивает интеллектуальную помощь в отладке, объединяя анализ исходного кода с инспекцией состояния во время выполнения.
Установка навыка
bunx skills add https://github.com/Cerdore/gdb-cli --skill=gdb-cliИспользование в Claude Code
/gdb-cli
# Or describe your debugging need:
I have a core dump at ./core.1234 and binary at ./myapp. Help me debug it.Возможности
Корреляция с исходным кодом: Автоматически считывает исходные файлы вокруг точек сбоя
Обнаружение взаимных блокировок (Deadlock): Выявляет шаблоны циклического ожидания в многопоточных программах
Предупреждения о безопасности: Оповещает о рисках для производственной среды при подключении к живым процессам
Структурированные отчеты: Генерирует анализ с гипотезами о первопричинах и следующими шагами
Подробнее см. skills/README.md.
Лицензия
Apache License 2.0
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Servers
- AlicenseBqualityCmaintenanceProvides GDB debugging functionality for use with Claude or other AI assistants, allowing users to manage debugging sessions, set breakpoints, examine variables, and execute GDB commands through natural language.Last updated16132154MIT
- AlicenseCqualityDmaintenanceEnables LLM clients to interact with the GNU Debugger (GDB) for comprehensive debugging and binary analysis. It provides a wide range of tools for program execution control, memory examination, stack analysis, and disassembly.Last updated1368GPL 3.0
- FlicenseAqualityDmaintenanceEnables AI agents to debug embedded systems by providing a comprehensive interface for GDB operations across multiple architectures like ARM and x86. It supports remote debugging via gdbserver or QEMU, allowing for detailed inspection of memory, registers, stack frames, and variables.Last updated31
- Alicense-qualityCmaintenanceEnables AI agents to interact with GDB for debugging via the MCP protocol. Supports setting breakpoints, stepping through code, inspecting memory and registers, and more.Last updated85MIT
Related MCP Connectors
Shared debugging memory for AI coding agents
Agent Replay Debugger MCP — record every agent step + deterministic replay. Step-debugger for
Live browser debugging for AI assistants — DOM, console, network via MCP.
Appeared in Searches
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/Cerdore/gdb-cli'
If you have feedback or need assistance with the MCP directory API, please join our Discord server