Command Palette

Search for a command to run...

UnylyUnyly
Browse all

GreenCodeMCP

FreeNot checked

An MCP server that detects energy anti-patterns in Python code, retrieves optimization examples, suggests refactoring, validates correctness, and benchmarks res

GitHubEmbed

About

An MCP server that detects energy anti-patterns in Python code, retrieves optimization examples, suggests refactoring, validates correctness, and benchmarks resource gains, integrating with VS Code, Cursor, and Windsurf.

README

DOI

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

Setup

# 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:

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):

{
  "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):

{
  "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):

{
  "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:
    "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:

# 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

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:

@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.

from github.com/DaoudiAmir/GreenCodeMCP

Install GreenCodeMCP in Claude Desktop, Claude Code & Cursor

Recommended · one command, every IDE
unyly install greencodemcp

Installs into Claude Desktop, Claude Code, Cursor & VS Code — handles npx, uvx and build-from-source repos for you.

First time? Get the CLI: curl -fsSL https://unyly.org/install | sh

Or configure manually

Run in your terminal:

claude mcp add greencodemcp -- uvx --from git+https://github.com/DaoudiAmir/GreenCodeMCP greencode-mcp

FAQ

Is GreenCodeMCP MCP free?

Yes, GreenCodeMCP MCP is free — one-click install via Unyly at no cost.

Does GreenCodeMCP need an API key?

No, GreenCodeMCP runs without API keys or environment variables.

Is GreenCodeMCP hosted or self-hosted?

Self-hosted: the server runs locally on your machine via the install command above.

How do I install GreenCodeMCP in Claude Desktop, Claude Code or Cursor?

Open GreenCodeMCP on unyly.org, pick your client tab (Claude Desktop, Claude Code, Cursor) and press Install — the config is generated automatically, no JSON editing.

Related MCPs

Compare GreenCodeMCP with

Not sure what to pick?

Find your stack in 60 seconds

Author?

Embed badge for your README

Browse similar

All development MCPs