filesystem-gitignore

filesystem-gitignore

A professional MCP server that provides filesystem operations while automatically respecting .gitignore patterns, enabling efficient and token-friendly file access for Claude.

Category
访问服务器

README

🗂️ MCP Filesystem Server

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 .gitignore automáticamente: Excluye venv/, 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 .gitignore con 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:

  1. MCP Protocol Layer (server.py):

    • Traduce requests MCP a llamadas del service
    • Serializa responses a JSON
    • Maneja el protocolo stdio
  2. 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
  3. Support Components:

    • path_validator: Normaliza y valida paths (seguridad)
    • ignore_manager: Cache y matching de .gitignore
    • filesystem_operations: I/O puro, sin lógica de negocio
  4. Foundation:

    • config.py: Configuración centralizada
    • errors.py: Excepciones tipadas
    • models.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?

  1. Parseo con pathspec: Usamos la librería pathspec que implementa el mismo algoritmo que Git
  2. Cache inteligente:
    • Cada .gitignore se parsea una sola vez y se cachea
    • El cache se invalida automáticamente cuando el .gitignore cambia (detecta por mtime)
    • Cache por directorio (cada dir tiene su propio .gitignore)
  3. Matching preciso:
    • Convierte paths a formato POSIX (forward slashes)
    • Agrega / al final de directorios (convención de Git)
    • Usa gitwildmatch para matching exacto

¿Cómo se optimiza el consumo de tokens?

  1. Filtrado temprano: Los archivos ignorados ni siquiera se listan
  2. Control de profundidad: directory_tree limita profundidad máxima (default: 5)
  3. Sin lectura de contenido: Solo lista nombres, no lee contenidos
  4. Respeto opcional: Todas las herramientas tienen respect_gitignore flag (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:

  1. ¿Existe .gitignore en el directorio?
  2. ¿Los patrones están bien escritos?
  3. ¿Estás usando respect_gitignore=True? (es el default)

Consume muchos tokens

Solución:

  1. Crea/mejora tu .gitignore
  2. Reduce max_depth en directory_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

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选