ohm-mcp logo
OHM-MCP AST-first refactoring server for Python
Documentation

OHM-MCP Refactor – Full docs

AST‑driven MCP server for Python refactoring, architecture analysis, type safety, performance, and automated execution.

Overview

OHM MCP Refactor (ohm-mcp) is an AI‑powered Python refactoring and code‑quality assistant that exposes 30+ AST‑driven tools through the Model Context Protocol.

It plugs into GitHub Copilot Chat, Cursor IDE, Cline, Antigravity, Roo Code, Codex, Kilo Code, and any other MCP‑compatible assistant, so you can drive deep refactors directly from chat.

Core capabilities

At a high level, OHM MCP Refactor focuses on five pillars.

  • Architecture: God Object detection, SOLID violation analysis, design pattern suggestions, and dependency‑injection refactoring.
  • Code quality: AST extract method, dead‑code elimination, import refactoring, symbol renaming, and duplication detection.
  • Type safety: Type coverage analysis, type stub generation, and auto test generation.
  • Performance: O(n²) pattern detection, hotspot analysis, and coverage‑driven prioritization.
  • Automation: Auto‑apply with rollback, operation history, and a quality dashboard with HTML/JSON/Markdown outputs.

Quick start

Installation

You have two main installation routes: NPX (recommended) and PyPI (Python package).

Recommended: NPM / NPX (auto‑installs dependencies)

No local installation needed; NPX pulls the latest version for you.

npx -y ohm-mcp@latest

Use this in your MCP config as shown in the IDE configuration examples below.

Alternative: PyPI (for local development / customization)

Use this path if you want to hack on the server locally or pin a specific version.

# From PyPI
pip install ohm-mcp

# From source (editable)
pip install -e .

Once installed, the MCP server entry point is:

python -m ohm_mcp.server

or via a console script configured as:

[project.scripts]
ohm-mcp = "ohm_mcp.server:main"

IDE configuration

The server works with any MCP client; below are ready‑to‑paste examples grouped by NPX (recommended) and Direct Python.

Option 1: NPX (recommended)

GitHub Copilot Chat (VS Code)

After publishing to npm:

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

For local development with a local npm package:

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

Cursor IDE

Global (after publishing to npm):

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

Local development:

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

Cline (VS Code extension) with NPX

Global:

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

Local development is similar, using --package and an absolute path; Cline requires absolute command and cwd.

Antigravity with NPX

Global configuration (note PYTHONUNBUFFERED):

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

Roo Code with NPX

Global:

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

Codex VS Code with NPX

config.toml:

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

Kilo Code

Local with Python virtualenv:

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

Global via NPX:

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

Note: External users always run the MCP server locally (Python or NPX); ohm-mcp.dev is docs + landing only, not a network endpoint.

Option 2: Direct Python

GitHub Copilot (VS Code) with Python

After pip install ohm-mcp:

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

Cursor IDE with Python

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

With virtualenv:

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

Cline (VS Code extension) with Python

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

Cline needs absolute paths for both command and cwd.

Generic MCP client

Template:

{
  "mcpServers": {
    "ohm-mcp": {
      "command": "/abs/path/to/python",
      "args": ["-m", "ohm_mcp.server"],
      "cwd": "/abs/path/to/project"
    }
  }
}

To discover Python path:

# Unix / macOS
which python
# or
which python3

# Windows
where python

Quick usage examples

Once configured, tools are called from chat using: Use #ohm-mcp.tool_name on @file.py.

Find dead code

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

Detects unused imports, unused variables, unreachable code, unused functions, and shadowed variables.

Code duplication detection

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

Finds exact duplicates, near duplicates, duplicate functions, and suggests DRY refactors.

Architecture analysis

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

Reports God Objects, SOLID violations, circular dependencies, and high coupling.

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 finds parameters, return values, and produces a unified diff patch.

Safe symbol renaming

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

Performs AST‑based renames with conflict detection and updates docstrings/comments.

Type coverage analysis

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

Returns coverage %, missing annotations, suggested types, and a migration plan.

Performance optimization

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

Detects nested loops, quadratic list operations, repeated calls needing caching, mutable defaults, and inefficient string concatenation.

Auto‑generate tests

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

Produces pytest tests covering happy paths and edge cases to lock in current behavior.

Design pattern suggestions

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

Recommends Strategy, Factory, Observer, Decorator, and more, with examples.

Import refactoring

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

Safely updates direct, from, submodule, and aliased imports.

Tool catalog

High‑level categories and goals.

Category Tools (examples) Primary goal
General analysis analyze_codebase, propose_function_refactor, explain_refactoring, create_refactor_patch Global and function‑level planning
Architecture & design analyze_architecture, suggest_design_patterns, analyze_tight_coupling, suggest_di_refactor SOLID and design‑pattern guidance
Code quality extract_method_ast, suggest_extractable_methods, detect_dead_code, refactor_imports, rename_symbol, detect_code_duplicates, extract_function_code, apply_function_refactor Safer refactors and DRY code
Type & tests analyze_type_hints, generate_type_stub, generate_characterization_tests, generate_test_for_function, suggest_tests Type‑safe and well‑tested code
Performance analyze_performance, prioritize_by_coverage Hotspots and risk‑based prioritization
Automation & history apply_refactoring, rollback_refactoring, show_refactoring_history, cleanup_old_backups Safe automation and audit trail
Metrics & reporting generate_quality_report Dashboards and CI‑friendly metrics

Common workflows

These workflows chain tools into realistic refactoring sequences.

1. Safe refactoring

generate_characterization_tests → pytest → extract_method_ast → pytest

Generate tests, refactor via AST, and re‑run tests to validate behavior.

2. Eliminate duplication

detect_code_duplicates → review suggestions → extract_method_ast

Find duplicate blocks and extract shared functions.

3. Type migration

analyze_type_hints → follow migration plan → generate_type_stub

Plan and apply gradual typing with .pyi stubs.

4. Performance optimization

analyze_performance → prioritize_by_coverage → apply fixes

Focus on hotspots that matter most for untested or complex code.

5. Module refactoring

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

Safely move modules and update imports.

6. Symbol renaming

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

Preview and apply project‑wide renames with AST‑based accuracy.

7. Quality tracking

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

Monitor health score, debt, type coverage, and duplication over time.

Metrics & reporting

The generate_quality_report tool provides a consolidated view of code health.

📊 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

It supports HTML, Markdown, and JSON output formats, making it suitable for dashboards, documentation, and CI/CD quality gates.

The JSON format is timestamped for historical trend tracking and can be parsed by CI pipelines to enforce a minimum health score or maximum debt threshold.

Design principles

OHM MCP Refactor applies a consistent set of principles across all tools.

Principle Implementation example
Test‑first Auto‑generate characterization tests before risky refactors
Reversible Every change goes through backup + rollback
AST‑driven No regex; all analysis and edits use the Python AST
Risk‑aware Coverage and complexity drive prioritization
SOLID‑focused Detects SOLID violations and suggests DI, patterns, and splits
Explainable explain_refactoring tool explains what and why

IDE compatibility

Any MCP client that supports the standard protocol can use this server.

All clients use the same two patterns: command: "npx" + args or command: "python" -m ohm_mcp.server.

Use cases

Audience How OHM MCP helps
Developers Safely refactor legacy code, remove dead code, and tune performance
Teams Track technical debt, enforce architecture and type‑safety standards
CI/CD Add quality gates, block risky PRs, and monitor quality trends

Troubleshooting

MCP connection issues

Verify Python path:

# Unix / macOS
which python
# or
which python3

# Windows
where python

Test MCP server directly:

python -m ohm_mcp.server

Common problems include using relative paths for command, missing virtualenv activation, and wrong cwd in certain clients such as Cline.

NPX issues

Ensure npx -y ohm-mcp@latest works in a terminal before wiring it into your MCP config.

If using a local npm package, prefer --package /abs/path/to/ohm-mcp-npm ohm-mcp with absolute paths.

Long‑running analysis

For very large repositories, scope tools like detect_code_duplicates or generate_quality_report to specific folders or modules to avoid timeouts.

Contributing

Before opening a PR, run the static analyzers and tests:

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

Follow the existing code‑quality standards and keep new tools AST‑driven and reversible (backups + rollback).

Glossary

  • MCP server: A tool server speaking the Model Context Protocol, callable from AI assistants like Copilot.
  • Tool: A callable operation (for example detect_dead_code) exposed by the MCP server.
  • Patch: A unified diff used to apply refactors safely (for example create_refactor_patch, apply_refactoring).
  • Health score: High‑level 0–100 quality score computed by generate_quality_report.
  • Technical debt points: Numeric summary of issues used for trend tracking and CI gates.
  • Main project README: https://github.com/Murugarajr/ohm-mcp
  • Landing page: https://www.ohm-mcp.dev
  • Model Context Protocol: https://modelcontextprotocol.io