A Model Context Protocol (MCP) server that analyzes Python code and provides guided refactoring suggestions without automatically modifying your code.
python refactoring code-analysis mcp-server ai-assistant claude rope radon vulture jedi educational mentoring code-quality static-analysis complexity-analysis
This tool integrates with AI coding assistants (Claude, ChatGPT, Cursor, etc.) to provide intelligent refactoring guidance. Instead of making automatic code changes, it gives you precise instructions on how to improve your Python code, acting as your refactoring mentor.
For AI Coding Assistants:
- Provides structured JSON responses with refactoring opportunities
- Identifies long functions, high complexity code, and dead code
- Gives precise line numbers for extract method refactoring
- Uses professional tools for comprehensive analysis
For Developers:
- Get step-by-step refactoring instructions
- Maintain full control over code changes
- Learn refactoring patterns through guided practice
- Improve code quality systematically
| Approach | This Tool | Traditional Refactoring Tools |
|---|---|---|
| Integration | Works with any LLM/AI assistant | IDE-specific or standalone |
| Guidance | Step-by-step instructions with line numbers | Automatic changes only |
| Learning | Educational approach teaches patterns | No learning component |
| Control | Developer maintains full control | Tool makes all decisions |
This MCP server is available across the entire MCP ecosystem:
Published and Live: registry.modelcontextprotocol.io
- Server name:
io.github.slamer59/mcp-python-refactoring - Discoverable by all MCP-compatible clients
Pull Request Submitted: docker/mcp-registry #207
- Will be available as
mcp/mcp-python-refactoringon Docker Hub - Includes enhanced security: signatures, SBOM, provenance tracking
- Integrated into Docker Desktop's MCP Toolkit
Community Curated Lists:
- appcypher/awesome-mcp-servers #180 - Development Tools section
- punkpeye/awesome-mcp-servers #1321 - Code Execution section
Once all registries are live, users can discover via:
- MCP catalog - Official registry search
- Docker Desktop - MCP Toolkit integration
- Community lists - GitHub awesome lists
- Docker Hub -
mcp/mcp-python-refactoring(with enhanced security)
# Pull from Docker Hub (after registry approval)
docker run -i mcp/mcp-python-refactoring
# Or build locally
docker build -t mcp-python-refactoring .
docker run -i mcp-python-refactoringFROM python:3.13-slim
WORKDIR /app
# Install system dependencies
RUN apt-get update && apt-get install -y \
git \
&& rm -rf /var/lib/apt/lists/*
# Copy project files
COPY pyproject.toml README.md ./
COPY src/ ./src/
# Install the package
RUN pip install --no-cache-dir -e .
# Expose MCP server port (optional, for documentation)
EXPOSE 3000
# Run the MCP server
ENTRYPOINT ["python-refactor", "server"]# Install and run MCP server directly from GitHub
uvx --from git+https://github.com/slamer59/mcp-python-refactoring.git python-refactor server# Add to Claude Code MCP configuration
claude-code mcp add mcp-python-refactoring uvx --from git+https://github.com/slamer59/mcp-python-refactoring.git python-refactor serverAfter running this command, restart Claude Desktop and the Python refactoring tools will be available in your Claude conversations!
# Clone and setup for development
git clone https://github.com/slamer59/mcp-python-refactoring.git
cd mcp-python-refactoring
uv sync
# Run MCP server locally
python -m mcp_refactoring_assistant server
# Or use the entry point after installation
pip install -e .
python-refactor serverSingle Server: Both guide-only and apply-changes modes in one server
Connection Options:
- stdin/stdout:
python-refactor server(default) - Module execution:
python -m mcp_refactoring_assistant server
Comprehensive analysis with optional automatic refactoring.
Parameters:
content(required): Python file content as stringmode(optional): "guide_only" (default) or "apply_changes"file_path(optional): Path to the file for contextline_threshold(optional): Minimum lines for long functions (default: 20)
Mode: guide_only - Returns instructions only Mode: apply_changes - Returns modified code
Comprehensive security scanning and modern Python patterns analysis.
Parameters:
content(required): Python file content as stringfile_path(optional): Path to the file for contextinclude_security_scan(optional): Enable security vulnerability scanning (default: true)include_dependency_scan(optional): Enable dependency vulnerability scanning (default: true)include_modernization(optional): Enable modern Python pattern suggestions (default: true)
Features:
- Security Analysis: Detects 20+ vulnerability types (hardcoded secrets, SQL injection, weak crypto, etc.)
- Dependency Scanning: Scans project dependencies for known CVEs using pip-audit
- Modernization: Suggests modern Python patterns (f-strings, pathlib, enumerate, etc.)
- Intelligent Prioritization: Issues ranked by severity and impact
- Configurable Analysis: Enable/disable specific scanning types as needed
Extract specific functions with guide or apply mode.
Parameters:
content(required): Python file contentmode(optional): "guide_only" or "apply_changes"function_name(optional): Specific function to targetstart_line,end_line(for apply_changes): Exact extraction rangenew_function_name(for apply_changes): Name for extracted function
Fast analysis for immediate refactoring opportunities.
Parameters:
content(required): Python file content
Returns: Quick summary of long functions and parameter issues
Advanced type checking and quality analysis using pyrefly.
Parameters:
content(required): Python code content to type check
Returns: Detailed type errors, quality issues, and improvement suggestions
Returns server capabilities and available analysis tools.
Returns: List of available tools: rope, radon, vulture, jedi, libcst, pyrefly, mccabe, complexipy
Code Quality Issues Detected:
- Functions over 20 lines (extract method opportunities)
- High cyclomatic complexity (>10) using McCabe analysis
- High cognitive complexity (>15) using Complexipy analysis
- Functions with too many parameters (>5)
- Dead/unused code (consolidated suggestions) via Vulture
- Low maintainability index (<20) using Radon metrics
- Type annotation problems detected by Pyrefly
- Large files (>500 lines) with module splitting recommendations
- Files with too many imports (>20) suggesting restructuring
π Security & Modernization Features (NEW!):
- Security Vulnerability Detection: Comprehensive security scanning using Bandit
- Dependency Security Analysis: CVE detection in project dependencies with pip-audit
- Modern Python Patterns: Code modernization suggestions using Refurb
- Unified Analysis: Intelligent prioritization combining security and modernization
- Configurable Scanning: Enable/disable specific analysis types via MCP endpoint
Additional Analysis Tools:
- Performance Analysis: Bottleneck identification and optimization suggestions
- Type Hints: Missing type annotation detection
- Documentation: Docstring coverage and quality assessment
Professional Tools Used:
π§ Core Refactoring Analysis:
- Rope: Professional refactoring analysis and extract method detection
- Radon: Code complexity metrics (cyclomatic, maintainability index)
- Vulture: Dead code detection and unused import analysis
- Jedi: Semantic code analysis and variable tracking
- LibCST: Syntax tree manipulation for precise code analysis
- Pyrefly: Advanced type checking and quality analysis
- McCabe: Cyclomatic complexity measurement
- Complexipy: Advanced complexity analysis and cognitive complexity
π Security & Modernization Tools (NEW!):
- Bandit: AST-based security vulnerability scanner (20+ vulnerability types)
- pip-audit: Dependency vulnerability scanner with CVE database
- Refurb: Modern Python pattern suggestions and code modernization
π Built-in Analysis:
- File Analysis: File size analysis and module splitting recommendations
- Package Analysis: Comprehensive package structure and dependency analysis
# Launch MCP Inspector
bunx @modelcontextprotocol/inspector
# In the web interface:
# Command: python
# Args: -m mcp_refactoring_assistant server
# Working Directory: /path/to/your/projectTest Both Modes in Inspector:
Guide Mode Test:
{
"content": "def long_function():\n print('line1')\n # ... 20+ lines",
"mode": "guide_only"
}Apply Mode Test:
{
"content": "def long_function():\n print('line1')\n # ... 20+ lines",
"mode": "apply_changes"
}# Install Bun if not available
curl -fsSL https://bun.sh/install | bash
# Install MCP SDK
bun install -g @modelcontextprotocol/sdk
# Run tests
export PATH=.venv/bin:$PATH && bun run test_unified.js# Simple Python test
python test_tool.py
# Test with example file
python -m mcp_refactoring_assistant --help# Check dependencies
uv sync
# Verify MCP imports
python -c "import mcp; print('MCP available')"
# Test individual tools
python -c "
from src.mcp_refactoring_assistant.server import EnhancedRefactoringAnalyzer
analyzer = EnhancedRefactoringAnalyzer()
print('Analyzer working')
"- AI assistant calls
analyze_python_codewithguide_onlymode - Tool returns structured suggestions with precise steps
- Developer follows step-by-step instructions
- Developer learns refactoring patterns through practice
- AI assistant calls
analyze_python_codewithapply_changesmode - Tool returns modified code with applied refactorings
- Developer reviews changes and applies as needed
- Faster refactoring for experienced developers
{
"analysis_summary": {
"total_issues_found": 2,
"medium_priority": 1,
"low_priority": 1
},
"refactoring_guidance": [
{
"issue_type": "extract_function",
"location": "Function 'process_data' lines 45-78",
"description": "Long function (34 lines) with extractable blocks",
"precise_steps": [
"SELECT lines 45-52 (validation block)",
"CREATE function: validate_input(data)",
"REPLACE with: is_valid = validate_input(data)"
]
},
{
"issue_type": "dead_code",
"location": "Multiple locations (6 items)",
"description": "6 unused items found",
"precise_steps": [
"Review all unused items listed below:",
"β’ Line 11: Unused import 're'",
"β’ Line 12: Unused import 'Optional'",
"Verify each item is truly unused",
"Remove confirmed unused code"
]
}
]
}Add to your MCP configuration:
{
"servers": {
"python-refactoring": {
"command": "uvx",
"args": ["--from", "git+https://github.com/slamer59/mcp-python-refactoring.git", "python-refactor", "server"]
}
}
}Or for local installation:
{
"servers": {
"python-refactoring": {
"command": "python",
"args": ["-m", "mcp_refactoring_assistant", "server"]
}
}
}Add to claude_desktop_config.json:
{
"mcpServers": {
"python-refactoring": {
"command": "uvx",
"args": ["--from", "git+https://github.com/slamer59/mcp-python-refactoring.git", "python-refactor", "server"]
}
}
}Or for local installation:
{
"mcpServers": {
"python-refactoring": {
"command": "python",
"args": ["-m", "mcp_refactoring_assistant", "server"]
}
}
}In VSCode settings or .vscode/settings.json:
{
"cline.mcpServers": {
"python-refactoring": {
"command": "python",
"args": ["-m", "mcp_refactoring_assistant", "server"]
}
}
}Add to Cursor's MCP configuration:
{
"mcpServers": {
"python-refactoring": {
"command": "python",
"args": ["-m", "mcp_refactoring_assistant", "server"]
}
}
}In ~/.continue/config.json:
{
"mcpServers": [
{
"name": "python-refactoring",
"command": "python",
"args": ["-m", "mcp_refactoring_assistant", "server"]
}
]
}Add to Windsurf MCP configuration:
{
"servers": {
"python-refactoring": {
"command": "python",
"args": ["-m", "mcp_refactoring_assistant", "server"]
}
}
}Use with MCP bridge or direct integration:
aider --mcp-server "python -m mcp_refactoring_assistant server"In OpenHands configuration:
mcp_servers:
python-refactoring:
command: python
args: ["-m", "mcp_refactoring_assistant", "server"]Add to Roo-Code's MCP settings:
{
"mcpServers": {
"python-refactoring": {
"command": "python",
"args": ["-m", "mcp_refactoring_assistant", "server"]
}
}
}Add to ~/.codex/config.toml:
[mcp_servers.python-refactoring]
command = "python"
args = ["-m", "mcp_refactoring_assistant", "server"]For most terminal-based MCP clients:
# With uvx
client-name --mcp-server "uvx --from git+https://github.com/slamer59/mcp-python-refactoring.git python-refactor server"
# With local installation
client-name --mcp-server "python -m mcp_refactoring_assistant server"For web-based clients that support SSE connections:
- Start the server in SSE mode:
# SSE mode is not currently supported
# Use stdin/stdout mode instead
python-refactor server- Use stdin/stdout connection instead of SSE
For clients without native MCP support:
# Install mcpo
pip install mcpo
# Bridge MCP to OpenAI-compatible API
mcpo --mcp-server "python -m mcp_refactoring_assistant server" --port 8080Then configure your client to use http://localhost:8080 as API endpoint.
- Use
python -m mcp_refactoring_assistant serverfor local installations - For uvx installation, use the full uvx command instead of local paths
- Some clients may require additional configuration or have different syntax
- Always use absolute paths when specifying python executable
- Test the connection with the client's MCP debugging tools if available
- Analysis: Server analyzes Python code using multiple professional tools
- Detection: Identifies specific refactoring opportunities with metrics
- Guidance: Provides precise line numbers and step-by-step instructions
- Integration: AI assistant interprets results and guides developer
- Control: Developer maintains full control over all code changes
Users report significant improvements in code quality understanding and refactoring skills when using this tool with AI assistants. The guided approach helps developers learn refactoring patterns while maintaining control over code changes.
"Finally, a tool that teaches me refactoring instead of doing it for me"
"The precise line numbers make it easy to follow the suggestions"
"Game changer for working with legacy code"
MCP Connection Issues:
- Ensure all dependencies installed:
uv sync - Check Python path:
which python - Verify MCP import:
python -c "import mcp"
Analysis Not Working:
- Test analyzer directly:
python test_tool.py - Check file permissions
- Verify example file exists:
ls examples/
Tool Responses Empty:
- Check if code has functions to analyze (minimum complexity threshold)
- Increase line threshold for testing:
"line_threshold": 10 - Verify file syntax is valid Python
- Ensure virtual environment is activated
SSE Connection Issues:
- Verify port is not in use:
netstat -an | grep 3001 - Check firewall settings for local connections
- Ensure FastAPI and Uvicorn are installed:
uv add fastapi uvicorn
Performance Issues:
- For large codebases (>100 files), consider using file-specific analysis
- Increase timeout settings in MCP client configuration
- Use
quick_analyzefor immediate feedback on specific functions
Submit to awesome lists and community catalogs:
- MCPServers.org - Create GitHub issue
- Awesome MCP Servers - Submit PR
- Wong2's Awesome List - Submit PR
π What's New:
-
π Security Scanning: Professional-grade vulnerability detection using Bandit
- Detects 20+ security issue types (SQL injection, hardcoded secrets, weak crypto)
- Integrates seamlessly with existing refactoring analysis
-
π¦ Dependency Security: CVE scanning with pip-audit
- Scans project dependencies for known vulnerabilities
- Provides specific version upgrade recommendations
-
β‘ Code Modernization: Python pattern suggestions using Refurb
- Suggests modern Python features (f-strings, pathlib, enumerate)
- Helps upgrade legacy code to contemporary best practices
-
π― Unified Analysis: Intelligent prioritization system
- Combines security, modernization, and refactoring analysis
- Smart priority ordering by severity and impact
- Configurable scanning options via new MCP endpoint
-
β Production Ready:
- 177+ comprehensive tests (100% passing)
- Extensive error handling and edge case coverage
- Performance tested on large codebases
- Full backward compatibility maintained
π Proven Results:
- Successfully analyzed and improved itself through iterative refinement
- Reduced code complexity while adding powerful new features
- Enhanced type safety and maintainability throughout the codebase
MIT License - Free for personal and commercial use.