Metadata-Version: 2.4
Name: dbgagent
Version: 0.5.0
Summary: AI-powered Python debugger — run a broken script, get root cause, explanation, and fix
Author: Aryan Tyagi
License-Expression: MIT
Project-URL: Homepage, https://github.com/aryantyagi2211/Debug_agent
Project-URL: Issues, https://github.com/aryantyagi2211/Debug_agent/issues
Keywords: debugger,python,ai,llm,groq,openai,claude
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: groq
Requires-Dist: openai
Requires-Dist: anthropic
Requires-Dist: python-dotenv
Requires-Dist: rich
Provides-Extra: mcp
Requires-Dist: mcp[cli]>=1.0; extra == "mcp"

# dbgagent

AI-powered Python debugger. Run a broken script, get a diagnosis with root cause, explanation, and a sandbox-verified fix.

> Built by [Aryan Tyagi](https://github.com/aryantyagi2211) with Codex/GPT-5.6 during OpenAI Build Week.

---

## What's New (v0.6.0)

### MCP Integration

dbgagent now supports Model Context Protocol (MCP) — both as a client and server.

**As MCP Client** — Connect to external MCP servers (databases, filesystems, APIs) for richer debugging context:

```bash
pip install "dbgagent[mcp]"
```

When a script fails, dbgagent matches the error against your configured triggers (e.g., "psycopg" → query PostgreSQL server for schema) and sends that context to the LLM for better fixes.

**As MCP Server** — Other AI tools (Claude Desktop, Cursor, opencode) can call dbgagent via MCP:

```bash
dbgagent-mcp
```

### Config Scope

- **Env var**: `DBGAGENT_CONFIG=/path/to/config.json` (highest priority)
- **Project**: `.dbgagent.json` in repo root
- **Global**: `~/.config/dbgagent/config.json` (lowest priority)

### New Files

| File | Purpose |
|------|---------|
| `mcp_client.py` | Connects to external MCP servers, queries context based on error triggers |
| `mcp_server.py` | Exposes dbgagent as MCP server with 5 tools |
| `dbgagent.example.json` | Example config with 12 MCP servers |

---

## Install

```bash
pip install dbgagent

# With MCP support
pip install "dbgagent[mcp]"
```

## Setup

Create `.env` with your Groq API key (free at [console.groq.com](https://console.groq.com)):

```
GROQ_API_KEY=your_key_here
```

## Usage

```bash
# Interactive menu (recommended)
dbgagent

# Direct debug
dbgagent run brokenscript.py

# MCP management
dbgagent add
dbgagent list
dbgagent remove
dbgagent config
dbgagent settings
```

### Interactive Menu

Run `dbgagent` with no arguments to see the interactive menu:

```
dbgagent — AI-powered Python debugger

What would you like to do?

  1 Debug a Python script
  2 Add MCP server
  3 List MCP servers
  4 Remove MCP server
  5 Edit config file
  6 Settings
  7 Exit

Pick [1-7]:
```

### Adding MCP Servers

```bash
dbgagent add
```

Follow the prompts:

```
Add MCP Server

Server name (e.g., agno): agno

Transport type:
  1 HTTP/SSE URL (e.g., http://localhost:8000/sse)
  2 stdio command (e.g., npx @modelcontextprotocol/server-postgres)

Pick [1/2]: 1
URL: http://localhost:8000/sse

Triggers (comma-separated, e.g., agno,agent,workflow): agno,agent,workflow

Server 'agno' added to .dbgagent.json
```

### Listing Servers

```bash
dbgagent list
```

```
┌──────────┬──────────┬─────────────────────────────────────┬──────────────────────┐
│ Name     │ Type     │ Connection                          │ Triggers             │
├──────────┼──────────┼─────────────────────────────────────┼──────────────────────┤
│ agno     │ HTTP/SSE │ http://localhost:8000/sse           │ agno, agent, workflow│
│ postgres │ stdio    │ npx @modelcontextprotocol/server... │ psycopg, postgresql  │
└──────────┴──────────┴─────────────────────────────────────┴──────────────────────┘
```

### Removing Servers

```bash
dbgagent remove
```

### Editing Config

```bash
dbgagent config
```

Opens `.dbgagent.json` in your default editor (`$EDITOR` or notepad).

### Settings

```bash
dbgagent settings
```

Shows current configuration: LLM provider, API key status, MCP servers count.

---

## How it works

```mermaid
flowchart TB
    subgraph User
        CMD["dbgagent run script.py"]
    end

    subgraph CLI["cli.py"]
        VAL[Check if .py file]
        RUN[Run script]
        LOOP[Try up to 3 times]
        DIFF[Show diff]
        APPLY{Apply fix? y/n}
    end

    subgraph Core
        CTX[Gather context]
        LLM[Ask LLM for fix]
        SBX[Test fix in temp folder]
    end

    CMD --> VAL
    VAL --> RUN
    RUN -->|exit 0| OK[Script works — done]
    RUN -->|exit ≠ 0| LOOP
    LOOP --> CTX --> LLM --> SBX
    SBX -->|pass| DIFF --> APPLY
    SBX -->|fail| LOOP
    APPLY -->|y| WRITE[Save fixed file]
    APPLY -->|n| SKIP[Skip — no changes]
```

## Debug loop

```mermaid
flowchart TD
    A[Run broken script] --> B{exit code 0?}
    B -->|Yes| C[Print success — done]
    B -->|No| D[Show error]
    D --> E[Read original file]
    E --> F["Try 1..3"]

    F --> G[Get context + ask LLM]
    G --> G2[Query MCP servers if triggers match]
    G2 --> H{Got fixed code?}
    H -->|No| I[Stop — can't verify]
    H -->|Yes| J[Run fix in temp folder]

    J --> K{Runs OK + no error output?}
    K -->|Yes| L[Show diff]
    L --> M{User says y?}
    M -->|Yes| N[Save fixed code to file]
    M -->|No| O[Skip]
    N --> P[Done]
    O --> P

    K -->|No| Q[Save error for next try]
    Q --> R{Tries left?}
    R -->|Yes| S[Re-run to get fresh traceback]
    S --> F
    R -->|No| T[All tries failed — no changes]
```

## Module overview

```mermaid
flowchart LR
    subgraph Entry
        CLI[cli.py<br/>argparse · Rich UI · retry · diff]
    end

    subgraph Execution
        RUN[runner.py<br/>run script · parse error]
        SBX[sandbox.py<br/>temp folder · test fix]
    end

    subgraph Intelligence
        CTX[context.py<br/>code · requirements · git diff]
        AGT[agent.py<br/>Groq API · JSON parse]
        MCP_C[mcp_client.py<br/>MCP servers · trigger match]
    end

    subgraph MCP["MCP Server (optional)"]
        MCP_S[mcp_server.py<br/>expose dbgagent as MCP]
    end

    CLI --> RUN
    CLI --> AGT
    CLI --> SBX
    AGT --> CTX
    AGT --> MCP_C
    AGT -->|llama-3.3-70b-versatile| GROQ[(Groq API)]
```

## Sandbox check

A fix only passes if the script exits with code 0 and produces no error output:

```mermaid
sequenceDiagram
    participant CLI
    participant Sandbox
    participant Temp as Temp folder
    participant Python

    CLI->>Sandbox: test_fix(script, fixed_code)
    Sandbox->>Temp: Write fixed file
    Sandbox->>Python: Run with 30s timeout
    Python-->>Sandbox: output, errors, exit code
    alt exit 0 AND no errors
        Sandbox-->>CLI: fixed=True
    else failure
        Sandbox-->>CLI: fixed=False + error
    end
    CLI->>Sandbox: cleanup temp folder
```

---

## Example output

```
$ dbgagent run brokenscript.py

dbgagent — AI-powered Python debugger

Running: brokenscript.py

Script failed (exit 1)

╭────── Traceback ──────╮
│ Traceback (most recent│
│   call last):         │
│   File "broken.py",   │
│     line 3            │
│   x = 1 / 0           │
│ ZeroDivisionError:    │
│   division by zero    │
╰───────────────────────╯

  Analyzing with LLM... ⠋

╭─── Root Cause ───╮
│ Division by zero │
│ on line 3        │
╰──────────────────╯
╭─── Explanation ──╮
│ x is divided by  │
│ 0 which is not   │
│ allowed          │
╰──────────────────╯
╭─── Proposed Fix ─╮
│ Add a check      │
│ before dividing  │
╰──────────────────╯

  Testing fix in sandbox... ⠋

╭─── Sandbox ──────╮
│ Fix verified!    │
╰──────────────────╯

diff -u original/broken.py fixed/broken.py
--- original/broken.py
+++ fixed/broken.py
@@ -1,3 +1,4 @@
-x = 1 / 0
+divisor = 0
+if divisor == 0:
+    print("Cannot divide by zero")
+else:
+    x = 1 / divisor

Apply fix to original file? (y/n): y
File updated.
```

---

## MCP Integration (Optional)

dbgagent can connect to MCP servers for richer context during debugging, and can also expose itself as an MCP server for other AI tools.

### Install with MCP support

```bash
pip install "dbgagent[mcp]"
```

### Configuration

#### Config scope

dbgagent supports three config levels:

1. **Env var** — `DBGAGENT_CONFIG=/path/to/config.json` (highest priority)
2. **Project config** — `.dbgagent.json` in repo root
3. **Global config** — `~/.config/dbgagent/config.json` (lowest priority)

Project config overrides global. Env var overrides both. MCP servers from all sources are merged (later sources override earlier servers with the same name).

#### Example config

Create `.dbgagent.json` in your project root or `~/.config/dbgagent/config.json` for global defaults. See `dbgagent.example.json` for full examples.

```json
{
  "mcp_servers": {
    "postgres": {
      "command": "npx",
      "args": ["@modelcontextprotocol/server-postgres", "postgresql://localhost:5432/mydb"],
      "triggers": ["psycopg", "postgresql", "database", "sql"]
    },
    "agno": {
      "url": "http://localhost:8000/sse",
      "triggers": ["agno", "agent", "workflow"]
    }
  }
}
```

**Transport types:**
- **stdio** — `{"command": "...", "args": [...]}` — spawns a subprocess
- **HTTP/SSE** — `{"url": "http://..."}` — connects to running server
- **Streamable HTTP** — `{"url": "http://..."}` — same config, auto-detected

### Using dbgagent as an MCP client

When an error matches configured triggers, dbgagent queries the relevant server (e.g., database schema, filesystem state) and sends that context to the LLM for better fixes.

```bash
dbgagent run broken_script.py
```

### Using dbgagent as an MCP server

Other AI tools (Claude Desktop, Cursor, opencode) can call dbgagent via MCP.

#### Available tools

| Tool | Description |
|------|-------------|
| `debug_run` | Run a Python script, return structured error info |
| `debug_context` | Gather source context around an error |
| `debug_analyze` | Analyze error with LLM, get root cause + fix |
| `debug_test_fix` | Test a fix in sandbox |
| `debug_script` | Full debug loop (run → analyze → test → retry) |

#### Run the MCP server

```bash
# Standalone
dbgagent-mcp

# Or via Python module
python -m debug_agent.mcp_server
```

#### Claude Desktop config

Add to `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "dbgagent": {
      "command": "dbgagent-mcp"
    }
  }
}
```

#### OpenCode config

Add to `opencode.json`:

```json
{
  "mcpServers": {
    "dbgagent": {
      "command": "dbgagent-mcp"
    }
  }
}
```

### Available servers

| Category | Server | Install |
|----------|--------|---------|
| Database | PostgreSQL | `npx @modelcontextprotocol/server-postgres` |
| Database | SQLite | `npx @modelcontextprotocol/server-sqlite` |
| Database | MongoDB | `npx @modelcontextprotocol/server-mongodb` |
| Database | Redis | `npx @modelcontextprotocol/server-redis` |
| Filesystem | Filesystem | `npx @modelcontextprotocol/server-filesystem` |
| Version Control | Git | `npx @modelcontextprotocol/server-git` |
| Web | Fetch | `npx @modelcontextprotocol/server-fetch` |
| Web | Brave Search | `npx @modelcontextprotocol/server-brave-search` |
| DevOps | GitHub | `npx @modelcontextprotocol/server-github` |
| DevOps | Kubernetes | `npx @modelcontextprotocol/server-kubernetes` |
| Monitoring | Sentry | `npx @modelcontextprotocol/server-sentry` |
| Memory | Memory | `npx @modelcontextprotocol/server-memory` |

## Architecture

| File | What it does |
|---|---|
| `runner.py` | Runs the script, parses traceback into structured error info |
| `context.py` | Reads source around the error, requirements.txt, git diff |
| `agent.py` | Sends context to Groq LLM, parses JSON response |
| `mcp_client.py` | Connects to MCP servers, queries relevant context based on error triggers |
| `mcp_server.py` | Exposes dbgagent as an MCP server for other AI tools |
| `sandbox.py` | Writes fix to temp dir, runs it, checks pass/fail |
| `cli.py` | Entry point — argparse, Rich output, retry loop, diff, apply prompt |

## License

MIT
