MCP File Edit
Realizar operaciones del sistema de archivos como leer, escribir, aplicar parches y gestionar directorios.
Documentación
MCP File Edit
Un servidor simple del Protocolo de Contexto de Modelos (MCP) que proporciona operaciones integrales del sistema de archivos, incluida la capacidad de aplicar parches a archivos y realizar análisis básico de código, con el objetivo de reducir el uso de tokens de Claude Desktop en comparación con otras herramientas similares. Construido sobre FastMCP.
Características
- 📁 Operaciones de Archivos: Leer, escribir, crear, eliminar, mover y copiar archivos
- 📂 Gestión de Directorios: Listar archivos, crear directorios, operaciones recursivas
- 🔍 Búsqueda: Buscar patrones en archivos usando expresiones regulares con control de profundidad
- 🔄 Reemplazo: Buscar y reemplazar texto en múltiples archivos
- 🔧 Parcheo: Aplicar modificaciones precisas usando parches basados en líneas, patrones o contexto
- 📍 Directorio de Proyecto: Establecer un directorio de trabajo para rutas relativas simplificadas
- 🧬 Análisis de Código: Extraer funciones, clases y estructura de archivos de código
- 🛡️ Seguridad: Protección integrada contra recorridos de ruta y operaciones seguras
- 💾 Soporte Binario: Manejar archivos de texto y binarios con codificación adecuada
- 📤 Transferencia SSH: Subir/descargar archivos y sincronización eficiente con rsync
- 📤 Subida/Descarga SSH: Transferir archivos entre sistemas de archivos locales y remotos
- 🔀 Operaciones Git: Soporte completo de git para repositorios locales y remotos
Instalación
Usando uv (recomendado)
git clone https://github.com/patrickomatik/mcp-file-edit.git
cd mcp-file-edit
uv pip install -e .
Usando pip
git clone https://github.com/patrickomatik/mcp-file-edit.git
cd mcp-file-edit
pip install -e .
Inicio Rápido
1. Configurar Claude Desktop
Agregue a su configuración de Claude Desktop (~/Library/Application Support/Claude/claude_desktop_config.json):
{
"mcpServers": {
"file-edit": {
"command": "uv",
"args": ["run", "mcp", "run", "/path/to/mcp-file-edit/server.py"]
}
}
}
O con Python directamente:
{
"mcpServers": {
"file-edit": {
"command": "/path/to/python",
"args": ["/path/to/mcp-file-edit/server.py"]
}
}
}
2. Reiniciar Claude Desktop
Después de actualizar la configuración, reinicie Claude Desktop para cargar el servidor MCP.
Guía de Uso
Directorio de Proyecto (Recomendado)
Establezca primero un directorio de proyecto para usar rutas relativas:
LLM chat session
>>> Use file-edit-mcp to set project directory to /User/fred/project
# Set project directory
set_project_directory("/path/to/your/project")
# Now use simple relative paths
read_file("src/main.py") # Reads from project/src/main.py
write_file("docs/README.md", content) # Writes to project/docs/README.md
list_files("tests") # Lists files in project/tests
Operaciones Básicas de Archivos
LLM chat session
>>> Use file-edit-mcp to read the file example.txt
# Read a file
content = read_file("example.txt")
# Write a file
write_file("output.txt", "Hello, World!")
# Delete a file
delete_file("old_file.txt")
```python
LLM chat session
>>> Use file-edit-mcp to delete the file old_file.txt
Mover/renombrar un archivo
move_file("old_name.txt", "new_name.txt")
LLM chat session
>>> Use file-edit-mcp to rename old_name to new_name
Copiar un archivo
copy_file("source.txt", "destination.txt")
```python
LLM chat session
>>> Use file-edit-mcp to set copy the file source to destination
Búsqueda y Reemplazo
Claude debería descubrir y usar estas funciones como parte de un cometido más amplio, por ejemplo, al escribir nuevo código fuente según sus especificaciones. También se pueden usar para operaciones manuales de búsqueda y reemplazo como esta:
LLM chat session
>>> Use file-edit-mcp to find all TODO occurrences and summarise here.
# Search for patterns
results = search_files(
pattern="TODO|FIXME",
path="src",
recursive=True,
max_depth=3
)
# Replace across files
replace_in_files(
search="old_function",
replace="new_function",
path=".",
file_pattern="*.py"
)
Parcheo Avanzado
Claude debería descubrir y usar estas funciones como parte de un cometido más amplio, por ejemplo, al modificar código fuente para corregir problemas descubiertos en las pruebas de su propio código.
# Line-based patch
patch_file("config.json", patches=[
{"line": 5, "content": ' "debug": true,'}
])
# Pattern-based patch
patch_file("main.py", patches=[
{"find": "import old", "replace": "import new"}
])
# Context-based patch (safer)
patch_file("app.py", patches=[{
"context": ["def process():", " return None"],
"replace": ["def process():", " return result"]
}])
Análisis de Código
# List all functions in a file
functions = list_functions("mycode.py")
# Returns function names, signatures, line numbers, docstrings
# Find function at specific line
func = get_function_at_line("mycode.py", 42)
# Returns the function containing line 42
# Get complete code structure
structure = get_code_structure("mycode.py")
# Returns imports, classes, functions, and more
# Search for functions by pattern
results = search_functions("test_.*", "tests/", "*.py")
# Finds all test functions
## Available Tools
### File Operations
- `read_file` - Read file contents with optional line range
- `write_file` - Write content to a file
- `create_file` - Create a new file
- `delete_file` - Delete a file or directory
- `move_file` - Move or rename files
- `copy_file` - Copy files or directories
### Directory Operations
- `list_files` - List files with glob patterns and depth control
- `get_file_info` - Get detailed file metadata
### Search and Modification
- `search_files` - Search for patterns with regex support
- `replace_in_files` - Find and replace across multiple files
- `patch_file` - Apply precise modifications to files
### Project Management
- `set_project_directory` - Set the working directory context
- `get_project_directory` - Get current project directory
### Code Analysis- `list_functions` - List all functions in a code file with signatures and line numbers- `get_function_at_line` - Find which function contains a specific line- `get_code_structure` - Extract complete code structure (imports, classes, functions)- `search_functions` - Search for functions by name pattern across files
## Safety Features
- **Path Traversal Protection**: All paths are validated to prevent directory traversal attacks
- **Project Boundary Enforcement**: Operations are restricted to the base directory
- **Backup Creation**: Automatic backups before modifications (configurable)
- **Dry Run Mode**: Preview changes before applying them
- **Atomic Operations**: All-or-nothing patch applications
### SSH Support
The file editor now supports SSH connections for remote filesystem operations:
```python
# Connect to a remote server using SSH URL format
set_project_directory("ssh://user@example.com:22/home/user/project")
# Or specify SSH parameters explicitly
set_project_directory(
path="/home/user/project",
connection_type="ssh",
ssh_host="example.com",
ssh_username="user",
ssh_port=22,
ssh_key_filename="~/.ssh/id_rsa" # Optional, defaults to ~/.ssh/id_rsa
)
# All file operations now work on the remote server
files = list_files("src") # Lists files on remote server
content = read_file("config.json") # Reads from remote server
write_file("output.txt", "Remote content") # Writes to remote server
# Switch back to local filesystem
set_project_directory("/local/path", connection_type="local")
Operaciones de Transferencia de Archivos SSH
Transferir archivos entre sistemas de archivos locales y remotos:
# First, establish SSH connection
set_project_directory(
path="/remote/project",
connection_type="ssh",
ssh_host="example.com",
ssh_username="user"
)
# Upload a single file
result = ssh_upload(
local_path="/local/file.txt",
remote_path="uploads/file.txt"
)
# Upload a directory recursively
result = ssh_upload(
local_path="/local/project",
remote_path="/remote/backup",
recursive=True,
overwrite=True
)
# Download a file
result = ssh_download(
remote_path="data/report.pdf",
local_path="/local/downloads/report.pdf"
)
# Download a directory
result = ssh_download(
remote_path="/remote/logs",
local_path="/local/logs_backup",
recursive=True
)
# Sync directories using rsync for efficiency
result = ssh_sync(
local_path="/local/source",
remote_path="/remote/mirror",
direction="upload", # or "download"
delete=False, # Don't delete extra files in destination
update_only=True, # Only update if source is newer (default)
show_progress=True, # Show rsync progress output (default)
exclude_patterns=[ # Patterns to exclude from sync
"*.log",
"*.tmp",
"node_modules/",
".git/"
]
)
**Transfer Features:**
- Efficient rsync-based synchronization with compression
- Single file or recursive directory transfers
- Smart updates - only transfer files if source is newer
- Automatic directory creation
- Overwrite control with update_only option
- Real-time progress tracking with rsync --progress
- Exclude patterns for filtering files
- Delete option for true mirror synchronization
- Error handling with detailed error reports
- Supports both absolute and relative paths
**SSH Features:**
- Key-based authentication (no password prompts)
- All file operations work transparently over SSH
- No tools required on the remote server
- Efficient operations using SFTP protocol
- Automatic reconnection on connection loss
- Upload/download files between local and remote systems
- Recursive directory transfers
- Sync operations with conflict handling
## Examples
=======
=======
### Git Operations
The file editor provides comprehensive git support for both local and remote repositories:
```python
# Check git status
status = git_status()
# Shows: branch, staged files, modified files, untracked files
# Initialize a new repository
git_init()
# Clone a repository
git_clone("https://github.com/user/repo.git", branch="main")
# Stage files
git_add("file.txt") # Single file
git_add(["*.py", "docs/"]) # Multiple files/patterns
# Commit changes
git_commit("feat: Add new feature")
# Push to remote
git_push("origin", "main", set_upstream=True)
# Pull changes
git_pull("origin", "main")
# View commit history
logs = git_log(limit=20, oneline=False)
# Branch operations
git_branch(create="feature/new-feature") # Create branch
git_checkout("feature/new-feature") # Switch branch
branches = git_branch() # List branches
git_branch(delete="old-branch") # Delete branch
# View differences
diff = git_diff() # Working directory changes
diff = git_diff(cached=True) # Staged changes
# Remote management
remotes = git_remote() # List remotes
git_remote(action="add", name="upstream", url="https://github.com/upstream/repo.git")
git_remote(action="remove", name="old-remote")
Git en Servidores Remotos
Las operaciones de Git funcionan sin problemas en servidores remotos a través de SSH:
# Connect to remote server
set_project_directory(
path="/home/user/project",
connection_type="ssh",
ssh_host="server.example.com",
ssh_username="user"
)
# All git operations now work on the remote server
status = git_status() # Check remote repository status
git_add("*.js") # Stage files on remote
git_commit("fix: Update configuration") # Commit on remote
git_push() # Push from remote to its origin
Características de Git:
- Soporte completo de comandos git (status, add, commit, push, pull, etc.)
- Funciona de manera idéntica en repositorios locales y remotos
- Gestión de ramas (crear, cambiar, eliminar)
- Gestión de repositorios remotos
- Historial de confirmaciones con información detallada
- Visualización de diferencias para cambios
- No se necesita instalación de git en el lado de Claude
Ejemplos Prácticos de Claude Desktop
Ejemplo 1: Analizar y Refactorizar un Proyecto Python
Usuario: "¿Puedes ayudarme a refactorizar este proyecto Python en /Users/me/projects/webapp?"
Claude:
# First, I'll set the project directory to work with your files
set_project_directory("/Users/me/projects/webapp")
# Let me explore the project structure
files = list_files(recursive=True, pattern="*.py")
# Found: app.py, models.py, utils.py, tests/test_app.py, etc.
# Let's look at the main application file
content = read_file("app.py")
# I can see this is a Flask application with some issues...
# Let me check the code structure
structure = get_code_structure("app.py")
# Found 15 functions, 3 classes, various imports
# Search for potential issues
results = search_files("TODO|FIXME|XXX", pattern="*.py")
# Found 8 TODOs across different files
# Let's refactor the database connection function
patch_file(
"app.py",
patches=[{
"find": "def get_db():\n return sqlite3.connect('database.db')",
"replace": "def get_db():\n \"\"\"Get database connection with proper error handling.\"\"\"\n try:\n conn = sqlite3.connect('database.db')\n conn.row_factory = sqlite3.Row\n return conn\n except sqlite3.Error as e:\n current_app.logger.error(f'Database connection failed: {e}')\n raise"
}]
)
# Create a new configuration file
create_file(
"config.py",
content='''"""Application configuration."""
import os
from dotenv import load_dotenv
load_dotenv()
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'dev-key-change-this'
DATABASE_URL = os.environ.get('DATABASE_URL') or 'sqlite:///app.db'
DEBUG = os.environ.get('DEBUG', 'False').lower() == 'true'
'''
)
Ejemplo 2: Desplegar una Aplicación Web en un Servidor Remoto
Usuario: "Necesito desplegar mi aplicación React en mi VPS en server.example.com"
Claude:
# First, let's connect to your remote server
set_project_directory(
path="/var/www/myapp",
connection_type="ssh",
ssh_host="server.example.com",
ssh_username="deploy",
ssh_port=22
)
# Check what's currently on the server
files = list_files()
# I see there's an old version deployed...
# Create a backup of the current deployment
create_file("backup_timestamp.txt", datetime.now().isoformat())
move_file("current", f"backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}")
# Now let's upload your built React app
# First, let me check your local build
set_project_directory("/Users/you/projects/react-app", connection_type="local")
# Make sure you have a fresh build
local_files = list_files("build", recursive=True)
# Good, I can see the build directory with all assets
# Switch back to SSH and upload
set_project_directory(
"ssh://deploy@server.example.com/var/www/myapp",
connection_type="ssh"
)
# Upload the entire build directory
result = ssh_upload(
local_path="/Users/you/projects/react-app/build",
remote_path="current",
recursive=True,
overwrite=True
)
# Uploaded 156 files successfully
# Set proper permissions
for html_file in list_files("current", pattern="*.html"):
# Note: You might need to run chmod via SSH separately
pass
# Create/update the nginx configuration
config_content = read_file("/etc/nginx/sites-available/myapp")
# Let me update the configuration...
Ejemplo 3: Analizar Registros en Múltiples Servidores
Usuario: "Necesito investigar un problema que ocurrió ayer en nuestros tres servidores web"
Claude:
# I'll help you gather and analyze logs from all three servers
# Server 1 - Web Frontend
set_project_directory(
"ssh://admin@web1.example.com/var/log",
connection_type="ssh"
)
# Search for errors in yesterday's logs
error_logs = search_files(
"ERROR|CRITICAL|Exception",
pattern="*.log",
recursive=True
)
# Found 45 matches in nginx/error.log and app/production.log
# Download yesterday's logs for detailed analysis
result = ssh_download(
remote_path="nginx/access.log.1",
local_path="/tmp/analysis/web1_access.log"
)
# Server 2 - API Backend
set_project_directory(
"ssh://admin@api.example.com/var/log",
connection_type="ssh"
)
# Check for database connection errors
db_errors = search_files(
"connection refused|timeout|Connection reset",
pattern="postgresql*.log"
)
# Found 12 connection timeout errors between 14:30-14:45
# Download the specific time range
result = ssh_download(
remote_path="app/api.log",
local_path="/tmp/analysis/api.log"
)
# Server 3 - Background Workers
set_project_directory(
"ssh://admin@worker.example.com/var/log",
connection_type="ssh"
)
# Check for job failures
job_failures = search_files(
"Job.*failed|Task.*error",
pattern="worker*.log"
)
# Now analyze locally
set_project_directory("/tmp/analysis", connection_type="local")
# Correlate timestamps across all logs
all_logs = list_files(pattern="*.log")
for log_file in all_logs:
content = read_file(log_file['name'])
# ... analyze and correlate events
Ejemplo 4: Mantener Archivos de Configuración en Diferentes Entornos
Usuario: "Necesito actualizar archivos de configuración en los entornos de desarrollo, preparación y producción"
Claude:
# Let's create a systematic approach to managing your configurations
# First, let's work with your configuration templates locally
set_project_directory("/Users/you/configs", connection_type="local")
# Create a base configuration template
create_file(
"base_config.yaml",
content="""# Base configuration for all environments
app:
name: MyApplication
version: 2.1.0
logging:
level: INFO
format: json
metrics:
enabled: true
port: 9090
"""
)
# Create environment-specific overrides
environments = ["dev", "staging", "prod"]
for env in environments:
create_file(
f"{env}_config.yaml",
content=f"""# {env.title()} environment configuration
env: {env}
database:
host: {env}-db.internal
pool_size: {'5' if env == 'dev' else '20'}
api:
rate_limit: {'100' if env == 'dev' else '1000'}
debug: {'true' if env == 'dev' else 'false'}
"""
)
# Now deploy to each environment
servers = {
"dev": "dev.example.com",
"staging": "staging.example.com",
"prod": "prod1.example.com"
}
for env, host in servers.items():
# Connect to the server
set_project_directory(
f"ssh://deploy@{host}/etc/myapp",
connection_type="ssh"
)
# Backup existing configuration
if await file_exists("config.yaml"):
copy_file("config.yaml", f"config.yaml.backup.{datetime.now().strftime('%Y%m%d')}")
# Upload the new configuration
result = ssh_upload(
local_path=f"/Users/you/configs/{env}_config.yaml",
remote_path="config.yaml"
)
# Verify the upload
content = read_file("config.yaml")
print(f"✓ Updated configuration on {env} server")
Ejemplo 5: Revisión Colaborativa de Código y Correcciones
Usuario: "¿Puedes revisar mi código y corregir cualquier problema de seguridad que encuentres?"
Claude:
# Let's do a comprehensive security review of your codebase
set_project_directory("/Users/you/projects/webapp")
# First, let's search for common security issues
# 1. Check for hardcoded secrets
secrets_search = search_files(
"password.*=.*['\"]|api_key.*=.*['\"]|secret.*=.*['\"]|token.*=.*['\"]",
pattern="*.py,*.js,*.env*"
)
# Found potential hardcoded secrets in config.py and test_api.py
# 2. Look for SQL injection vulnerabilities
sql_issues = search_files(
"execute\(.*%.*%|execute\(.*format\(|execute\(.*\+.*",
pattern="*.py"
)
# Found 3 potential SQL injection points
# Let's fix the SQL injection in user.py
patch_file(
"models/user.py",
patches=[{
"find": 'cursor.execute(f"SELECT * FROM users WHERE email = \'{email}\'")',
"replace": 'cursor.execute("SELECT * FROM users WHERE email = %s", (email,))'
}]
)
# 3. Check for missing input validation
validation_check = list_functions("routes.py")
# I'll examine each route handler...
# Fix missing validation in the user registration endpoint
patch_file(
"routes.py",
patches=[{
"find": "@app.route('/register', methods=['POST'])\ndef register():\n email = request.form['email']\n password = request.form['password']",
"replace": "@app.route('/register', methods=['POST'])\ndef register():\n email = request.form.get('email', '').strip()\n password = request.form.get('password', '')\n \n # Validate input\n if not email or not re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', email):\n return jsonify({'error': 'Invalid email address'}), 400\n if len(password) < 8:\n return jsonify({'error': 'Password must be at least 8 characters'}), 400"
}]
)
# 4. Create a security configuration file
create_file(
"security.py",
content='''"""Security configuration and utilities."""
import os
from functools import wraps
from flask import request, jsonify
import secrets
# Security headers
SECURITY_HEADERS = {
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block',
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains'
}
# Rate limiting configuration
RATE_LIMIT_REQUESTS = 100
RATE_LIMIT_WINDOW = 3600 # 1 hour
def generate_secure_token():
"""Generate a cryptographically secure token."""
return secrets.token_urlsafe(32)
def require_api_key(f):
"""Decorator to require API key for endpoints."""
@wraps(f)
def decorated_function(*args, **kwargs):
api_key = request.headers.get('X-API-Key')
if not api_key or not validate_api_key(api_key):
return jsonify({'error': 'Invalid or missing API key'}), 401
return f(*args, **kwargs)
return decorated_function
'''
)
# 5. Create a security audit report
report = f"""# Security Audit Report
Date: {datetime.now().strftime('%Y-%m-%d %H:%M')}
## Issues Found and Fixed:
1. SQL Injection: Fixed {len(sql_issues['results'])} vulnerable queries
2. Hardcoded Secrets: Found {len(secrets_search['results'])} instances
3. Input Validation: Added validation to user registration
4. Security Headers: Created security configuration file
## Recommendations:
- Move all secrets to environment variables
- Implement rate limiting on all endpoints
- Add CSRF protection to forms
- Enable security headers in production
- Regular dependency updates
"""
create_file("SECURITY_AUDIT.md", report)
Más Interacciones Prácticas con Claude Desktop
Operaciones Rápidas de Archivos
Usuario: "Lista los archivos en el directorio actual"
Claude:
# I'll list the files in your current directory
files = list_files()
# Here are the files I found:
# - README.md (2.5 KB)
# - app.py (10.2 KB)
# - requirements.txt (456 bytes)
# - tests/ (directory)
# - static/ (directory)
Usuario: "Muéstrame qué hay en la carpeta de pruebas"
Claude:
test_files = list_files("tests", recursive=True)
# Found in tests/:
# - test_app.py (3.2 KB)
# - test_models.py (2.8 KB)
# - test_utils.py (1.5 KB)
# - fixtures/test_data.json (890 bytes)
Gestión de Servidores Remotos
Usuario: "Usa el servidor remoto user@foo.example.com, establece el directorio de trabajo remoto en /home/user/project_a y sube el archivo readme.txt"
Claude:
# I'll connect to your remote server and upload the file
set_project_directory(
path="/home/user/project_a",
connection_type="ssh",
ssh_host="foo.example.com",
ssh_username="user"
)
# Connected to foo.example.com as user
# Now uploading readme.txt from your local directory
result = ssh_upload(
local_path="readme.txt",
remote_path="readme.txt"
)
# Successfully uploaded readme.txt (1,234 bytes)
Usuario: "Verifica si el archivo se subió correctamente y muéstrame qué archivos hay en el servidor"
Claude:
# Let me verify the upload and show you the directory contents
files = list_files()
# Files in /home/user/project_a:
# - readme.txt (1,234 bytes) - just uploaded
# - config.json (456 bytes)
# - src/ (directory)
# - logs/ (directory)
# Let's verify the content matches
content = read_file("readme.txt")
# The file contains your project documentation and was uploaded successfully
Edición de Archivos de Configuración
Usuario: "Necesito actualizar la cadena de conexión de la base de datos en mi archivo de configuración"
Claude:
# I'll help you update the database configuration
# First, let me read the current config
config_content = read_file("config.json")
# I'll update the database connection string
patch_file(
"config.json",
patches=[{
"find": "\"database_url\": \"postgresql://localhost/myapp\"",
"replace": "\"database_url\": \"postgresql://db.example.com:5432/myapp_prod\""
}]
)
# Configuration updated successfully
Búsqueda en Archivos
Usuario: "Encuentra todos los comentarios TODO en mis archivos Python"
Claude:
# I'll search for TODO comments across all Python files
todos = search_files(
pattern="TODO|FIXME|XXX",
file_pattern="*.py",
recursive=True
)
# Found 12 TODOs:
# app.py:45 - TODO: Add error handling for database connection
# app.py:89 - TODO: Implement rate limiting
# models.py:23 - FIXME: This query is not optimized
# utils.py:67 - TODO: Add unit tests for this function
# ...
Copia de Seguridad y Restauración
Usuario: "Crea una copia de seguridad de todo mi directorio de proyecto"
Claude:
# I'll create a timestamped backup of your project
from datetime import datetime
backup_name = f"backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
# Create backup directory
create_file(f"../{backup_name}/.backup_info", f"Backup created at {datetime.now()}")
# Copy all files
files = list_files(recursive=True)
for file in files:
if file['type'] == 'file':
content = read_file(file['name'])
write_file(f"../{backup_name}/{file['name']}", content)
# Backup created successfully at ../{backup_name}/
Trabajo con Múltiples Archivos
Usuario: "Reemplaza todas las instancias de 'http://' con 'https://' en todos mis archivos de configuración"
Claude:
# I'll update all config files to use HTTPS
result = replace_in_files(
search="http://",
replace="https://",
file_pattern="*.conf,*.json,*.yaml,*.yml",
recursive=True
)
# Updated 8 files:
# - config.json: 3 replacements
# - app.conf: 2 replacements
# - settings.yaml: 1 replacement
# ...
# Total: 15 replacements across 8 files
Análisis de Estructura de Código
Usuario: "Muéstrame todas las funciones en mi archivo main.py"
Claude:
# I'll analyze the code structure of main.py
functions = list_functions("main.py")
# Found 12 functions in main.py:
# 1. initialize_app() - Line 10-25: Sets up the application
# 2. connect_database() - Line 28-45: Establishes database connection
# 3. authenticate_user() - Line 48-72: Handles user authentication
# 4. process_request() - Line 75-95: Main request handler
# ...
# Let me also show you the overall structure
structure = get_code_structure("main.py")
# File structure:
# - Imports: 8 (flask, sqlalchemy, ...)
# - Classes: 3 (App, Database, UserAuth)
# - Functions: 12
# - Total lines: 450
Control de Versiones con Git
Usuario: "Inicializa git para este proyecto y haz la primera confirmación"
Claude:
# I'll initialize git and create your first commit
# Initialize the repository
result = git_init()
# Initialized empty Git repository in /Users/you/project/.git/
# Check current status
status = git_status()
# Untracked files: app.py, README.md, requirements.txt, config.json
# Create a .gitignore file
create_file(".gitignore", '''# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
venv/
ENV/
# IDE
.vscode/
.idea/
*.swp
*.swo
# Environment
.env
.env.local
# OS
.DS_Store
Thumbs.db
''')
# Add all files
git_add(".")
# Added 5 files to staging area
# Make the first commit
commit_result = git_commit("Initial commit: Project setup")
# Created commit 7a8b9c1: Initial commit: Project setup
Usuario: "Crea una nueva rama de características y súbela a GitHub"
Claude:
# I'll create a feature branch and set up the GitHub remote
# First, let's add the GitHub remote
git_remote(
action="add",
name="origin",
url="https://github.com/yourusername/project.git"
)
# Added remote 'origin'
# Create and switch to a new feature branch
git_branch(create="feature/user-authentication")
git_checkout("feature/user-authentication")
# Switched to new branch 'feature/user-authentication'
# Make some changes for the feature
create_file("auth.py", '''"""User authentication module."""
import hashlib
import secrets
class UserAuth:
def __init__(self):
self.users = {}
def create_user(self, username, password):
salt = secrets.token_hex(16)
password_hash = hashlib.sha256((password + salt).encode()).hexdigest()
self.users[username] = {
"salt": salt,
"password_hash": password_hash
}
return True
''')
# Stage and commit the changes
git_add("auth.py")
git_commit("feat: Add user authentication module")
# Push the branch to GitHub
git_push("origin", "feature/user-authentication", set_upstream=True)
# Branch 'feature/user-authentication' set up to track 'origin/feature/user-authentication'
# Successfully pushed to GitHub
Creación de Plantillas de Proyecto
Usuario: "Crea una estructura básica de proyecto Flask para mí"
Claude:
# I'll create a basic Flask project structure
# Create main application file
create_file("app.py", '''from flask import Flask, render_template
app = Flask(__name__)
app.config.from_object('config.Config')
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
''')
# Create configuration
create_file("config.py", '''import os
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'dev-secret-key'
DATABASE_URL = os.environ.get('DATABASE_URL') or 'sqlite:///app.db'
''')
# Create requirements file
create_file("requirements.txt", '''Flask==2.3.2
SQLAlchemy==2.0.19
python-dotenv==1.0.0
''')
# Create directory structure
create_file("templates/index.html", '''<!DOCTYPE html>
<html>
<head>
<title>My Flask App</title>
</head>
<body>
<h1>Welcome to Flask!</h1>
</body>
</html>
''')
create_file("static/style.css", '''body {
font-family: Arial, sans-serif;
margin: 40px;
}
''')
create_file(".env.example", '''SECRET_KEY=your-secret-key-here
DATABASE_URL=sqlite:///app.db
''')
# Flask project structure created successfully!
Ejemplos de Código
Consulte el directorio examples/ para ver ejemplos detallados de uso:
example_usage.py- Operaciones básicas de archivosenhanced_features_examples.py- Búsqueda avanzada y control de profundidadpatch_examples.py- Varias técnicas de parcheoproject_directory_examples.py- Uso del directorio de proyectossh_transfer_examples.py- Operaciones de subida/descarga SSH
Desarrollo
Ejecutar Pruebas
# Run all tests
python -m pytest tests/
# Run specific test
python tests/test_patch.py
Estructura del Proyecto
mcp-file-edit/
├── server.py # Main MCP server implementation
├── pyproject.toml # Project configuration
├── README.md # This file
├── LICENSE # MIT license
├── examples/ # Usage examples
│ ├── example_usage.py
│ ├── patch_examples.py
│ └── ...
└── tests/ # Test files
├── test_patch.py
├── test_enhanced.py
└── ...
Contribuciones
¡Las contribuciones son bienvenidas! No dude en enviar una Solicitud de Extracción.
- Haga un fork del repositorio
- Cree su rama de características (
git checkout -b feature/AmazingFeature) - Confirme sus cambios (
git commit -m 'Add some AmazingFeature') - Envíe a la rama (
git push origin feature/AmazingFeature) - Abra una Solicitud de Extracción
Licencia
Este proyecto está licenciado bajo la Licencia MIT - consulte el archivo LICENSE para más detalles.
Agradecimientos
- Construido con el marco FastMCP
- Implementa la especificación del Protocolo de Contexto de Modelos
Soporte
Para problemas, preguntas o sugerencias, abra un problema en GitHub.