--- name: init-jupyter description: Inicializa o inicia Jupyter Lab via MCP con kernel compartido. Detecta notebooks existentes automáticamente. argument-hint: [ruta-proyecto] disable-model-invocation: true user-invocable: true allowed-tools: Bash, Read, Write, Edit, Glob --- # Inicializar/Iniciar Proyecto Jupyter via MCP Este skill gestiona entornos Jupyter Lab integrados con Claude via MCP. Detecta automáticamente si ya existe un proyecto configurado. ## Modo de Colaboración (Kernel Compartido) **IMPORTANTE**: Para que las ejecuciones de Claude sean visibles en Jupyter Lab, se debe usar el **mismo kernel** que el notebook abierto. Esto permite: - Ver las ejecuciones de Claude en tiempo real en Jupyter Lab - Compartir variables y estado entre Claude y el usuario - Colaboración real entre ambos en el mismo notebook ## Flujo de decisión ### 1. Detectar notebooks existentes Buscar archivos `.ipynb` en: - Raíz del proyecto - Carpeta `notebooks/` - Cualquier subcarpeta ```bash find [ruta] -name "*.ipynb" -type f 2>/dev/null | head -5 ``` ### 2. Si HAY notebooks existentes → Conectar o Iniciar **2a. Verificar que MCP está configurado con kernel compartido** - Comprobar si existe `.claude/settings.local.json` con configuración de jupyter - Verificar que incluye `--start-new-runtime false` para colaboración - Si no existe o falta la configuración, crearlo (ver paso 3f) **2b. Verificar que jupyter-mcp-server está instalado** ```bash which jupyter-mcp-server || uv tool install jupyter-mcp-server ``` **2c. Verificar si el script run-jupyter-lab.sh existe** - Si no existe, crearlo (ver paso 3g) **2d. Detectar si Jupyter ya está corriendo** ```bash # Verificar si hay un servidor Jupyter activo en el puerto esperado curl -s http://localhost:8888/api/status 2>/dev/null && echo "Jupyter activo" || echo "Jupyter no detectado" ``` **2e. Si Jupyter YA está corriendo:** - **NO arrancarlo de nuevo** - Informar al usuario: "Jupyter Lab detectado en http://localhost:8888" - Claude puede conectarse directamente via MCP al kernel existente - El usuario tiene libertad total para gestionar Jupyter manualmente **2f. Si Jupyter NO está corriendo:** - Preguntar al usuario si quiere que Claude lo arranque o prefiere hacerlo manualmente con `./run-jupyter-lab.sh` - Si el usuario quiere arrancarlo: ```bash source .venv/bin/activate 2>/dev/null || true jupyter lab --no-browser --NotebookApp.token='' --NotebookApp.password='' --NotebookApp.disable_check_xsrf=True ``` **2g. Informar al usuario** que puede usar las herramientas MCP de Jupyter desde Claude. ### 3. Si NO hay notebooks → Inicializar proyecto completo Seguir estos pasos: **3a. Validar ubicación** - Si se proporciona `$1`, usar esa ruta - Si no, usar el directorio actual **3b. Inicializar proyecto con uv** (si no existe pyproject.toml) ```bash cd [ruta] && uv init ``` **3c. Crear entorno virtual** ```bash uv venv ``` **3d. Instalar dependencias** ```bash uv add jupyter jupyter-collaboration ``` **3e. Instalar jupyter-mcp-server** ```bash uv tool install jupyter-mcp-server ``` **3f. Configurar MCP para Claude (con kernel compartido)** Crear o actualizar `.claude/settings.local.json`: ```json { "mcpServers": { "jupyter": { "command": "jupyter-mcp-server", "args": [ "--jupyter-url", "http://localhost:8888", "--start-new-runtime", "false" ] } } } ``` **Parámetros clave:** - `--jupyter-url`: URL del servidor Jupyter (por defecto localhost:8888) - `--start-new-runtime false`: **CRÍTICO** - Conecta al kernel existente en lugar de crear uno nuevo **3g. Crear script `run-jupyter-lab.sh`** Crear un script ejecutable para que el usuario pueda arrancar Jupyter manualmente: ```bash cat > run-jupyter-lab.sh << 'SCRIPT' #!/bin/bash # Script para iniciar Jupyter Lab con configuración de colaboración # El usuario puede arrancarlo manualmente y Claude se conectará al kernel existente PORT=${1:-8888} source .venv/bin/activate 2>/dev/null || true echo "Iniciando Jupyter Lab en puerto $PORT..." echo "Abre http://localhost:$PORT en tu navegador" echo "" echo "Claude se conectará automáticamente al kernel cuando abras un notebook." jupyter lab \ --port=$PORT \ --no-browser \ --NotebookApp.token='' \ --NotebookApp.password='' \ --NotebookApp.disable_check_xsrf=True \ --ServerApp.allow_origin='*' SCRIPT chmod +x run-jupyter-lab.sh ``` **3h. Crear carpeta notebooks** (opcional) ```bash mkdir -p notebooks ``` **3i. Iniciar Jupyter via MCP** ```bash source .venv/bin/activate jupyter lab --no-browser --NotebookApp.token='' --NotebookApp.password='' --NotebookApp.disable_check_xsrf=True ``` ## Ejemplos de uso **Iniciar/inicializar en directorio actual:** ```bash /init-jupyter ``` **Iniciar/inicializar en ruta específica:** ```bash /init-jupyter ~/proyectos/mi-analisis ``` ## Flujo de trabajo colaborativo (Kernel Compartido) ### Cómo funciona la colaboración 1. **Usuario inicia Jupyter Lab** (via este skill) 2. **Usuario abre un notebook** en Jupyter Lab → se inicia un kernel 3. **Claude se conecta al MISMO kernel** via MCP con `--start-new-runtime false` 4. **Ambos comparten**: - El mismo estado de variables - El mismo historial de ejecución - Las salidas son visibles para ambos en tiempo real ### Pasos para colaborar **Opción A - Usuario arranca Jupyter manualmente (recomendado):** 1. Ejecutar `./run-jupyter-lab.sh` (o `./run-jupyter-lab.sh 8889` para otro puerto) 2. Abrir el navegador en http://localhost:8888 3. Abrir o crear el notebook deseado 4. Ejecutar `/init-jupyter` - Claude detectará Jupyter y se conectará al kernel existente 5. **Claude ya puede ejecutar celdas** y el usuario verá las ejecuciones en su Jupyter Lab **Opción B - Claude arranca Jupyter:** 1. Ejecutar `/init-jupyter` 2. Si no hay Jupyter corriendo, Claude lo arrancará 3. Abrir el navegador en http://localhost:8888 4. Abrir o crear el notebook deseado 5. **Claude ya puede ejecutar celdas** ### Obtener kernel ID específico (opcional) Si hay múltiples kernels corriendo, puedes obtener el ID del kernel activo: ```bash curl -s http://localhost:8888/api/kernels | jq '.[0].id' ``` Y configurar MCP con ese kernel específico: ```json { "mcpServers": { "jupyter": { "command": "jupyter-mcp-server", "args": [ "--jupyter-url", "http://localhost:8888", "--runtime-id", "KERNEL_ID_AQUI" ] } } } ``` ## Notas importantes - **Siempre usa MCP**: Jupyter se ejecuta siempre de forma que Claude pueda interactuar via MCP - **Kernel compartido por defecto**: Con `--start-new-runtime false`, Claude usa el kernel existente - **Script `run-jupyter-lab.sh`**: Se crea automáticamente para que el usuario pueda arrancar Jupyter cuando quiera - **Detección automática**: Claude detecta si Jupyter ya está corriendo y no lo arranca de nuevo - **Libertad del usuario**: El usuario puede gestionar Jupyter manualmente, Claude se adapta - Si detecta notebooks existentes, NO reinicializa el proyecto, solo conecta o inicia Jupyter - Si el proyecto ya tiene `pyproject.toml`, no ejecuta `uv init` - La configuración MCP se guarda en `.claude/settings.local.json` del proyecto - El servidor MCP permite a Claude crear, editar y ejecutar celdas de notebooks - **jupyter-collaboration** ya está incluido en las dependencias para sincronización en tiempo real