Initial commit

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
dinlo
2026-05-31 18:45:22 +08:00
commit 017135fe0e
13 changed files with 2008 additions and 0 deletions
+546
View File
@@ -0,0 +1,546 @@
# MCP Python Project Manager Server
A Model Context Protocol (MCP) server for managing and debugging Python projects on Windows 11.
## 🚀 Features
### Project Management
- **Project Info**: Get comprehensive information about Python projects including structure, dependencies, and environment
- **File Operations**: List, read, and analyze project files with filtering options
- **Directory Tree**: Visualize project structure with configurable depth
### Execution & Debugging
- **Run Scripts**: Execute Python scripts with custom arguments and environment variables
- **Debug Info**: Get information about running Python processes and scripts
- **Environment Details**: Inspect Python interpreter, packages, and sys.path
### Package Management
- **Install Packages**: Install packages via pip with requirements file support
- **List Packages**: View installed packages in JSON or text format
- **Dependency Analysis**: Analyze requirements files and detect potential issues
### Code Quality
- **Linting**: Run flake8, pylint, and black checks on your code
- **Formatting**: Auto-format code using black or autopep8
- **Testing**: Execute tests with pytest or unittest framework
### Environment Management
- **Virtual Environments**: Create and manage Python virtual environments
- **Environment Detection**: Auto-detect and use project venvs
- **Python Version Support**: Configure specific Python versions
### File Watching
- **Change Notifications**: Watch files for modifications (configurable patterns)
- **Pattern Filtering**: Include/exclude files by glob patterns
## 📦 Installation
### Prerequisites
**Option A: Using uv (Recommended ⚡)**
- [`uv`](https://github.com/astral-sh/uv) installed on Windows 11
- Install uv: `winget install astral-sh.uv` or `pip install uv`
**Option B: Traditional Python**
- Python 3.10+ installed on Windows 11
- pip package manager
### Setup with uv (Recommended)
```cmd
# 1. Navigate to project directory
cd C:\Users\dimir\proects\mcp-python
# 2. Install and run directly with uvx (no venv needed!)
uvx --from C:/Users/dimir/proects/mcp-python mcp-python-manager
```
### Setup with pip (Traditional)
```cmd
# 1. Clone or create project directory:
cd C:\Users\dimir\proects
mkdir mcp-python
cd mcp-python
# 2. Create virtual environment:
python -m venv .venv
.venv\Scripts\activate
# 3. Install dependencies:
pip install -r requirements.txt
# 4. Optional: Install development tools:
pip install py-spy safety pip-audit
```
## ⚙️ Configuration
### Environment Variables
| Variable | Description | Default |
|----------|-------------|---------|
| `MCP_PYTHON_WORKSPACE` | Root directory for projects | `C:/Users/dimir/projects` |
| `MCP_PYTHON_DEBUG` | Enable debug logging | `false` |
| `MCP_PYTHON_LOG_LEVEL` | Logging level | `INFO` |
| `MCP_PYTHON_MAX_EXEC_TIME` | Command timeout (seconds) | `300` |
### Config File (`config.py`)
Customize server behavior by editing `config.py`:
```python
from config import ServerConfig
config = ServerConfig(
workspace_root=Path("C:/Users/dimir/projects"),
venv_name=".venv",
debug_mode=True,
allowed_commands=["python", "pip", "pytest", "black", "flake8", "pylint"],
max_execution_time=600,
)
```
## 🔌 Usage
### Running the Server
#### 🚀 With uvx (Recommended)
```cmd
# Run directly without installation
uvx --from C:/Users/dimir/proects/mcp-python mcp-python-manager
# With custom workspace
uvx --from C:/Users/dimir/proects/mcp-python mcp-python-manager --workspace "C:\MyProjects"
# With debug mode
uvx --from C:/Users/dimir/proects/mcp-python mcp-python-manager --debug
# SSE transport
uvx --from C:/Users/dimir/proects/mcp-python mcp-python-manager --transport sse --port 8000
```
#### 🐍 With Python (Traditional)
**Stdio Transport (Default for MCP clients):**
```cmd
# Direct execution
python server.py
# Via MCP stdio module
python -m mcp.server.stdio server:main
```
**SSE Transport (HTTP-based clients):**
```cmd
python server.py --transport sse --host localhost --port 8000
```
**With Options:**
```cmd
python server.py --debug --workspace "C:\MyProjects"
```
### Connecting from Claude Desktop
#### ⚡ Using uvx (Recommended)
Add to your Claude Desktop config (`%APPDATA%\Claude\claude_desktop_config.json`):
```json
{
"mcpServers": {
"python-manager": {
"command": "uvx",
"args": [
"--from",
"C:/Users/dimir/proects/mcp-python",
"mcp-python-manager",
"--transport",
"stdio"
],
"env": {
"MCP_PYTHON_WORKSPACE": "C:/Users/dimir/projects",
"UV_NO_CACHE": "0",
"UV_LINK_MODE": "copy"
}
}
}
}
```
#### 🐍 Using Python (Traditional)
```json
{
"mcpServers": {
"python-manager": {
"command": "python",
"args": [
"C:/Users/dimir/proects/mcp-python/server.py"
],
"env": {
"MCP_PYTHON_WORKSPACE": "C:/Users/dimir/projects"
}
}
}
}
```
### Connecting from Cursor/VS Code
#### ⚡ Using uvx (Recommended)
```json
{
"mcp": {
"servers": {
"python-manager": {
"type": "stdio",
"command": "uvx",
"args": [
"--from",
"C:/Users/dimir/proects/mcp-python",
"mcp-python-manager",
"--transport",
"stdio"
],
"env": {
"UV_NO_CACHE": "0",
"UV_LINK_MODE": "copy"
}
}
}
}
}
```
#### 🐍 Using Python (Traditional)
```json
{
"mcp": {
"servers": {
"python-manager": {
"type": "stdio",
"command": "python",
"args": ["C:/Users/dimir/proects/mcp-python/server.py"],
"env": {
"PYTHONUNBUFFERED": "1"
}
}
}
}
}
```
## 🛠️ Available Tools
### `get_project_info`
Get comprehensive project information.
```json
{
"project_path": "C:/Users/dimir/projects/my-app"
}
```
### `run_python_script`
Execute a Python script.
```json
{
"script_path": "main.py",
"args": ["--config", "prod.yaml"],
"env": {"DEBUG": "false"},
"use_venv": true,
"cwd": "C:/Users/dimir/projects/my-app"
}
```
### `install_package`
Install Python packages.
```json
{
"packages": ["requests", "fastapi"],
"upgrade": true,
"use_venv": true
}
```
Or with requirements file:
```json
{
"requirements_file": "requirements.txt",
"use_venv": true
}
```
### `list_packages`
List installed packages.
```json
{
"project_path": "C:/Users/dimir/projects/my-app",
"format": "json"
}
```
### `run_tests`
Execute tests.
```json
{
"test_path": "tests/",
"test_framework": "pytest",
"args": ["-x", "--cov"],
"verbose": true
}
```
### `lint_code`
Run code linters.
```json
{
"file_path": "src/",
"linter": "all",
"fix": false
}
```
### `create_venv`
Create virtual environment.
```json
{
"project_path": "C:/Users/dimir/projects/new-project",
"venv_name": ".venv",
"python_version": "3.11"
}
```
### `get_debug_info`
Get debugging information.
```json
{
"script_path": "main.py",
"include_stack": true
}
```
Or by PID:
```json
{
"pid": 12345,
"include_stack": true
}
```
### `list_project_files`
List project files.
```json
{
"directory": "C:/Users/dimir/projects/my-app",
"pattern": "*.py",
"recursive": true,
"exclude_dirs": ["__pycache__", ".git"]
}
```
### `read_file`
Read file contents.
```json
{
"file_path": "main.py",
"start_line": 1,
"end_line": 50,
"encoding": "utf-8"
}
```
### `execute_command`
Execute allowed shell commands.
```json
{
"command": "python -m pytest tests/ -v",
"cwd": "C:/Users/dimir/projects/my-app",
"timeout": 120
}
```
### `get_python_env`
Get Python environment info.
```json
{
"project_path": "C:/Users/dimir/projects/my-app"
}
```
### `format_code`
Format Python code.
```json
{
"file_path": "src/",
"formatter": "black",
"check_only": false
}
```
### `analyze_dependencies`
Analyze project dependencies.
```json
{
"project_path": "C:/Users/dimir/projects/my-app",
"check_updates": false,
"check_security": false
}
```
### `watch_files`
Configure file watching.
```json
{
"directory": "C:/Users/dimir/projects/my-app/src",
"patterns": ["*.py", "*.json"],
"recursive": true
}
```
## 🔒 Security
### Allowed Commands
By default, only these commands can be executed:
- `python` - Run Python scripts
- `pip` - Package management
- `pytest` - Run tests
- `black` - Code formatting
- `flake8` - Linting
- `pylint` - Advanced linting
Modify `config.allowed_commands` to customize.
### Path Validation
All file paths are validated to prevent directory traversal attacks.
### Output Truncation
Command output is limited to `max_output_length` characters (default: 50,000).
## 🐛 Debugging
### Enable Debug Logging
```cmd
set MCP_PYTHON_DEBUG=true
set MCP_PYTHON_LOG_LEVEL=DEBUG
python server.py
```
### Log File
Configure logging to file in `config.py`:
```python
config.log_file = Path("C:/Users/dimir/proects/mcp-python/server.log")
```
### Common Issues
| Issue | Solution |
|-------|----------|
| "Command not allowed" | Add command to `config.allowed_commands` |
| "Virtual environment not found" | Create venv with `create_venv` tool or manually |
| "Timeout executing command" | Increase `max_execution_time` in config |
| "Permission denied" | Run terminal as Administrator or check file permissions |
## 🧪 Testing the Server
### Manual Test with MCP Inspector
```cmd
# Install MCP inspector
npm install -g @modelcontextprotocol/inspector
# Run server and inspector
python server.py
# In another terminal:
mcp-inspector
```
### Python Test Script
```python
import asyncio
from mcp.client.session import ClientSession
from mcp.client.stdio import stdio_client
async def test_server():
async with stdio_client(["python", "server.py"]) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# List available tools
tools = await session.list_tools()
print(f"Available tools: {[t.name for t in tools.tools]}")
# Test get_project_info
result = await session.call_tool(
"get_project_info",
{"project_path": "C:/Users/dimir/projects"}
)
print(result)
asyncio.run(test_server())
```
## 📁 Project Structure
```
mcp-python/
├── server.py # Main server entry point
├── tools.py # MCP tool implementations
├── config.py # Configuration settings
├── requirements.txt # Python dependencies
├── README.md # This file
├── .gitignore # Git ignore rules
└── logs/ # Log files (created at runtime)
```
## 🔄 Development
### Adding New Tools
1. Add tool definition in `tools.py` `_register_tools()` method
2. Implement the async method in `PythonProjectTools` class
3. Add handler case in `handle_tool_call()` method
4. Update this README with documentation
### Example Tool Addition
```python
# In _register_tools():
Tool(
name="my_new_tool",
description="What this tool does",
inputSchema={...}
)
# Implementation:
async def my_new_tool(self, arg1: str) -> ToolResult:
# Your logic here
return ToolResult(success=True, message="Done", data={...})
# Handler:
elif name == "my_new_tool":
result = await self.my_new_tool(**arguments)
```
## 📄 License
MIT License - Feel free to use and modify for your projects.
## 🤝 Contributing
1. Fork the repository
2. Create a feature branch
3. Add tests for new functionality
4. Submit a pull request
## 🔗 Resources
- [MCP Specification](https://modelcontextprotocol.io)
- [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk)
- [Windows Python Setup Guide](https://docs.python.org/3/using/windows.html)
---
**Author**: dimir
**Created**: 2026
**Platform**: Windows 11, Python 3.10+