Skip to main content
Glama

Repositoriesは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/: プロキシ、ツール動作、およびWebSocketサーバー動作のユニットテスト。

  • docs/: 使用方法、ツール一覧、例、トラブルシューティング、API規約。

  • TODO.md: 実装チェックリストとフォローアップメモ。

セットアップ

uv sync --dev
uv run pytest

MCPサーバーの実行:

uv run colab-mcp

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"
      }
    }
  }
}

<path-to-colab_mcp> をローカルチェックアウトの絶対パスに置き換えてください。

ランタイムの準備状況

ブラウザのMCPが接続されているからといって、Pythonランタイムが準備完了しているとは限りません。シェル、ファイル、GPU、トレーニングツールには、実際のColabランタイムとターミナルソケットが必要です。

結果の規約

ツールは構造化されたステータスフィールドを使用します:

  • ok=true, status="ok": 既知の警告なしで操作が完了。

  • ok=false, status="warning": 前提条件の欠如、部分的または無操作の結果、あるいは復旧可能な状態。warnings と recommendedNextActions を確認してください。

  • ok=false, status="error": 実行失敗、タイムアウト、ゼロ以外の終了コード、または明示的なツールエラー。再試行の前に error、stdout、stderr、および recommendedNextActions を確認してください。

warning または error の後に、返された指示に従わずにワークフローを続行しないでください。

ブラウザとランタイムのフロー

2つの独立した接続レイヤーがあります:

  1. ブラウザ/フロントエンドMCP接続。

  2. 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_connection

  • connect_runtime

  • check_runtime

  • restart_runtime

  • shutdown_runtime

  • set_runtime_accelerator

シェルと長時間ジョブ:

  • run_shell_command

  • start_background_command

  • check_background_command

  • watch_background_command

  • list_background_commands

  • stop_background_command

  • tail_file

ランタイムファイル:

  • upload_local_file

  • download_file_to_local

  • upload_file

  • download_file

  • upload_file_chunk

  • complete_upload

  • download_file_chunk

  • stat_file

  • list_files

  • make_directory

  • delete_file

GPUとリソース監視:

  • check_gpu

  • resource_usage_snapshot

  • sample_gpu_usage

  • start_gpu_monitor

  • read_gpu_monitor

  • stop_gpu_monitor

ノートブックセル:

  • get_cells

  • get_cell

  • add_code_cell

  • add_text_cell

  • update_cell

  • patch_cell

  • delete_cell

  • move_cell

  • find_cells

  • replace_cells

  • run_code_cell

  • run_code_cells

  • run_cell_range

  • run_all_cells

  • cancel_queued_cells

  • get_cell_status

  • wait_for_cells

  • read_cell_outputs

  • watch_cell_outputs

環境:

  • set_env_vars

  • get_env_vars

  • unset_env_vars

  • load_env_file

  • rerun_env_setup_cells

ノートブックのインポート/エクスポート:

  • import_notebook

  • export_notebook

  • upload_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 でランタイムをシャットダウン

ドキュメント

linux.doの老友(Laoyou)のサポートに感謝します。「老友」とは、コミュニティ内で尊敬される仲間を指す親しみを込めた言葉です。

プライバシーに関する注意

このREADMEでは <path-to-colab_mcp> などのプレースホルダーを使用しており、ローカルのユーザー名、個人のチェックアウトパス、トークン、ランタイム成果物は含まれていません。生成されたトレーニング成果物は artifacts/ 配下に保持されるべきであり、これはgitによって無視されます。

Available Tools

59 tools
add_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

    B3/5.0

    Scored across 59 tools

    Disambiguation4/5

    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.

    Naming Consistency4/5

    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.

    Tool Count2/5

    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+.

    Completeness4/5

    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

    Related MCP Servers