Skip to main content
Glama
DaoudiAmir

GreenCodeMCP

by DaoudiAmir
README.md
# GreenCodeMCP

[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.21373323.svg)](https://doi.org/10.5281/zenodo.21373323)

**An MCP-based tool for sustainable software maintenance and resource-aware refactoring.**

> Accepted at IEEE ICSME 2026 — Tool Demonstration and Data Showcase Track

---

## Overview

GreenCodeMCP is a developer-facing tool that connects modern AI coding assistants to a sustainable refactoring workflow via the **Model Context Protocol (MCP)**. Given Python code, it:

1. **Detects** energy anti-patterns using 20 AST-based rules
2. **Retrieves** optimization evidence from an 800-example knowledge base
3. **Suggests** refactored code (deterministic auto-fix + LLM-assisted)
4. **Validates** behavioral preservation (syntax, signature, tests, output hash)
5. **Benchmarks** resource gains under a controlled protocol (time, memory, energy, CO2)
6. **Reports** results as structured JSON or Markdown

It integrates directly into **VS Code**, **Cursor**, and **Windsurf** via MCP.

---

## Installation

### Prerequisites

- Python >= 3.10
- No GPU required
- (Optional) NVIDIA API key for LLM-assisted refactoring — [get one free](https://build.nvidia.com)

### Setup

```bash
# Clone the repository
git clone https://github.com/DaoudiAmir/GreenCodeMCP.git
cd GreenCodeMCP

# Create and activate a virtual environment
python -m venv .venv

# Windows
.venv\Scripts\activate
# Linux / macOS
source .venv/bin/activate

# Install the package
pip install -e .

# (Optional) Configure LLM access
cp .env.example .env
# Edit .env and set NVIDIA_API_KEY=your_key_here
```

> **Note:** Without an API key, all features work except LLM-assisted generation. The deterministic auto-fix (7 rules), KB retrieval, validation, and benchmarking are fully offline.

---

## Running the MCP Server

Start the server with:

```bash
python -m src.greencode_mcp.mcp_server
```

The server communicates over **stdio** (standard input/output), which is the default MCP transport for IDE integration.

---

## IDE Integration

### Cursor

Add to your Cursor MCP settings (`.cursor/mcp.json` in your project, or global settings):

```json
{
  "mcpServers": {
    "greencode-mcp": {
      "command": "python",
      "args": ["-m", "src.greencode_mcp.mcp_server"],
      "cwd": "/absolute/path/to/GreenCodeMCP"
    }
  }
}
```

Then in Cursor's chat, the 9 GreenCodeMCP tools become available to the AI agent.

### VS Code (with Copilot MCP support)

Add to your VS Code settings (`.vscode/mcp.json`):

```json
{
  "servers": {
    "greencode-mcp": {
      "command": "python",
      "args": ["-m", "src.greencode_mcp.mcp_server"],
      "cwd": "/absolute/path/to/GreenCodeMCP"
    }
  }
}
```

### Windsurf

Add to your Windsurf MCP configuration (`~/.codeium/windsurf/mcp_config.json`):

```json
{
  "mcpServers": {
    "greencode-mcp": {
      "command": "python",
      "args": ["-m", "src.greencode_mcp.mcp_server"],
      "cwd": "/absolute/path/to/GreenCodeMCP"
    }
  }
}
```

### Tips

- Replace `/absolute/path/to/GreenCodeMCP` with the actual absolute path to this repository.
- On Windows, use the full path to the Python executable inside the venv:
  ```json
  "command": "C:/path/to/GreenCodeMCP/.venv/Scripts/python.exe"
  ```
- After configuring, restart the IDE or reload MCP servers.
- Verify the tools are loaded by asking the agent: *"List available MCP tools"*.

---

## MCP Tools

| # | Tool | Description |
|---|------|-------------|
| 1 | `analyze_code` | Detect energy anti-patterns (20 AST rules) |
| 2 | `retrieve_green_practices` | Query KB for relevant before/after examples |
| 3 | `suggest_refactoring` | Generate optimized code (auto-fix + LLM) |
| 4 | `validate_equivalence` | Verify functional correctness preservation |
| 5 | `benchmark_resource_gain` | Measure time, memory, energy, CO2 gains |
| 6 | `run_full_green_refactor_pipeline` | End-to-end pipeline (recommended) |
| 7 | `generate_green_report` | Produce JSON or Markdown report |
| 8 | `list_demo_workloads` | List available demo scenarios |
| 9 | `run_demo_workload` | Run a complete demo scenario |

### Typical Usage (via AI agent in IDE)

> "Analyze this Python file for energy anti-patterns and suggest an optimized version"

The agent will call `run_full_green_refactor_pipeline`, which orchestrates all stages and returns a full report.

---

## Demo

Run the built-in demo without IDE integration:

```bash
# Single workload
python scripts/run_demo.py --workload transaction_analytics

# All demo workloads
python scripts/run_demo.py --all
```

### Available Demo Workloads

| Workload | Category | Anti-patterns | Expected Gain |
|----------|----------|---------------|---------------|
| `statistics_sorting` | Statistics & Sorting | Multiple sorts, list in sum, string concat | 20–50% |
| `numerical_loops` | Numerical Computation | Generator misuse, redundant computation | 15–40% |
| `transaction_analytics` | Data Processing | Deep copy, repeated iteration, O(n²) grouping | 30–60% |

---

## Project Structure

```
GreenCodeMCP/
├── src/greencode_mcp/          # Core MCP tool package
│   ├── mcp_server.py           # MCP server entry point (9 tools)
│   ├── config.py               # Centralized configuration
│   ├── schemas.py              # Data schemas
│   ├── analysis/               # 20 AST-based energy anti-pattern rules
│   ├── kb/                     # TF-IDF retrieval over 800-entry KB
│   ├── generation/             # Refactoring (auto-fix + LLM)
│   ├── validation/             # 4-level functional equivalence gate
│   ├── benchmark/              # Controlled benchmarking (CodeCarbon)
│   ├── pipelines/              # End-to-end pipeline orchestration
│   └── reporting/              # JSON + Markdown report generation
├── data/
│   ├── knowledge_base/         # 800 curated energy-optimization samples
│   └── demo_workloads/         # 3 controlled demo scenarios
├── scripts/
│   └── run_demo.py             # CLI demo runner
├── tests/                      # Test suite (91 tests)
├── pyproject.toml              # Package metadata and dependencies
├── requirements.txt            # Python dependencies
├── .env.example                # Environment variable template
└── LICENSE                     # MIT License
```

---

## Knowledge Base

The `data/knowledge_base/` directory contains **800 curated Python energy-optimization examples** derived from 7,056 candidates through a 10-step filtering pipeline. Each entry includes:

- Original (inefficient) code
- Optimized code
- Functional test assertions
- CodeCarbon-estimated energy measurements (before/after)
- Quality tier (Gold / Silver / Bronze)

Sources: MBPP, Mercury (NeurIPS 2024), HumanEval.

---

## Configuration

All parameters are configurable via environment variables or `.env` file:

| Variable | Default | Description |
|----------|---------|-------------|
| `NVIDIA_API_KEY` | (empty) | API key for LLM-assisted refactoring |
| `LLM_MODEL` | `qwen/qwen2.5-coder-32b-instruct` | LLM model identifier |
| `LLM_BASE_URL` | `https://integrate.api.nvidia.com/v1` | LLM API endpoint |
| `BENCHMARK_WARMUP` | `3` | Warm-up iterations before measurement |
| `BENCHMARK_RUNS` | `10` | Number of measurement runs |
| `BENCHMARK_TIMEOUT` | `60` | Timeout per benchmark (seconds) |
| `LOG_LEVEL` | `INFO` | Logging verbosity |

---

## Running Tests

```bash
pytest tests/ -v
```

---

## Limitations

- Energy/CO2 values are **software-level estimates** (CodeCarbon), not hardware measurements
- Validation depends on the completeness of available tests
- Currently supports **Python only**
- LLM-assisted refactoring requires internet access and API key
- The 20 AST rules detect local, single-file patterns only

---

## Citation

If you use GreenCodeMCP in your research, please cite:

```bibtex
@inproceedings{greencodemcp2026,
  title     = {GreenCodeMCP: An MCP-based Tool for Sustainable Software 
               Maintenance and Resource-Aware Refactoring},
  author    = {Oubelmouh, Youssef and Daoudi, Amir Salah Eddine and Chhieng, Pierre},
  booktitle = {Proceedings of the 42nd IEEE International Conference on 
               Software Maintenance and Evolution (ICSME), Tool Demonstration Track},
  year      = {2026}
}
```

---

## License

MIT — see [LICENSE](LICENSE).