GreenCodeMCP

GreenCodeMCP

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.

Category
Visit Server

README

GreenCodeMCP

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.

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
E2B

E2B

Using MCP to run code via e2b.

Official
Featured
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured