Filesystem Gitignore
БесплатноНе проверенA professional MCP server that provides filesystem operations while automatically respecting .gitignore patterns, enabling efficient and token-friendly file acc
Описание
A professional MCP server that provides filesystem operations while automatically respecting .gitignore patterns, enabling efficient and token-friendly file access for Claude.
README
Python 3.10+ License: MIT Code style: black
Un servidor MCP (Model Context Protocol) profesional que proporciona operaciones de sistema de archivos mientras respeta automáticamente los patrones de .gitignore.
🎯 ¿Qué problema resuelve?
Cuando Claude trabaja con proyectos que tienen venv/, node_modules/, o .git/, intentar leer todo el directorio puede:
- ⚠️ Agotar el límite de tokens leyendo 50k+ archivos innecesarios
- ⏱️ Ser extremadamente lento al procesar directorios gigantes
- 🤯 Ser confuso mezclando código fuente con dependencias
Este servidor resuelve eso respetando .gitignore automáticamente, igual que Git. Claude solo ve lo que realmente importa: tu código.
✨ Características
- ✅ Respeta
.gitignoreautomáticamente: Excluyevenv/,node_modules/,__pycache__/, etc. - ✅ Optimizado para tokens: Solo lee archivos relevantes de tu proyecto
- ✅ Operaciones completas: Leer, escribir, listar, buscar, y crear archivos/directorios
- ✅ Seguridad por diseño: Solo accede a directorios explícitamente permitidos
- ✅ Caracteres especiales: Maneja espacios,
#,@, y otros caracteres en nombres - ✅ Cache inteligente: Cachea patrones
.gitignorecon invalidación automática - ✅ Type-safe: Completamente tipado con dataclasses y type hints
- ✅ Production-ready: Tests, logging, manejo de errores robusto
🏗️ Arquitectura
┌─────────────────────────────────────────────────────────────┐
│ MCP Protocol Layer │
│ (server.py - Adaptador que traduce MCP ↔ FileSystemService)│
└────────────────────┬────────────────────────────────────────┘
│
┌───────────────────▼────────────────────────────────────────┐
│ Business Logic Layer │
│(filesystem_service.py - Orquesta validación + operaciones) │
└──────┬──────────────────────────────┬──────────────────────┘
│ │
▼ ▼
┌──────────────────┐ ┌──────────────────────┐
│ Path Validation │ │ .gitignore Manager │
│ (path_validator) │ │ (ignore_manager) │
│ │ │ │
│ - URL decoding │ │ - Pattern matching │
│ - Security check │ │ - Intelligent cache │
└──────────────────┘ └──────────────────────┘
│ │
└──────────────┬───────────────┘
│
┌──────────────▼──────────────────┐
│ Data Access Layer │
│ (filesystem_operations.py) │
│ │
│ - Pure I/O operations │
│ - No business logic │
└─────────────────────────────────┘
Responsabilidades por capa:
MCP Protocol Layer (
server.py):- Traduce requests MCP a llamadas del service
- Serializa responses a JSON
- Maneja el protocolo stdio
Business Logic Layer (
filesystem_service.py):- Orquesta validación + filtering + operaciones
- Punto de entrada público del sistema
- Combina múltiples componentes para cada operación
Support Components:
path_validator: Normaliza y valida paths (seguridad)ignore_manager: Cache y matching de.gitignorefilesystem_operations: I/O puro, sin lógica de negocio
Foundation:
config.py: Configuración centralizadaerrors.py: Excepciones tipadasmodels.py: Dataclasses para type safety
Beneficios de esta arquitectura:
- ✅ Cada capa es testeable independientemente
- ✅ Fácil cambiar implementación de una capa sin afectar otras
- ✅ Separación clara de responsabilidades
- ✅ Código reutilizable (el service puede usarse fuera de MCP)
📋 Requisitos
- Python 3.10+
- Compatible con clientes MCP como Claude Desktop, Zed, Sourcegraph Cody y otros que implementen el estándar Model Context Protocol.
🚀 Instalación Rápida
# 1. Clonar y navegar al proyecto
cd "C:\DesarrolloPython\MCP FileSystem"
# 2. Instalar dependencias de desarrollo
make.bat install-dev
# 3. Ejecutar tests para verificar
make.bat test
Configurar Claude Desktop
Edita el archivo de configuración:
Windows: %APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"filesystem-gitignore": {
"command": "python",
"args": [
"-m",
"mcp_filesystem"
],
"env": {
"ALLOWED_DIRECTORIES": "C:\\DesarrolloPython;C:\\MisProyectos"
}
}
}
}
Notas:
- Usa paths absolutos
- Windows: separa directorios con
; - Unix/Mac: separa directorios con
:
Reinicia Claude Desktop para aplicar cambios.
🔧 Uso
Herramientas Disponibles
1. read_file - Leer archivo de texto
read_file(path="C:\\DesarrolloPython\\proyecto\\src\\main.py")
2. write_file - Escribir archivo
write_file(
path="C:\\DesarrolloPython\\nuevo_archivo.py",
content="print('Hello, World!')"
)
3. list_directory - Listar contenido (no recursivo)
# Por defecto respeta .gitignore
list_directory(path="C:\\DesarrolloPython\\proyecto")
# Forzar mostrar TODO (incluso venv)
list_directory(path="C:\\DesarrolloPython\\proyecto", respect_gitignore=False)
4. directory_tree - Árbol recursivo
directory_tree(
path="C:\\DesarrolloPython\\proyecto",
max_depth=5,
respect_gitignore=True # Default
)
5. search_files - Buscar archivos
search_files(
path="C:\\DesarrolloPython",
pattern="config", # Case-insensitive
respect_gitignore=True
)
6. get_file_info - Información detallada
get_file_info(path="C:\\DesarrolloPython\\proyecto\\README.md")
7. create_directory - Crear directorio
create_directory(path="C:\\DesarrolloPython\\nuevo_proyecto\\src")
📝 Decisiones de Diseño
¿Cómo se maneja .gitignore?
- Parseo con pathspec: Usamos la librería
pathspecque implementa el mismo algoritmo que Git - Cache inteligente:
- Cada
.gitignorese parsea una sola vez y se cachea - El cache se invalida automáticamente cuando el
.gitignorecambia (detecta pormtime) - Cache por directorio (cada dir tiene su propio
.gitignore)
- Cada
- Matching preciso:
- Convierte paths a formato POSIX (forward slashes)
- Agrega
/al final de directorios (convención de Git) - Usa
gitwildmatchpara matching exacto
¿Cómo se optimiza el consumo de tokens?
- Filtrado temprano: Los archivos ignorados ni siquiera se listan
- Control de profundidad:
directory_treelimita profundidad máxima (default: 5) - Sin lectura de contenido: Solo lista nombres, no lee contenidos
- Respeto opcional: Todas las herramientas tienen
respect_gitignoreflag (default:True)
Comparación:
# ❌ Sin .gitignore (50k+ archivos en venv):
directory_tree("C:\\proyecto") # 🔥 Consume 100k+ tokens
# ✅ Con .gitignore (solo archivos de proyecto):
directory_tree("C:\\proyecto") # ✅ ~2k tokens
Seguridad: ¿Por qué directorios permitidos?
- Previene acceso a archivos sensibles del sistema
- Claude solo puede trabajar en tus proyectos
- Validación en cada operación (no se puede "escapar" con
../../../)
🧪 Testing
# Ejecutar todos los tests
make.bat test
# Solo tests unitarios
make.bat test-unit
# Solo tests de integración
make.bat test-integration
# Con reporte de coverage
make.bat test-cov
🛠️ Desarrollo
# Formatear código
make.bat format
# Linters
make.bat lint
# Limpiar archivos generados
make.bat clean
🐛 Troubleshooting
"ALLOWED_DIRECTORIES environment variable must be set"
Solución: Configura la variable de entorno en Claude Desktop config.
"Access denied"
Causa: El path no está en ALLOWED_DIRECTORIES
Solución: Agrega el directorio a la lista.
No respeta .gitignore
Verifica:
- ¿Existe
.gitignoreen el directorio? - ¿Los patrones están bien escritos?
- ¿Estás usando
respect_gitignore=True? (es el default)
Consume muchos tokens
Solución:
- Crea/mejora tu
.gitignore - Reduce
max_depthendirectory_tree
# .gitignore recomendado para Python:
venv/
env/
__pycache__/
*.pyc
.git/
.pytest_cache/
.mypy_cache/
htmlcov/
📚 Referencias
🤝 Contribuciones
¡Las contribuciones son bienvenidas!
Antes de hacer PR:
- ✅ Ejecuta
make.bat test(todos los tests deben pasar) - ✅ Ejecuta
make.bat lint(sin warnings) - ✅ Ejecuta
make.bat format(código formateado) - ✅ Agrega tests para nueva funcionalidad
📄 Licencia
MIT License - Úsalo libremente.
Desarrollado con ❤️ para optimizar la interacción de Claude con proyectos reales
Установка Filesystem Gitignore
У этого сервера нет опубликованного пакета — он собирается из исходников. Открой репозиторий и следуй инструкции в README.
▸ github.com/mvecchiett/mcp-filesystem-gitignoreFAQ
Filesystem Gitignore MCP бесплатный?
Да, Filesystem Gitignore MCP бесплатный — установка в пару кликов через Unyly без оплаты.
Нужен ли API-ключ для Filesystem Gitignore?
Нет, Filesystem Gitignore работает без API-ключей и переменных окружения.
Filesystem Gitignore — hosted или self-hosted?
Self-hosted: сервер запускается локально на твоей машине командой из раздела установки.
Как установить Filesystem Gitignore в Claude Desktop, Claude Code или Cursor?
Открой Filesystem Gitignore на unyly.org, выбери вкладку своего клиента (Claude Desktop, Claude Code, Cursor) и нажми Install — конфиг сгенерируется автоматически, без правки JSON.
Похожие MCP
Fetch
Web content fetching and conversion for efficient LLM usage.
AWS KB Retrieval
Retrieval from AWS Knowledge Base using Bedrock Agent Runtime.
автор: modelcontextprotocolSpring AI MCP Server
Provides auto-configuration for setting up an MCP server in Spring Boot applications.
llm-analysis-assistant
A very streamlined mcp client that supports calling and monitoring stdio/sse/streamableHttp, and can also view request responses through the /logs page. It also
автор: xuzexin-hzCompare Filesystem Gitignore with
Не уверен что выбрать?
Найди свой стек за 60 секунд
Автор?
Embed-бейдж для README
Похожее
Все в категории ai
