colab-mcp
Los repositorios fueron apoyados por Linux.do
Colab MCP
Servidor MCP local-first para controlar Google Colab como entorno de desarrollo, shell, archivos y entrenamiento.
Documentación en chino: README.zh-CN.md
Qué proporciona esto
Este fork extiende la base estática de Colab MCP original con:
edición de notebooks, ejecución por lotes, sondeo de estado y lectura de salidas
inicio controlado del navegador Edge y reparación del MCP del frontend de Colab
conexión explícita al entorno de ejecución de Python con
connect_runtimecambio de acelerador del entorno de ejecución nativo de MCP, incluida la selección de GPU T4
comandos de shell respaldados por la terminal de Colab y trabajos en segundo plano
herramientas de carga/descarga de archivos desde rutas locales
herramientas de listado/estado/eliminación/directorio de archivos del entorno de ejecución
comprobaciones de GPU, instantáneas y trabajos de monitoreo
ayudantes de variables de entorno y herramientas de reinicio/apagado del entorno de ejecución
Related MCP server: mcp-server-colab-exec
Estructura del proyecto
src/colab_mcp/: Servidor MCP de Python, proxy de sesión de Colab, herramientas de entorno de ejecución/navegador.tests/: pruebas unitarias para el proxy, comportamiento de las herramientas y comportamiento del servidor websocket.docs/: uso, inventario de herramientas, ejemplos, solución de problemas y convenciones de API.TODO.md: lista de verificación de implementación y notas de seguimiento.
Configuración
uv sync --dev
uv run pytestEjecuta el servidor MCP:
uv run colab-mcpConfiguración del cliente MCP:
{
"mcpServers": {
"colab-mcp": {
"command": "uv",
"args": ["run", "--directory", "<path-to-colab_mcp>", "colab-mcp"],
"startup_timeout_sec": 120,
"env": {
"COLAB_MCP_EDGE_CDP_PORT": "9333",
"COLAB_MCP_EDGE_URL_CONTAINS": "colab.research.google.com"
}
}
}
}Reemplaza <path-to-colab_mcp> con la ruta absoluta a tu copia local.
Preparación del entorno de ejecución
No asumas que el entorno de ejecución de Python está listo solo porque el MCP del navegador está conectado. Las herramientas de shell, archivos, GPU y entrenamiento requieren un entorno de ejecución de Colab real y un socket de terminal.
Contrato de resultados
Las herramientas utilizan campos de estado estructurados:
ok=true,status="ok": la operación se completó sin advertencias conocidas.ok=false,status="warning": falta un prerrequisito, resultado parcial/sin efecto o estado recuperable. LeewarningsyrecommendedNextActions.ok=false,status="error": la ejecución falló, se agotó el tiempo de espera, devolvió un código de salida distinto de cero o encontró un error explícito de la herramienta. Inspeccionaerror,stdout,stderryrecommendedNextActionsantes de volver a intentar.
No continúes un flujo de trabajo después de una warning o error sin manejar las instrucciones devueltas.
Flujo del navegador y del entorno de ejecución
Hay dos capas de conexión separadas:
Conexión MCP del navegador/frontend.
Conexión al entorno de ejecución de Python de Colab.
Para el trabajo normal en el entorno de ejecución:
open_colab_browser_connection()
connect_runtime(waitSeconds=180)Para trabajo con GPU:
open_colab_browser_connection()
set_runtime_accelerator(accelerator="T4 GPU", apply=true)
open_colab_browser_connection()
connect_runtime(waitSeconds=180)
check_gpu()Cambiar el acelerador puede reiniciar o desconectar el entorno de ejecución. Siempre vuelve a conectar el MCP del navegador y luego llama a connect_runtime antes de usar herramientas de shell, archivos, GPU o entrenamiento.
Flujo de entrenamiento común
Todos los pasos principales de entrenamiento pueden ejecutarse a través de herramientas MCP:
open_colab_browser_connection()
set_runtime_accelerator(accelerator="T4 GPU", apply=true)
open_colab_browser_connection()
connect_runtime(waitSeconds=180)
check_gpu()
upload_local_file(localPath="<path-to-train.py>", path="/content/train.py", overwrite=true)
start_background_command(
name="train",
command="python /content/train.py",
logPath="/content/train.log",
cwd="/content"
)
watch_background_command(name="train", lines=100)
download_file_to_local(path="/content/model.pt", localPath="<path-to-model.pt>", overwrite=true)
shutdown_runtime(reason="training finished")Usa start_background_command para entrenamiento y trabajos largos. No uses run_shell_command para entrenamiento; es para comandos cortos y acotados.
Liberar o cerrar la instancia del entorno de ejecución
Libera siempre el entorno de ejecución de Colab cuando el trabajo haya terminado, se haya cancelado o ya no necesite recursos de CPU/GPU:
shutdown_runtime(reason="training finished")Flujo de finalización recomendado:
stat_file(path="/content/model.pt")
download_file_to_local(path="/content/model.pt", localPath="<path-to-model.pt>", overwrite=true)
shutdown_runtime(reason="training finished")Flujo de cancelación recomendado:
check_background_command(name="train")
stop_background_command(name="train")
shutdown_runtime(reason="training cancelled")Notas importantes:
Descarga pesos, registros y otros artefactos antes de apagar. Los archivos en
/contentpueden perderse después de liberar el entorno de ejecución.shutdown_runtimelibera/desconecta la instancia activa del entorno de ejecución de CPU/GPU de Colab. No desinstala este servidor MCP y no cierra la pestaña del navegador.Después del apagado, el trabajo futuro en el entorno de ejecución debe reconectarse con
open_colab_browser_connection()yconnect_runtime(waitSeconds=180).
Transferencia de archivos locales
Prefiere las herramientas de ruta local al mover archivos entre esta máquina y Colab:
upload_local_file(localPath="<local-file>", path="/content/input.txt", overwrite=true)
download_file_to_local(path="/content/output.txt", localPath="<local-output>", overwrite=true)Las herramientas Base64 siguen estando disponibles para clientes que ya tienen contenido en memoria:
upload_file(path="/content/input.txt", contentBase64="...")
download_file(path="/content/output.txt")
upload_file_chunk(...)
download_file_chunk(...)
complete_upload(...)Grupos de herramientas
Conexión:
get_connection_info
Navegador, entorno de ejecución y acelerador:
open_colab_browser_connectionconnect_runtimecheck_runtimerestart_runtimeshutdown_runtimeset_runtime_accelerator
Shell y trabajos largos:
run_shell_commandstart_background_commandcheck_background_commandwatch_background_commandlist_background_commandsstop_background_commandtail_file
Archivos del entorno de ejecución:
upload_local_filedownload_file_to_localupload_filedownload_fileupload_file_chunkcomplete_uploaddownload_file_chunkstat_filelist_filesmake_directorydelete_file
Monitoreo de GPU y recursos:
check_gpuresource_usage_snapshotsample_gpu_usagestart_gpu_monitorread_gpu_monitorstop_gpu_monitor
Celdas de notebook:
get_cellsget_celladd_code_celladd_text_cellupdate_cellpatch_celldelete_cellmove_cellfind_cellsreplace_cellsrun_code_cellrun_code_cellsrun_cell_rangerun_all_cellscancel_queued_cellsget_cell_statuswait_for_cellsread_cell_outputswatch_cell_outputs
Entorno:
set_env_varsget_env_varsunset_env_varsload_env_filererun_env_setup_cells
Importación/exportación de notebook:
import_notebookexport_notebookupload_notebookalias paraimport_notebookdownload_notebookalias paraexport_notebook
Control del navegador
open_colab_browser_connection puede iniciar una instancia dedicada de Microsoft Edge, abrir Colab y conectar el frontend de Colab al servidor MCP local.
Valores predeterminados:
Puerto CDP:
9333, sobrescribir conCOLAB_MCP_EDGE_CDP_PORTPerfil de Edge:
~/.codex/edge-colab-mcp-profile, sobrescribir conCOLAB_MCP_EDGE_PROFILEEjecutable de Edge: detectado automáticamente, sobrescribir con
COLAB_MCP_EDGE_PATH
colabctl sigue estando disponible para diagnósticos y reparación manual:
uv run colabctl status
uv run colabctl connect
uv run colabctl smoke-mcp
uv run colabctl set-accelerator --accelerator GPULa automatización normal debería preferir las herramientas MCP sobre colabctl.
Verificación
Ejecuta pruebas locales:
uv run pytest
uv run python -m compileall srcEl flujo actual ha sido validado con una prueba de humo ResCNN completa solo con MCP:
selección de T4 a través de MCP
conexión del entorno de ejecución de Python a través de MCP
confirmación de
Tesla T4concheck_gpucarga de un script de entrenamiento local
entrenamiento con
start_background_commandvisualización de registros con
watch_background_commanddescarga de pesos con
download_file_to_localapagado del entorno de ejecución con
shutdown_runtime
Documentación
docs/USAGE.md: notas de uso
docs/TOOLS.md: inventario de herramientas
docs/EXAMPLES.md: ejemplos comunes
docs/TROUBLESHOOTING.md: guía de recuperación
docs/API_CONVENTIONS.md: convenciones de esquema y resultados
Gracias a los laoyou de linux.do por su apoyo. "Laoyou" es el término amistoso de la comunidad para referirse a compañeros respetados.
Notas de privacidad
El README utiliza marcadores de posición como <path-to-colab_mcp> y no incluye nombres de usuario locales, rutas de copia personal, tokens o artefactos del entorno de ejecución. Los artefactos de entrenamiento generados deben permanecer en artifacts/, que es ignorado por git.
Available Tools
59 toolsadd_code_cellA
Inserts a code type cell at the provided index and shifts existing cells. The resulting new cell id is returned.
Inputs: cellIndex (required), language (required), code (required).
add_text_cellA
Inserts a text type cell at the provided index and shifts existing cells. The resulting new cell id is returned.
Inputs: cellIndex (required), content (required).
cancel_queued_cellsA
Best-effort queued cell cancellation. Returns no-op status when Colab queue controls are not exposed through MCP.
Inputs: cellIds.
check_background_commandB
Checks through Colab Terminal the status of a background command started by start_background_command.
Inputs: name (required).
check_gpuA
Checks actual GPU availability in the connected Python runtime using nvidia-smi. Call open_colab_browser_connection and connect_runtime first. If no GPU is active this returns status=warning with remediation steps; do not rely on UI text alone.
Inputs: no named parameters.
check_runtimeA
Checks the current Colab runtime Python, platform, CPU, working directory, and selected package versions.
Inputs: no named parameters.
complete_uploadC
Moves a temporary chunked upload into its final runtime path through Colab's browser file upload API.
Inputs: uploadId (required), path (required), overwrite.
connect_runtimeB
Uses the controlled Colab browser to connect or reconnect the Colab Python runtime, then waits until terminal-backed runtime tools can see kernel.runtime.
Inputs: waitSeconds.
delete_cellB
Deletes the cell with the provided cell ID.
Inputs: cellId (required).
delete_fileC
Deletes a file or directory in the Colab runtime through Colab's contents API.
Inputs: path (required), recursive, force.
download_fileC
Reads a file from the Colab runtime through Colab's /files download API and returns base64 content without consuming a notebook cell execution slot.
Inputs: path (required), offset, maxBytes.
download_file_chunkB
Reads one base64 chunk from a file in the Colab runtime through Colab's /files download API.
Inputs: path (required), offset, maxBytes.
download_file_to_localA
Downloads a file from the Colab runtime to a local path on the machine running this MCP server. Prefer this over download_file when the target is a local file.
Inputs: path (required), localPath (required), overwrite, makeParents.
download_notebookB
Alias for export_notebook. Downloads the current Colab notebook cells to a local .ipynb file on the machine running Codex/MCP.
Inputs: path (required), includeOutputs.
export_notebookB
Exports the current Colab notebook cells to a local .ipynb file on the machine running Codex/MCP.
Inputs: path (required), includeOutputs.
find_cellsC
Finds cells by source or output text.
Inputs: query, regex, cellType, includeOutputs.
get_cellC
Returns a single cell by cell ID.
Inputs: cellId (required), includeOutputs.
get_cellsB
Gets a range of cells as JSON from the notebook.
Inputs: cellIndexStart, cellIndexEnd, includeOutputs.
get_cell_statusB
Returns best-effort execution status for selected cells or all cells.
Inputs: cellIds, includeOutputs.
get_connection_infoA
Returns the local Colab MCP WebSocket connection details and scratch URL for manually connecting a browser.
Inputs: no named parameters.
get_env_varsC
Reads environment variables from the Colab runtime with secret redaction in text output.
Inputs: names, redactPatterns.
import_notebookB
Imports cells from a local .ipynb file into the current Colab notebook.
Inputs: path (required), cellIndex, replaceExisting.
list_background_commandsA
Lists through Colab Terminal background commands registered by start_background_command.
Inputs: no named parameters.
list_filesC
Lists files in the Colab runtime through Colab's contents API.
Inputs: path, recursive, maxEntries.
load_env_fileC
Loads a local .env file and applies it to the current Colab Python runtime.
Inputs: path (required), persist, markerName.
make_directoryC
Creates a directory in the Colab runtime through Colab's contents API.
Inputs: path (required), parents, existOk.
move_cellA
Moves a cell to the provided index and shifts existing cells.
Inputs: cellId (required), cellIndex (required).
open_colab_browser_connectionA
Opens a connection to a Google Colab browser session and unlocks notebook editing tools. Returns a boolean representing whether the connection attempt succeeded
Inputs: no named parameters. Returns: result
patch_cellC
Partially updates a cell. Currently supports source/content updates.
Inputs: cellId (required), source, content.
read_cell_outputsC
Returns outputs for selected cells.
Inputs: cellIds (required), maxBytes, normalize.
read_gpu_monitorC
Reads recent JSONL samples from a GPU monitor file.
Inputs: name, path, lines.
replace_cellsC
Bulk inserts cells and optionally deletes existing cells first.
Inputs: cells (required), replaceExisting, cellIndex.
rerun_env_setup_cellsA
Reruns persisted environment setup cells created by set_env_vars with persist=true.
Inputs: markerName, includeOutputs.
resource_usage_snapshotA
Captures CPU, memory, disk, and GPU usage through Colab Terminal and optionally appends it to a JSONL file.
Inputs: savePath.
restart_runtimeA
Restarts the current Colab Python runtime. The notebook page stays open, but the runtime state and environment variables are reset.
Inputs: reason.
run_all_cellsC
Runs all code cells in notebook order.
Inputs: stopOnError, includeOutputs, timeoutSeconds.
run_cell_rangeC
Runs code cells in an inclusive index range.
Inputs: cellIndexStart (required), cellIndexEnd (required), stopOnError, includeOutputs, +1 more.
run_code_cellA
Executes the code in the cell with the provided cell ID. The cell must be a code cell type. The output of the cell execution is returned.
Inputs: cellId (required).
run_code_cellsB
Runs a list of code cells in order and returns per-cell outputs.
Inputs: cellIds (required), stopOnError, includeOutputs, timeoutSeconds.
run_shell_commandA
Runs a short shell command through Colab Terminal and waits for completion. Do NOT use this for training or long jobs; use start_background_command plus watch_background_command instead.
Inputs: command (required), timeoutSeconds, cwd.
sample_gpu_usageB
Samples GPU utilization with nvidia-smi through Colab Terminal and optionally writes JSONL.
Inputs: intervalSeconds, count, savePath.
set_env_varsB
Sets environment variables in the current Colab Python runtime by executing a generated setup cell.
Inputs: variables (required), persist, markerName, cellIndex.
set_runtime_acceleratorA
Uses the controlled Colab browser to choose an accelerator such as T4 GPU. Applying may restart/disconnect the runtime; always call open_colab_browser_connection, connect_runtime, then check_gpu afterwards.
Inputs: accelerator, apply.
shutdown_runtimeA
Disconnects and releases/unassigns the active Colab CPU/GPU runtime instance. Call this as the final cleanup step after training or long runtime work is complete or cancelled. Download needed weights, logs, and artifacts first because /content files can be lost after release. This does not uninstall the MCP server and does not close the browser tab.
Inputs: reason.
start_background_commandA
Preferred tool for training and long jobs. Starts a background shell command through Colab Terminal, writes stdout/stderr to a log file, and records status for watch_background_command.
Inputs: command (required), name, logPath, cwd.
start_gpu_monitorB
Starts a lightweight nvidia-smi background sampler through Colab Terminal that writes timestamped JSONL samples.
Inputs: name, intervalSeconds, savePath.
stat_fileC
Stats a path in the Colab runtime through Colab's runtime file APIs.
Inputs: path (required).
stop_background_commandC
Stops through Colab Terminal a background command started by start_background_command.
Inputs: name (required), signal.
stop_gpu_monitorB
Stops a GPU monitor started by start_gpu_monitor.
Inputs: name.
tail_fileB
Returns through Colab Terminal the last lines or bytes from a file in the Colab runtime, useful for background command logs.
Inputs: path (required), lines, maxBytes.
unset_env_varsC
Unsets environment variables in the current Colab Python runtime.
Inputs: names (required).
update_cellA
Overwrites the contents of the cell with the provided new content. The cell must already exist and is identified by its cell ID.
Inputs: cellId (required), content (required).
upload_fileB
Writes a base64 encoded file into the Colab runtime through Colab's browser file upload API without consuming a notebook cell execution slot.
Inputs: path (required), contentBase64 (required), overwrite, makeParents.
upload_file_chunkC
Appends or writes one base64 chunk to a temporary upload file in the Colab runtime through Colab's browser file upload API.
Inputs: uploadId (required), path (required), chunkBase64 (required), chunkIndex (required), +1 more.
upload_local_fileA
Uploads a file from the local machine running this MCP server to the Colab runtime. Prefer this over upload_file when the source is a local path.
Inputs: localPath (required), path (required), overwrite, makeParents.
upload_notebookB
Alias for import_notebook. Uploads cells from a local .ipynb file into the current Colab notebook.
Inputs: path (required), cellIndex, replaceExisting.
wait_for_cellsC
Polls cell status until every selected cell reaches one of the target states.
Inputs: cellIds (required), targetStates, timeoutSeconds, pollIntervalSeconds.
watch_background_commandC
Polls through Colab Terminal a background command and returns status plus recent log tail.
Inputs: name (required), lines.
watch_cell_outputsC
Polls selected cell outputs for a short period and returns the latest outputs.
Inputs: cellIds (required), timeoutSeconds, pollIntervalSeconds, maxBytes, +1 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 59 tools
Most tools have distinct purposes, but aliases like download_notebook/export_notebook and upload_notebook/import_notebook could confuse an agent. Additionally, multiple run cell tools (run_code_cell, run_code_cells, run_cell_range, run_all_cells) have overlapping functionality.
Tool names consistently use snake_case, but the verb patterns vary (e.g., run_ vs. start_ vs. watch_). Aliases like download_notebook vs. export_notebook break the pattern slightly.
59 tools is excessive for a Colab notebook server. The scope, though broad, could be covered with fewer tools by merging similar ones (e.g., file upload/download variants). This exceeds the 'too many' threshold of 25+.
The toolset covers notebook cell operations, runtime management, file handling, environment variables, GPU monitoring, and background commands. Minor gaps exist, such as a tool to list all notebooks or retrieve runtime metadata.
Related MCP Connectors
Shared memory MCP server for Claude Code, Codex, Gemini CLI and Cursor. Cited, editable.
Remote MCP server exposing your Node Command fleet (files, shell, processes, browser) to AI hosts.
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
Remote MCP server for supportsheep: run AI interviews and manage support content for your blog.
Related MCP Servers
- AlicenseBqualityDmaintenanceAn MCP server that bridges local AI agents to Google Colab notebooks, enabling execution of Python code and interaction with notebook states directly from the agent.1Apache 2.0
- AlicenseAqualityDmaintenanceMCP server that allocates Google Colab GPU runtimes (T4/L4) and executes Python code on them. Lets any MCP-compatible AI assistant run GPU-accelerated code without local GPU hardware.39MIT
- Apache 2.0
- FlicenseNot gradedqualityDmaintenanceEnables MCP clients to execute Python code on Google Colab GPU/TPU runtimes via the official Colab CLI, with session, file, and package management capabilities.-