AutoCoder-MCP
by hasim2006
README.md
# AutoCoder-MCP
Autonomous Sandboxed Coding Agent with Model Context Protocol (MCP) and Self-Healing Test Execution.
---
## About the Project
In modern software engineering, autonomous coding agents represent a fundamental shift from passive AI code completion to active, closed-loop problem resolution. However, allowing language models to execute unconstrained code on host machines introduces severe security risks, including denial-of-service, fork bombs, and system tampering. Furthermore, single-turn LLMs frequently fail to handle complex edge cases on their first attempt.
AutoCoder-MCP solves these challenges by combining three critical architectural pillars:
1. Hardened Sandboxing: All code exploration, modification, and test execution occurs inside an isolated, resource-constrained container environment.
2. Standardized Tool Protocol: Model Context Protocol (MCP) provides a decoupled, JSON-RPC 2.0 interface between the agent reasoning engine and the execution environment.
3. Deterministic Self-Healing: An automated feedback loop captures unit test failure tracebacks, diagnoses assertion errors, and guides the agent to iteratively refine code until all tests pass green.
The result is a production-grade autonomous agent that fetches an issue from a repository, reproduces the bug, patches the codebase safely, verifies resolution with unit tests, and submits an automated Pull Request.
---
## Key Capabilities
### Sandboxed Execution Runtime
All untrusted code and test commands execute inside an isolated Docker container with strict resource limits:
- Memory Ceilings: Hard memory limit of 512MB to prevent host memory exhaustion.
- CPU Quotas: Throttled to 1.0 CPU core to prevent runaway infinite loops.
- Process Caps: Maximum limit of 100 active processes to eliminate fork bomb vulnerabilities.
- Non-Root Execution: Container runs under an unprivileged user context (`sandboxuser`, UID 1000) with disabled privilege escalation (`no-new-privileges`).
- Resilient Fallback: If Docker is not available in the host environment, an intelligent path-jailed local sandbox activates automatically to prevent directory traversal and block dangerous system commands.
### Model Context Protocol (MCP) Compliance
Rather than giving the model direct terminal access, the agent interacts with the workspace exclusively through standardized MCP tools over JSON-RPC 2.0:
- `list_files`: Explores repository structure within workspace boundaries.
- `read_file`: Reads source code and test files safely.
- `edit_file`: Performs targeted string replacements for surgical patching.
- `write_file`: Writes full file content when necessary.
- `run_command`: Executes validated shell commands inside the container.
- `run_tests`: Invokes the test suite (e.g., PyTest) and captures exit codes with stdout/stderr.
- `git_diff`: Generates a unified diff of current workspace changes.
### Traceback-Driven Self-Healing Loop
When a code patch fails the test suite, the Self-Healing Engine takes control:
1. Error Parsing: Extracts failed test identifiers, exception names (e.g., ZeroDivisionError, AssertionError), and relevant traceback segments.
2. Context Synthesis: Packages the failure log, current git diff, and targeted hints into a structured prompt.
3. Iterative Refinement: The language model analyzes why the previous attempt failed and applies corrective code changes.
4. Convergence: The loop continues until all unit tests pass (exit code 0) or the maximum attempt ceiling is reached, preventing token exhaustion.
### Automated Pull Request Workflow
Once the test suite is fully green:
- Creates a dedicated git branch (e.g., `fix/issue-42-autocoder`).
- Commits changes with a conventional commit message.
- Submits an automated Pull Request containing the issue summary, sandbox execution report, and verified unified diff.
### Real-Time Monitoring Web Dashboard
A built-in FastAPI backend provides:
- Live streaming of agent thoughts, tool invocations, and test results via Server-Sent Events (SSE).
- Visual pipeline tracking across all six lifecycle phases.
- Real-time unified diff viewer with syntax highlighting.
- Pull Request preview card displaying test metrics and repository links.
---
## Workflow Lifecycle
1. Issue Ingestion: Fetches the issue title, description, and reproduction steps from GitHub or simulated repositories.
2. Sandbox Provisioning: Initializes the isolated container and mounts the workspace.
3. Baseline Diagnostics: Runs the existing test suite inside the container to verify the bug reproduces.
4. Reasoning and Planning: The agent formulates a hypothesis and reads relevant source files.
5. Surgical Patching: Code modifications are applied via MCP tools.
6. Self-Healing Verification: Tests are executed. If any test fails, the traceback is parsed and fed back to the agent for iterative repair.
7. Verification and PR Creation: Once 100% test pass rate is achieved, git changes are committed and a Pull Request is generated.
---
## Quick Start Guide
### Prerequisites
- Python 3.12 or higher
- Git
- Docker (Optional: used for containerized isolation; fallback local sandbox activates automatically if Docker is offline)
### 1. Installation
Clone the repository and install dependencies:
```bash
git clone https://github.com/hasim2006/autocoder-MCP.git
cd autocoder-MCP
python -m pip install -r requirements.txt
```
### 2. Run Instant Terminal Demo
Execute the complete autonomous workflow directly in your terminal with zero configuration:
```bash
python run.py --demo
```
This sets up a sample repository, reproduces an issue, runs initial tests, triggers the self-healing loop on an edge-case failure, verifies all tests green, and creates a Pull Request.
### 3. Launch Web Dashboard
Start the FastAPI server:
```bash
python run.py --server
```
Open your browser at `http://localhost:8000` to interact with the visual dashboard.
---
## Automated Test Suite
A comprehensive test suite covering sandboxing, MCP JSON-RPC protocol compliance, self-healing parsing, and end-to-end integration is included.
Run all tests:
```bash
python -m pytest -v
```
Test coverage includes:
- Sandbox Security: Path traversal prevention and forbidden command rejection.
- MCP Server and Client: Tool schema validation and JSON-RPC dispatching.
- Self-Healing Engine: Failure log analysis and retry ceiling enforcement.
- Integration: Full lifecycle execution on a sample pricing engine repository.
---
## Configuration and Environment Variables
Configure settings via environment variables or a `.env` file (see `.env.example`):
| Variable | Description | Default |
| :--- | :--- | :--- |
| `LLM_PROVIDER` | LLM backend (`gemini`, `openai`, or `mock`) | `mock` |
| `GEMINI_API_KEY` | Google Gemini API key | None |
| `OPENAI_API_KEY` | OpenAI API key | None |
| `MODEL_NAME` | Model identifier | `gemini-2.5-flash` |
| `GITHUB_TOKEN` | GitHub personal access token for live PR creation | None |
| `DOCKER_IMAGE` | Base container image for sandboxing | `python:3.12-slim` |
| `SANDBOX_MEMORY_LIMIT`| Container RAM limit | `512m` |
| `SANDBOX_CPU_QUOTA` | Container CPU quota | `100000` (1 Core) |
| `SANDBOX_PIDS_LIMIT` | Maximum container processes | `100` |
| `MAX_HEALING_ATTEMPTS`| Maximum self-healing iterations before halting | `4` |
---
## Tech Stack
- Core Framework: Python 3.12, Pydantic v2
- Sandboxing: Docker SDK for Python, Subprocess Path-Jailing
- Agent Protocol: Model Context Protocol (MCP JSON-RPC 2.0)
- Reasoning: ReAct Pattern with pluggable LLM support (Gemini, OpenAI, Mock Engine)
- API and Web Server: FastAPI, Uvicorn, Server-Sent Events (SSE)
- Version Control: GitPython, GitHub REST API v3
- Testing Framework: PyTest
---
## License
This project is licensed under the MIT License.
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues