colab-mcp
이 저장소는 Linux.do의 지원을 받았습니다.
Colab MCP
Google Colab을 개발, 셸, 파일 및 학습 런타임으로 제어하기 위한 로컬 우선 MCP 서버입니다.
중국어 문서: README.zh-CN.md
제공 기능
이 포크는 기존의 정적 Colab MCP 베이스라인을 확장하여 다음 기능을 제공합니다:
노트북 편집, 배치 실행, 상태 폴링 및 출력 읽기
제어된 Edge 브라우저 시작 및 Colab 프론트엔드 MCP 복구
connect_runtime을 통한 명시적 Python 런타임 연결T4 GPU 선택을 포함한 MCP 네이티브 런타임 가속기 전환
Colab 터미널 기반 셸 명령 및 백그라운드 작업
로컬 경로 파일 업로드/다운로드 도구
런타임 파일 목록/상태 확인/삭제/디렉토리 도구
GPU 확인, 스냅샷 및 모니터 작업
환경 변수 도우미 및 런타임 재시작/종료 도구
Related MCP server: mcp-server-colab-exec
프로젝트 구조
src/colab_mcp/: Python MCP 서버, Colab 세션 프록시, 런타임/브라우저 도구.tests/: 프록시, 도구 동작 및 웹소켓 서버 동작에 대한 단위 테스트.docs/: 사용법, 도구 목록, 예제, 문제 해결 및 API 규칙.TODO.md: 구현 체크리스트 및 후속 메모.
설정
uv sync --dev
uv run pytestMCP 서버 실행:
uv run colab-mcpMCP 클라이언트 구성:
{
"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"
}
}
}
}<path-to-colab_mcp>를 로컬 체크아웃의 절대 경로로 바꾸십시오.
런타임 준비 상태
브라우저 MCP가 연결되었다고 해서 Python 런타임이 준비되었다고 가정하지 마십시오. 셸, 파일, GPU 및 학습 도구는 실제 Colab 런타임과 터미널 소켓이 필요합니다.
결과 계약
도구는 구조화된 상태 필드를 사용합니다:
ok=true,status="ok": 알려진 경고 없이 작업이 완료됨.ok=false,status="warning": 필수 구성 요소 누락, 부분적/작업 없음 결과 또는 복구 가능한 상태.warnings및recommendedNextActions를 읽으십시오.ok=false,status="error": 실행 실패, 시간 초과, 0이 아닌 종료 코드 반환 또는 명시적 도구 오류 발생. 재시도하기 전에error,stdout,stderr및recommendedNextActions를 검사하십시오.
반환된 지침을 처리하지 않고 warning 또는 error 이후에 워크플로우를 계속하지 마십시오.
브라우저 및 런타임 흐름
두 개의 별도 연결 계층이 있습니다:
브라우저/프론트엔드 MCP 연결.
Colab Python 런타임 연결.
일반적인 런타임 작업:
open_colab_browser_connection()
connect_runtime(waitSeconds=180)GPU 작업:
open_colab_browser_connection()
set_runtime_accelerator(accelerator="T4 GPU", apply=true)
open_colab_browser_connection()
connect_runtime(waitSeconds=180)
check_gpu()가속기를 변경하면 런타임이 재시작되거나 연결이 끊길 수 있습니다. 항상 브라우저 MCP를 다시 연결한 다음 셸, 파일, GPU 또는 학습 도구를 사용하기 전에 connect_runtime을 호출하십시오.
일반적인 학습 흐름
모든 핵심 학습 단계는 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")학습 및 긴 작업에는 start_background_command를 사용하십시오. 학습에 run_shell_command를 사용하지 마십시오. 이는 짧고 제한된 명령을 위한 것입니다.
런타임 인스턴스 해제 또는 종료
작업이 완료되거나 취소되었거나 더 이상 CPU/GPU 리소스가 필요하지 않을 때는 항상 Colab 런타임을 해제하십시오:
shutdown_runtime(reason="training finished")권장 완료 흐름:
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")권장 취소 흐름:
check_background_command(name="train")
stop_background_command(name="train")
shutdown_runtime(reason="training cancelled")중요 참고 사항:
종료하기 전에 가중치, 로그 및 기타 아티팩트를 다운로드하십시오.
/content아래의 파일은 런타임이 해제된 후 손실될 수 있습니다.shutdown_runtime은 활성 Colab CPU/GPU 런타임 인스턴스를 해제/연결 해제합니다. 이 MCP 서버를 제거하거나 브라우저 탭을 닫지는 않습니다.종료 후 향후 런타임 작업을 수행하려면
open_colab_browser_connection()및connect_runtime(waitSeconds=180)으로 다시 연결해야 합니다.
로컬 파일 전송
이 머신과 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)Base64 도구는 이미 메모리에 콘텐츠가 있는 클라이언트를 위해 계속 사용할 수 있습니다:
upload_file(path="/content/input.txt", contentBase64="...")
download_file(path="/content/output.txt")
upload_file_chunk(...)
download_file_chunk(...)
complete_upload(...)도구 그룹
연결:
get_connection_info
브라우저, 런타임 및 가속기:
open_colab_browser_connectionconnect_runtimecheck_runtimerestart_runtimeshutdown_runtimeset_runtime_accelerator
셸 및 긴 작업:
run_shell_commandstart_background_commandcheck_background_commandwatch_background_commandlist_background_commandsstop_background_commandtail_file
런타임 파일:
upload_local_filedownload_file_to_localupload_filedownload_fileupload_file_chunkcomplete_uploaddownload_file_chunkstat_filelist_filesmake_directorydelete_file
GPU 및 리소스 모니터링:
check_gpuresource_usage_snapshotsample_gpu_usagestart_gpu_monitorread_gpu_monitorstop_gpu_monitor
노트북 셀:
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
환경:
set_env_varsget_env_varsunset_env_varsload_env_filererun_env_setup_cells
노트북 가져오기/내보내기:
import_notebookexport_notebookupload_notebook(import_notebook의 별칭)download_notebook(export_notebook의 별칭)
브라우저 제어
open_colab_browser_connection은 전용 Microsoft Edge 인스턴스를 시작하고, Colab을 열고, Colab 프론트엔드를 로컬 MCP 서버에 연결할 수 있습니다.
기본값:
CDP 포트:
9333,COLAB_MCP_EDGE_CDP_PORT로 재정의 가능Edge 프로필:
~/.codex/edge-colab-mcp-profile,COLAB_MCP_EDGE_PROFILE로 재정의 가능Edge 실행 파일: 자동 감지,
COLAB_MCP_EDGE_PATH로 재정의 가능
colabctl은 진단 및 수동 복구를 위해 계속 사용할 수 있습니다:
uv run colabctl status
uv run colabctl connect
uv run colabctl smoke-mcp
uv run colabctl set-accelerator --accelerator GPU일반적인 자동화는 colabctl보다 MCP 도구를 선호해야 합니다.
검증
로컬 테스트 실행:
uv run pytest
uv run python -m compileall src현재 흐름은 전체 MCP 전용 ResCNN 스모크 테스트로 검증되었습니다:
MCP를 통해 T4 선택
MCP를 통해 Python 런타임 연결
check_gpu로Tesla T4확인로컬 학습 스크립트 업로드
start_background_command로 학습watch_background_command로 로그 확인download_file_to_local로 가중치 다운로드shutdown_runtime으로 런타임 종료
문서
docs/USAGE.md: 사용 참고 사항
docs/TOOLS.md: 도구 목록
docs/EXAMPLES.md: 일반적인 예제
docs/TROUBLESHOOTING.md: 복구 지침
docs/API_CONVENTIONS.md: 스키마 및 결과 규칙
지원해 주신 linux.do의 노우(laoyou)분들께 감사드립니다. "노우(Laoyou)"는 존경받는 동료를 지칭하는 커뮤니티의 친근한 용어입니다.
개인정보 보호 참고 사항
README는 <path-to-colab_mcp>와 같은 자리 표시자를 사용하며 로컬 사용자 이름, 개인 체크아웃 경로, 토큰 또는 런타임 아티팩트를 포함하지 않습니다. 생성된 학습 아티팩트는 git에서 무시되는 artifacts/ 아래에 유지되어야 합니다.
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.-