Skip to main content
OHM-MCP

OHM-MCP

AI-Powered Python Refactoring & Code Quality Assistant

Works with GitHub Copilot, Cursor IDE, Cline, and any MCP-compatible AI assistant.

Python 3.8+ MCP AST-Based License


✨ Core Capabilities

🏗️ Architecture

  • God Object Detection
  • SOLID Violation Analysis
  • Design Pattern Suggestions
  • Dependency Injection Refactoring

🔧 Code Quality

  • AST Extract Method (100% accurate)
  • Dead Code Elimination
  • Import Refactoring
  • Symbol Renaming (project-wide)
  • Duplication Detection

📊 Type Safety

  • Type Coverage Analysis
  • Type Stub Generation
  • Auto Test Generation

Performance

  • O(n²) Pattern Detection
  • Hotspot Analysis
  • Coverage-Driven Prioritization

🤖 Automation

  • Auto-Apply with Rollback
  • Operation History
  • Quality Dashboard

🚀 Quick Start

Installation

📦 Recommended: NPM Method (Auto-installs dependencies)

No installation required! Use NPX to run the latest version automatically:

npx -y ohm-mcp@latest

This is the easiest way to get started. Just add the configuration to your AI assistant (see IDE Configuration below).

MCP Registry: mcp-name: io.github.Murugarajr/ohm-mcp

🐍 Alternative: PyPI Method (For local development)

Use this method when you need to:

  • Develop locally with the Python package
  • Use a specific Python virtual environment
  • Install from source for customization

Install from PyPI:

pip install ohm-mcp

Install from source (for development):

pip install -e .

IDE Configuration

📦 Option 1: NPX (Recommended - Auto-installs dependencies)

🔵 GitHub Copilot (VS Code) with NPX

After publishing to npm:

{
  "mcpServers": {
    "ohm-mcp": {
      "command": "npx",
      "args": ["ohm-mcp@latest"]
    }
  }
}

For local development:

{
  "mcpServers": {
    "ohm-mcp": {
      "command": "npx",
      "args": ["--package", "/path/to/ohm-mcp-npm", "ohm-mcp"]
    }
  }
}

Usage:

  • Open Copilot Chat
  • Type # and select ohm-mcp tools
  • Ask: "Analyze this file and suggest refactorings"
🟣 Cursor IDE with NPX

Global (After publishing to npm):

{
  "mcpServers": {
    "ohm-mcp": {
      "command": "npx",
      "args": ["-y", "ohm-mcp@latest"]
    }
  }
}

For local development:

{
  "mcpServers": {
    "ohm-mcp": {
      "command": "npx",
      "args": ["--package", "/path/to/ohm-mcp-npm", "ohm-mcp"]
    }
  }
}

Usage:

  • Open Cursor Chat (Cmd+L / Ctrl+L)
  • Tools are automatically available
  • Ask: "Use ohm-mcp to detect dead code"
🟢 Cline (VS Code Extension) with NPX

Global (After publishing to npm):

{
  "mcpServers": {
    "ohm-mcp": {
      "command": "npx",
      "args": ["-y", "ohm-mcp@latest"]
    }
  }
}

For local development:

{
  "mcpServers": {
    "ohm-mcp": {
      "command": "npx",
      "args": ["--package", "/path/to/ohm-mcp-npm", "ohm-mcp"]
    }
  }
}

Usage:

  • Open Cline panel
  • Tools are available in agent context
  • Ask: "Analyze type coverage and suggest improvements"
🟠 Antigravity with NPX

Global (After publishing to npm):

{
  "mcpServers": {
    "ohm-mcp": {
      "command": "npx",
      "args": ["-y", "ohm-mcp@latest"],
      "env": {
        "PYTHONUNBUFFERED": "1"
      }
    }
  }
}

Usage:

  • Tools are automatically available in Antigravity
  • Ask: "Use ohm-mcp to analyze architecture"
🔴 Roo Code with NPX

Global (After publishing to npm):

{
  "mcpServers": {
    "ohm-mcp": {
      "command": "npx",
      "args": ["-y", "ohm-mcp@latest"]
    }
  }
}

Usage:

  • Open Roo Code panel
  • Tools are available in agent context
  • Ask: "Use ohm-mcp to detect duplicates"
⚫ Codex VS Code with NPX

Configuration (config.toml):

[mcp_servers.ohm-mcp]
args = ["-y", "ohm-mcp@latest"]
command = "npx"

Usage:

  • Open Codex panel
  • Tools are automatically available
  • Ask: "Use ohm-mcp to suggest design patterns"
🟡 Kilo Code with NPX (Local/Global)

Local (For local development with virtual environment):

{
  "mcpServers": {
    "ohm-mcp": {
      "command": "/Users/username/project/venv/bin/python",
      "args": ["-m", "ohm_mcp.server"],
      "disabled": false,
      "alwaysAllow": []
    }
  }
}

Global (After publishing to npm):

{
  "mcpServers": {
    "ohm-mcp": {
      "command": "npx",
      "args": ["-y", "ohm-mcp@latest"]
    }
  }
}

Usage:

  • Open Kilo Code panel
  • Tools are available in agent context
  • Ask: "Use ohm-mcp for refactoring"

🐍 Option 2: Direct Python (Manual setup)

🔵 GitHub Copilot (VS Code) with Python

First install: pip install ohm-mcp

Then add to .vscode/mcp.json:

{
  "servers": {
    "ohm-mcp": {
      "command": "python",
      "args": ["-m", "ohm_mcp.server"]
    }
  },
  "inputs": []
}

Usage:

  • Open Copilot Chat
  • Type # and select ohm-mcp tools
  • Ask: "Analyze this file and suggest refactorings"
🟣 Cursor IDE with Python

First install: pip install ohm-mcp

Then add to Cursor's MCP settings file (.cursorrules or MCP config):

{
  "mcpServers": {
    "ohm-mcp": {
      "command": "python",
      "args": ["-m", "ohm_mcp.server"]
    }
  },
  "inputs": []
}

Example with virtual environment:

{
  "mcpServers": {
    "ohm-mcp": {
      "command": "/Users/username/projects/venv/bin/python",
      "args": ["-m", "ohm_mcp.server"]
    }
  }
}

Usage:

  • Open Cursor Chat (Cmd+L / Ctrl+L)
  • Tools are automatically available
  • Ask: "Use ohm-mcp to detect dead code"
🟢 Cline (VS Code Extension) with Python

First install: pip install ohm-mcp

Then add to Cline's MCP settings:

{
  "mcpServers": {
    "ohm-mcp": {
      "command": "python",
      "args": ["-m", "ohm_mcp.server"]
    }
  }
}

Example with virtual environment:

{
  "mcpServers": {
    "ohm-mcp": {
      "command": "/Users/username/projects/venv/bin/python",
      "args": ["-m", "ohm_mcp.server"]
    }
  }
}

Note: Cline requires absolute paths for both command and cwd.

Usage:

  • Open Cline panel
  • Tools are available in agent context
  • Ask: "Analyze type coverage and suggest improvements"
🔧 Other MCP-Compatible Clients

Any MCP-compatible client can use this server. General configuration:

{
  "mcpServers": {
    "ohm-mcp": {
      "command": "<python-interpreter-path>",
      "args": ["<path-to-mcp_server.py>"],
      "cwd": "<project-directory>"
    }
  }
}

Finding your Python path:

# Unix/Mac
which python
# or
which python3

# Windows
where python

💡 Quick Usage Examples

Once configured, simply reference tools in your AI assistant chat using the format: use #ohm-mcp.tool_name on the current file or @file_name.py

🗑️ Find Dead Code

Use #ohm-mcp.detect_dead_code on @utils.py

This will detect:

  • ✅ Unused imports (import statements never referenced)
  • ✅ Unused variables (assigned but never read)
  • ✅ Unreachable code (after return/raise/break/continue)
  • ✅ Unused functions (defined but never called)
  • ✅ Shadowed variables (inner scope hides outer scope variable)

📋 Code Duplication Detection

Use #ohm-mcp.detect_code_duplicates to find duplicates in /path/to/project

Finds:

  • ✅ Exact duplicates (100% identical code blocks)
  • ✅ Near duplicates (90%+ similarity)
  • ✅ Duplicate functions (same structure, different names)
  • ✅ Provides refactoring suggestions to eliminate duplication

🏗️ Architecture Analysis

Analyze architecture of @my_module.py using #ohm-mcp.analyze_architecture

Detects:

  • ✅ God Objects (classes doing too much)
  • ✅ SOLID principle violations
  • ✅ Circular dependencies
  • ✅ High coupling issues

✂️ Extract Method Refactoring

Use #ohm-mcp.extract_method_ast to extract lines 45-60 from @handler.py into a new function called "process_request"

Automatically:

  • ✅ Detects required parameters
  • ✅ Identifies return values
  • ✅ Generates refactored code
  • ✅ Creates unified diff patch

🔄 Safe Symbol Renaming

Use #ohm-mcp.rename_symbol to rename "old_function_name" to "new_function_name" in /path/to/project

Features:

  • ✅ AST-based (100% accurate)
  • ✅ Detects naming conflicts
  • ✅ Shows all occurrences before applying
  • ✅ Updates docstrings and comments

📊 Type Coverage Analysis

Analyze type hints in @module.py using #ohm-mcp.analyze_type_hints

Provides:

  • ✅ Coverage percentage and grade
  • ✅ Functions missing type hints
  • ✅ Suggested type annotations
  • ✅ Migration plan with priorities

⚡ Performance Optimization

Use #ohm-mcp.analyze_performance on @slow_module.py

Detects:

  • ✅ Nested loops (O(n²) complexity)
  • ✅ Quadratic list operations
  • ✅ Repeated function calls (missing caching)
  • ✅ Mutable default arguments
  • ✅ Inefficient string concatenation

🧪 Auto-Generate Tests

Generate tests for @calculator.py using #ohm-mcp.generate_characterization_tests

Creates:

  • ✅ Happy path test cases
  • ✅ Edge cases (None, zero, negative, empty)
  • ✅ Ready-to-run pytest code
  • ✅ Preserves current behavior before refactoring

🎨 Design Pattern Suggestions

Suggest design patterns for @legacy_code.py using #ohm-mcp.suggest_design_patterns

Recommends:

  • ✅ Strategy pattern for long if/elif chains
  • ✅ Factory pattern for repetitive object creation
  • ✅ Observer pattern for callback hell
  • ✅ Decorator pattern for cross-cutting concerns

🔧 Import Refactoring

Use #ohm-mcp.refactor_imports to update all files in /path/to/project from "old.module" to "new.module"

Handles:

  • ✅ Direct imports (import old.module)
  • ✅ From imports (from old.module import X)
  • ✅ Submodule imports
  • ✅ Import aliases

🎯 Key Tools (30 Total)

📋 General Analysis & Planning (4 tools)
Tool Purpose Output
analyze_codebase Comprehensive code analysis Issues + refactoring plan
propose_function_refactor Function-level refactor planning Detailed refactor proposal
explain_refactoring Explain refactoring patterns Educational guidance
create_refactor_patch Generate unified diff patches Patch file
🏗️ Architecture & Design (4 tools)
Tool Purpose Output
analyze_architecture Detect God Objects, SOLID violations Detailed issue report
suggest_design_patterns Recommend patterns (Strategy, Factory, Observer) Pattern suggestions + examples
analyze_tight_coupling Find coupling issues DI recommendations
suggest_di_refactor Generate DI code Before/after refactor
🔧 Code Quality & Refactoring (10 tools)
Tool Purpose Key Feature
extract_method_ast Extract code into function 100% AST-based accuracy
suggest_extractable_methods Find extractable blocks Cohesion scoring
detect_dead_code Find unused code 5 types of dead code
refactor_imports Update imports project-wide Safe module renaming
refactor_single_file_imports Refactor imports in one file Single file focus
analyze_wildcard_imports Find wildcard imports Explicit replacements
rename_symbol Rename across codebase Conflict detection
detect_code_duplicates Find DRY violations Exact + near duplicates
extract_function_code Extract single function code Code extraction utility
apply_function_refactor Apply function-level refactor Direct code modification

Example - Extract Method:

# Input: Lines 45-60
result = extract_method_ast(code, 45, 60, "calculate_total")

# Output: Refactored code + patch + auto-detected params/returns
📊 Type Safety & Testing (5 tools)
Tool Purpose Benefit
analyze_type_hints Check type coverage Migration plan
generate_type_stub Create .pyi files Gradual typing
generate_characterization_tests Auto-generate tests Safe refactoring
generate_test_for_function Single function tests Targeted testing
suggest_tests Suggest test strategies Test planning
⚡ Performance & Prioritization (2 tools)
Tool Purpose Detects
analyze_performance Find bottlenecks Nested loops, mutable defaults, O(n²)
prioritize_by_coverage Risk-based prioritization High-risk uncovered code
🤖 Automated Execution & History (4 tools)
graph LR
    A[apply_refactoring] --> B{Dry Run?}
    B -->|Yes| C[Show Preview]
    B -->|No| D[Create Backup]
    D --> E[Apply Changes]
    E --> F{Run Tests}
    F -->|Pass| G[Success]
    F -->|Fail| H[Auto Rollback]
    H --> I[rollback_refactoring]
Tool Purpose
apply_refactoring Auto-apply refactoring with safety checks
rollback_refactoring Rollback previous refactoring
show_refactoring_history View refactoring audit trail
cleanup_old_backups Clean up old backup files

Features:

  • ✅ Automatic backup before changes
  • ✅ Test execution validation
  • ✅ Auto-rollback on failure
  • ✅ Full audit trail with history
  • ✅ Automatic backup cleanup
📈 Metrics & Reporting (1 tool)

generate_quality_report - Comprehensive dashboard in HTML/Markdown/JSON

Output Preview:

📊 Health Score: 85/100 (Good)
📁 Files: 47 | Lines: 12,450 | Tech Debt: 23 pts

📊 Type Coverage: 67%
🗑️ Dead Code: 8 imports, 12 variables, 3 functions
⚡ Performance: 4 nested loops, 2 mutable defaults
📋 Duplication: 3 exact, 5 near-duplicates

Visual Dashboard:

  • 🎨 Circular health gauge
  • 📊 Color-coded metrics (🟢🟡🔴)
  • 📈 Trend tracking ready
  • 🔗 CI/CD integration (JSON export)

💡 Common Workflows

1️⃣ Safe Refactoring

generate_characterization_tests  pytest  extract_method_ast  pytest

2️⃣ Eliminate Duplication

detect_code_duplicates  review suggestions  extract_method_ast

3️⃣ Type Migration

analyze_type_hints  follow migration plan  generate_type_stub

4️⃣ Performance Optimization

analyze_performance  prioritize_by_coverage  apply fixes

5️⃣ Module Refactoring

refactor_imports(old="myapp.old", new="myapp.new")  review patches

6️⃣ Symbol Renaming

rename_symbol(old="calc", new="calculate", preview_only=True)  apply

7️⃣ Quality Tracking

generate_quality_report(format="html")  open dashboard  track trends

🎨 Visual Examples

Quality Dashboard Preview

┌─────────────────────────────────────────────┐
│  🔍 Code Quality Dashboard                  │
├─────────────────────────────────────────────┤
│                                             │
│       ╭─────────╮     📁 Overview           │
│       │   85    │     Files: 47             │
│       │  /100   │     Lines: 12,450         │
│       ╰─────────╯     Tech Debt: 23         │
│     Health Score                            │
│                                             │
├─────────────────────────────────────────────┤
│  📊 Type Coverage       ⚡ Performance       │
│  ████████░░ 67%         🔴 4 nested loops   │
│  120/180 typed          🟡 2 mutable args   │
├─────────────────────────────────────────────┤
│  🗑️ Dead Code           📋 Duplication      │
│  8 imports              3 exact             │
│  12 variables           5 near              │
│  3 functions                                │
└─────────────────────────────────────────────┘

Symbol Rename Preview

# Before
- def calc(x, y):
-     return x + y
- result = calc(5, 3)

# After
+ def calculate_sum(x, y):
+     return x + y
+ result = calculate_sum(5, 3)

✅ 1 function renamed
✅ 3 call sites updated
✅ 0 conflicts detected

🧠 Design Principles

Principle Implementation
🧪 Test-First Auto-generate characterization tests before refactoring
↩️ Reversible Every change = backup + rollback capability
🎯 AST-Driven 100% accurate (no regex)
📊 Risk-Aware Coverage + complexity = prioritization
🏛️ SOLID Detect violations + concrete fixes
🚫 No Blindness Analyze → Plan → Validate

🔌 IDE Compatibility

🤖 Any MCP Client
✅ Standard Protocol
✅ Easy Setup
✅ Works with all MCP-compatible AI assistants

📊 Comparison

Feature OHM MCP Traditional Tools
Accuracy 100% AST ~70% Regex
Safety Auto backup/rollback Manual
Testing Auto-generates Manual
Automation Full Suggestions only
Dashboard HTML/JSON/MD Text logs
IDE Support Copilot/Cursor/Cline Limited

🎯 Use Cases

👨‍💻 Developers
• Refactor legacy code safely
• Find dead code
• Optimize performance
👥 Teams
• Track tech debt
• Enforce standards
• Design patterns
🚀 CI/CD
• Quality gates
• Trend tracking
• Block bad PRs

📈 Metrics

✅ 30 MCP Tools
✅ 40+ Static Checks
✅ 100% AST Accuracy
✅ Zero Regex Patterns
✅ Automated Execution with Rollback
✅ Beautiful Dashboards (HTML/JSON/MD)
✅ Universal MCP Compatibility
✅ Safe Refactoring with Auto-Backup

🛠️ Troubleshooting

MCP Connection Issues
  1. Verify Python path:

    which python  # Unix/Mac
    where python  # Windows
    
  2. Test MCP server directly:

    python -m ohm_mcp.server
    
  3. Check logs:

    • VS Code: Check Output panel
    • Cursor: Check Cursor logs
    • Cline: Check Cline settings panel
  4. Common issues:

    • ❌ Relative paths in command → Use absolute paths
    • ❌ Missing virtual environment → Activate venv first
    • ❌ Wrong cwd for Cline → Must be absolute path

🤝 Contributing

Run before submitting:

./static_analyser.sh  # Runs ruff, mypy, pylint, flake8
pytest                 # All tests must pass

🙏 Credits

Built with Model Context Protocol • Python AST • Compatible with GitHub Copilot, Cursor IDE, Cline


Made with ❤️ for better code quality

Star this repo if it helps you write cleaner code!

Documentation

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ohm_mcp-1.0.1.tar.gz (46.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ohm_mcp-1.0.1-py3-none-any.whl (18.5 kB view details)

Uploaded Python 3

File details

Details for the file ohm_mcp-1.0.1.tar.gz.

File metadata

  • Download URL: ohm_mcp-1.0.1.tar.gz
  • Upload date:
  • Size: 46.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.11

File hashes

Hashes for ohm_mcp-1.0.1.tar.gz
Algorithm Hash digest
SHA256 770cf6533a22388af7319653016d37e3622aec0d0087e4baf99fabc73d243c3c
MD5 e8eee7707d987c2104e347280cffe7d9
BLAKE2b-256 822622bcc1036280c0278841a941a65b58584c4d9241854f2e20eff81625d791

See more details on using hashes here.

File details

Details for the file ohm_mcp-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: ohm_mcp-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 18.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.11

File hashes

Hashes for ohm_mcp-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 8519987f62fd64af71833b90d221fe03116a7939197f85707f5114da1106a10f
MD5 9100c22c62339b210873b2924a0f3c84
BLAKE2b-256 f59828050f2193a4755199493b3f2c837f4ec360e3035938c07e834c79d3d63b

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

1.0.1 This release

2 files

1.0.0

2 files

0.1.8

2 files

0.1.7

2 files

0.1.6

2 files

0.1.5

2 files

0.1.4

2 files

0.1.3

2 files

0.1.2

2 files

0.1.1

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page