io.github.Murugarajr/ohm-mcp

编码与调试

by murugarajr

基于 AST 的 Python refactoring MCP server,支持安全的自动重构与回滚。

什么是 io.github.Murugarajr/ohm-mcp

基于 AST 的 Python refactoring MCP server,支持安全的自动重构与回滚。

README

<div align="center"> <img src="https://raw.githubusercontent.com/murugarajr/ohm-mcp/main/image/ohm-mcp.png" alt="OHM-MCP" width="300">

OHM-MCP

AI-Powered Python Refactoring & Code Quality Assistant

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

MCP Registry Python 3.8+ MCP AST-Based License

</div>

✨ Core Capabilities

<table> <tr> <td width="50%">

🏗️ 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
</td> <td width="50%">

📊 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
</td> </tr> </table>

🚀 Quick Start

Installation

📦 Recommended: NPM Method (Auto-installs dependencies)

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

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

bash
pip install ohm-mcp

Install from source (for development):

bash
pip install -e .

IDE Configuration

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

<details> <summary><b>🔵 GitHub Copilot (VS Code) with NPX</b></summary>

After publishing to npm:

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

For local development:

json
{
  "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"
</details> <details> <summary><b>🟣 Cursor IDE with NPX</b></summary>

Global (After publishing to npm):

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

For local development:

json
{
  "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"
</details> <details> <summary><b>🟢 Cline (VS Code Extension) with NPX</b></summary>

Global (After publishing to npm):

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

For local development:

json
{
  "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"
</details> <details> <summary><b>🟠 Antigravity with NPX</b></summary>

Global (After publishing to npm):

json
{
  "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"
</details> <details> <summary><b>🔴 Roo Code with NPX</b></summary>

Global (After publishing to npm):

json
{
  "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"
</details> <details> <summary><b>⚫ Codex VS Code with NPX</b></summary>

Configuration (config.toml):

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"
</details> <details> <summary><b>🟡 Kilo Code with NPX (Local/Global)</b></summary>

Local (For local development with virtual environment):

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

Global (After publishing to npm):

json
{
  "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"
</details>

🐍 Option 2: Direct Python (Manual setup)

<details> <summary><b>🔵 GitHub Copilot (VS Code) with Python</b></summary>

First install: pip install ohm-mcp

Then add to .vscode/mcp.json:

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"
</details> <details> <summary><b>🟣 Cursor IDE with Python</b></summary>

First install: pip install ohm-mcp

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

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

Example with virtual environment:

json
{
  "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"
</details> <details> <summary><b>🟢 Cline (VS Code Extension) with Python</b></summary>

First install: pip install ohm-mcp

Then add to Cline's MCP settings:

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

Example with virtual environment:

json
{
  "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"
</details> <details> <summary><b>🔧 Other MCP-Compatible Clients</b></summary>

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

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

Finding your Python path:

bash
# Unix/Mac
which python
# or
which python3

# Windows
where python
</details>

💡 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

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

code
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

code
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

code
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

code
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

code
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

code
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

code
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

code
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

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

<details> <summary><b>📋 General Analysis & Planning (4 tools)</b></summary>
ToolPurposeOutput
analyze_codebaseComprehensive code analysisIssues + refactoring plan
propose_function_refactorFunction-level refactor planningDetailed refactor proposal
explain_refactoringExplain refactoring patternsEducational guidance
create_refactor_patchGenerate unified diff patchesPatch file
</details> <details> <summary><b>🏗️ Architecture & Design (4 tools)</b></summary>
ToolPurposeOutput
analyze_architectureDetect God Objects, SOLID violationsDetailed issue report
suggest_design_patternsRecommend patterns (Strategy, Factory, Observer)Pattern suggestions + examples
analyze_tight_couplingFind coupling issuesDI recommendations
suggest_di_refactorGenerate DI codeBefore/after refactor
</details> <details> <summary><b>🔧 Code Quality & Refactoring (10 tools)</b></summary>
ToolPurposeKey Feature
extract_method_astExtract code into function100% AST-based accuracy
suggest_extractable_methodsFind extractable blocksCohesion scoring
detect_dead_codeFind unused code5 types of dead code
refactor_importsUpdate imports project-wideSafe module renaming
refactor_single_file_importsRefactor imports in one fileSingle file focus
analyze_wildcard_importsFind wildcard importsExplicit replacements
rename_symbolRename across codebaseConflict detection
detect_code_duplicatesFind DRY violationsExact + near duplicates
extract_function_codeExtract single function codeCode extraction utility
apply_function_refactorApply function-level refactorDirect code modification

Example - Extract Method:

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

# Output: Refactored code + patch + auto-detected params/returns
</details> <details> <summary><b>📊 Type Safety & Testing (5 tools)</b></summary>
ToolPurposeBenefit
analyze_type_hintsCheck type coverageMigration plan
generate_type_stubCreate .pyi filesGradual typing
generate_characterization_testsAuto-generate testsSafe refactoring
generate_test_for_functionSingle function testsTargeted testing
suggest_testsSuggest test strategiesTest planning
</details> <details> <summary><b>⚡ Performance & Prioritization (2 tools)</b></summary>
ToolPurposeDetects
analyze_performanceFind bottlenecksNested loops, mutable defaults, O(n²)
prioritize_by_coverageRisk-based prioritizationHigh-risk uncovered code
</details> <details> <summary><b>🤖 Automated Execution & History (4 tools)</b></summary>
mermaid
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]
ToolPurpose
apply_refactoringAuto-apply refactoring with safety checks
rollback_refactoringRollback previous refactoring
show_refactoring_historyView refactoring audit trail
cleanup_old_backupsClean up old backup files

Features:

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

generate_quality_report - Comprehensive dashboard in HTML/Markdown/JSON

Output Preview:

code
📊 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)
</details>

💡 Common Workflows

1️⃣ Safe Refactoring

bash
generate_characterization_tests → pytest → extract_method_ast → pytest

2️⃣ Eliminate Duplication

bash
detect_code_duplicates → review suggestions → extract_method_ast

3️⃣ Type Migration

bash
analyze_type_hints → follow migration plan → generate_type_stub

4️⃣ Performance Optimization

bash
analyze_performance → prioritize_by_coverage → apply fixes

5️⃣ Module Refactoring

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

6️⃣ Symbol Renaming

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

7️⃣ Quality Tracking

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

🎨 Visual Examples

Quality Dashboard Preview

code
┌─────────────────────────────────────────────┐
│  🔍 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

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

PrincipleImplementation
🧪 Test-FirstAuto-generate characterization tests before refactoring
↩️ ReversibleEvery change = backup + rollback capability
🎯 AST-Driven100% accurate (no regex)
📊 Risk-AwareCoverage + complexity = prioritization
🏛️ SOLIDDetect violations + concrete fixes
🚫 No BlindnessAnalyze → Plan → Validate

🔌 IDE Compatibility

<table> <tr> <td align="center" width="100%"> <b>🤖 Any MCP Client</b><br> ✅ Standard Protocol<br> ✅ Easy Setup<br> ✅ Works with all MCP-compatible AI assistants </td> </tr> </table>

📊 Comparison

FeatureOHM MCPTraditional Tools
Accuracy100% AST~70% Regex
SafetyAuto backup/rollbackManual
TestingAuto-generatesManual
AutomationFullSuggestions only
DashboardHTML/JSON/MDText logs
IDE SupportCopilot/Cursor/ClineLimited

🎯 Use Cases

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

📈 Metrics

code
✅ 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

<details> <summary><b>MCP Connection Issues</b></summary>
  1. Verify Python path:

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

    bash
    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
</details>

🤝 Contributing

Run before submitting:

bash
./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


<div align="center">

Made with ❤️ for better code quality

Star this repo if it helps you write cleaner code!

Documentation

</div>

常见问题

io.github.Murugarajr/ohm-mcp 是什么?

基于 AST 的 Python refactoring MCP server,支持安全的自动重构与回滚。

相关 Skills

网页构建器

by anthropics

Universal
热门

面向复杂 claude.ai HTML artifact 开发,快速初始化 React + Tailwind CSS + shadcn/ui 项目并打包为单文件 HTML,适合需要状态管理、路由或多组件交互的页面。

在 claude.ai 里做复杂网页 Artifact 很省心,多组件、状态和路由都能顺手搭起来,React、Tailwind 与 shadcn/ui 组合效率高、成品也更精致。

编码与调试
未扫描114.1k

前端设计

by anthropics

Universal
热门

面向组件、页面、海报和 Web 应用开发,按鲜明视觉方向生成可直接落地的前端代码与高质感 UI,适合做 landing page、Dashboard 或美化现有界面,避开千篇一律的 AI 审美。

想把页面做得既能上线又有设计感,就用前端设计:组件到整站都能产出,难得的是能避开千篇一律的 AI 味。

编码与调试
未扫描114.1k

网页应用测试

by anthropics

Universal
热门

用 Playwright 为本地 Web 应用编写自动化测试,支持启动开发服务器、校验前端交互、排查 UI 异常、抓取截图与浏览器日志,适合调试动态页面和回归验证。

借助 Playwright 一站式验证本地 Web 应用前端功能,调 UI 时还能同步查看日志和截图,定位问题更快。

编码与调试
未扫描114.1k

相关 MCP Server

GitHub

编辑精选

by GitHub

热门

GitHub 是 MCP 官方参考服务器,让 Claude 直接读写你的代码仓库和 Issues。

这个参考服务器解决了开发者想让 AI 安全访问 GitHub 数据的问题,适合需要自动化代码审查或 Issue 管理的团队。但注意它只是参考实现,生产环境得自己加固安全。

编码与调试
83.4k

by Context7

热门

Context7 是实时拉取最新文档和代码示例的智能助手,让你告别过时资料。

它能解决开发者查找文档时信息滞后的问题,特别适合快速上手新库或跟进更新。不过,依赖外部源可能导致偶尔的数据延迟,建议结合官方文档使用。

编码与调试
52.2k

by tldraw

热门

tldraw 是让 AI 助手直接在无限画布上绘图和协作的 MCP 服务器。

这解决了 AI 只能输出文本、无法视觉化协作的痛点——想象让 Claude 帮你画流程图或白板讨论。最适合需要快速原型设计或头脑风暴的开发者。不过,目前它只是个基础连接器,你得自己搭建画布应用才能发挥全部潜力。

编码与调试
46.3k

评论