Skip to main content
Glama
mlagents-mcp
by limam-B

mlagents-mcp

MCP server for controlling Unity ML-Agents training runs from Claude Code.

Launch, stop, resume, monitor, compare, and export ML-Agents training — all through natural conversation without leaving your editor.

Features

  • Training control — start, stop, resume runs as background processes

  • Instant checks — check training progress without blocking the conversation

  • Live monitoring — read TensorBoard metrics, reward curves, and training logs in real time

  • Run comparison — compare metrics across runs for hyperparameter tuning

  • Config management — read and deep-merge update YAML training configs

  • Model export — locate .onnx models and checkpoints

  • Two training modes — Unity Editor (interactive) and built executable (headless batch)

Related MCP server: projtool

Requirements

  • Python 3.10+

  • uv package manager

  • Unity ML-Agents mlagents-learn available in PATH (or via conda env)

  • Claude Code CLI

Installation

git clone https://github.com/limam-B/mlagents-mcp-server.git
cd mlagents-mcp-server
uv sync

Quick setup with Claude Code

# Register the MCP server:
claude mcp add --scope project --transport stdio mlagents-training \
  -- uv run --directory /path/to/mlagents-mcp-server mlagents-mcp

# Unregister (from all scopes to clean up stale configs):
claude mcp remove --scope local mlagents-training
claude mcp remove --scope user mlagents-training
claude mcp remove --scope project mlagents-training

# List registered servers:
claude mcp list

With environment variables

The server reads its configuration from environment variables. Add them to your .mcp.json (project-level) or pass them via the CLI:

{
  "mcpServers": {
    "mlagents-training": {
      "command": "uv",
      "args": ["run", "--directory", "/path/to/mlagents-mcp-server", "mlagents-mcp"],
      "env": {
        "MLAGENTS_PROJECT_ROOT": "/path/to/your/unity/project",
        "MLAGENTS_RESULTS_DIR": "results",
        "MLAGENTS_CONFIG_DIR": "config"
      }
    }
  }
}

With conda (if ML-Agents is installed in a conda env)

{
  "mcpServers": {
    "mlagents-training": {
      "command": "uv",
      "args": ["run", "--directory", "/path/to/mlagents-mcp-server", "mlagents-mcp"],
      "env": {
        "MLAGENTS_PROJECT_ROOT": "/path/to/your/unity/project",
        "MLAGENTS_RESULTS_DIR": "results",
        "MLAGENTS_CONFIG_DIR": "config",
        "MLAGENTS_CONDA_ENV": "mlagents",
        "MLAGENTS_CONDA_PATH": "/home/user/miniconda3"
      }
    }
  }
}

Environment variables

Variable

Default

Description

MLAGENTS_PROJECT_ROOT

.

Root directory of your Unity project

MLAGENTS_RESULTS_DIR

results

Training results directory (relative to project root)

MLAGENTS_CONFIG_DIR

config

Training config YAML directory (relative to project root)

MLAGENTS_CONDA_ENV

—

Conda environment name to activate before running mlagents-learn

MLAGENTS_CONDA_PATH

—

Path to conda installation (e.g. /home/user/miniconda3)

Tools (18)

Training control

Tool

Description

force_training

Launch a new training run (overwrites previous results). Blocks until ready by default.

stop_training

Gracefully stop a run (SIGINT, saves the model).

resume_training

Resume from checkpoint. Auto-reads config from previous run.

cleanup_processes

Kill orphaned mlagents-learn and Unity build processes not tracked by any active run.

Monitoring

Tool

Description

get_run_status

Status overview: reward trend, checkpoints, step progress.

get_metrics

Read TensorBoard scalars (reward, losses, learning rate, etc.).

get_training_logs

Tail live stdout/stderr from an active run.

list_runs

List all known runs with status filtering.

Comparison & export

Tool

Description

compare_runs

Compare a metric across multiple runs (min/max/final + trend).

export_model

Locate .onnx model files and checkpoints.

Configuration

Tool

Description

get_config

Read a YAML training config.

update_config

Deep-merge updates into a config (only specified keys change).

Wait & check

Tool

Default

Description

wait_for_first_metrics

Blocks

Blocks until first TensorBoard data point appears (~1-2 min).

wait_for_completion

Blocks

Blocks until training finishes. For automated run chaining (up to 4 hours).

check_step

Instant

Check if training reached a target step. Returns current progress.

check_reward

Instant

Check if mean reward reached a target. Returns current reward.

check_completion

Instant

Check if training finished. Returns current status and progress.

check_checkpoint

Instant

Check if new .onnx files appeared. Returns checkpoint list.

The check_* tools always return instantly — they never block the conversation. Use wait_for_completion when you want to block until a run finishes (e.g. to chain skill A → skill B automatically).

Two training modes

Editor mode (no env_path)

Training connects to the Unity Editor. force_training blocks until mlagents-learn prints "Listening on port... press Play", then you (or an AI agent) presses Play in Unity.

force_training(config_path="movement.yaml", run_id="Movement_v1")
# → blocks until "Listening on port 5004. Start training by pressing Play..."

Batch mode (with env_path)

Training launches a built executable directly — no Unity Editor needed. force_training blocks until the executable connects.

force_training(
    config_path="movement.yaml",
    run_id="Movement_v1",
    env_path="/path/to/Build.x86_64",
    num_envs=12,
    no_graphics=True,
)
# → blocks until "Connected to Unity environment"

Example workflow

A typical automated training session:

1. force_training(config, run_id, ...)     # launch, blocks until ready
2. wait_for_first_metrics(run_id)          # blocks until data flowing
3. wait_for_completion(run_id)             # blocks until training ends (hours)
4. export_model(run_id)                    # get checkpoint
5. update_config(next_skill, init_path=..) # chain checkpoint to next skill
6. [repeat from step 1 for next skill]

Steps 1-2 block briefly during startup. Step 3 blocks for the full duration (hours) — use this for automated chaining. For manual monitoring, use check_step/check_completion instead of step 3.

Development

# Install dev dependencies:
uv sync --group dev

# Lint:
uv run ruff check src/

# Format:
uv run ruff format src/

# Run the server directly (stdio):
uv run mlagents-mcp

Project structure

src/mlagents_mcp/
  server.py            # FastMCP app, all 18 tool definitions, entry point
  process_manager.py   # Subprocess launch/stop, log capture, port assignment
  metrics_reader.py    # TensorBoard event file parsing
  config_manager.py    # YAML config read/write/deep-merge
  run_registry.py      # Thread-safe run tracking + historical disk scan
  waiters.py           # Blocking wait logic for all wait_for_* tools
  types.py             # Shared dataclasses and enums

License

MIT

Available Tools

18 tools
check_checkpointA

Check if new .onnx checkpoint files appeared on disk. Always returns instantly with list of all checkpoints and any new ones.

Args: run_id: The run to check. known_checkpoints: List of checkpoint paths already known (from a previous call). New files = current minus these. If omitted, returns all checkpoints.

Inputs: run_id (required), known_checkpoints. Returns: object

check_completionA

Check if a training run has finished. Always returns instantly with current status, step, reward, and whether it completed.

Args: run_id: The run to check.

Inputs: run_id (required). Returns: object

check_rewardA

Check if mean cumulative reward reached a target threshold. Always returns instantly with current reward, step, and whether the target was reached.

Args: run_id: The run to check. target_reward: The reward threshold.

Inputs: run_id (required), target_reward (required). Returns: object

check_stepA

Check if training reached a target step count. Always returns instantly with current step, reward, and whether the target was reached.

Args: run_id: The run to check. target_step: The step count target.

Inputs: run_id (required), target_step (required). Returns: object

cleanup_processesA

Kill orphaned mlagents-learn and Unity build processes that are not tracked by any active run. Use this when force_training fails due to leftover processes occupying ports, or after a crash.

Inputs: no named parameters. Returns: object

compare_runsA

Compare a specific metric across multiple training runs (useful for hyperparameter tuning).

Args: run_ids: List of run IDs to compare. metric_key: The TensorBoard metric key to compare (e.g. 'Environment/Cumulative Reward'). last_n: Number of most recent data points per run to include in the trend. Use -1 for all.

Inputs: run_ids (required), metric_key (required), last_n. Returns: object

export_modelA

Locate .onnx model files and checkpoints for a training run.

Args: run_id: The run to query. behavior_name: Specific behavior (searches all if omitted). last_n: Number of most recent models/checkpoints to return. Use -1 for all.

Inputs: run_id (required), last_n, behavior_name. Returns: object

force_trainingA

Launch a new mlagents-learn training run as a background process. Always overwrites previous results for the same run_id. To continue from a checkpoint, use resume_training instead.

By default, blocks until ready: in editor mode (no env_path), waits until mlagents-learn says 'Listening on port... press Play'. In batch mode (with env_path), waits until the executable connects.

Args: config_path: Path to the YAML training config file. run_id: Unique identifier for this training run. env_path: Path to a built Unity environment executable. Omit to use the Unity Editor. num_envs: Number of parallel Unity environment instances. no_graphics: Disable graphics rendering for faster training. torch_device: PyTorch device (e.g. 'cuda', 'cpu', 'cuda:0'). seed: Random seed (-1 for random). time_scale: Unity time scale multiplier. base_port: Base port for Unity communication (auto-assigned if omitted). wait: Block until ready (default true). Editor mode: waits for 'press Play'. Batch mode: waits for connection. wait_timeout: Max seconds to wait when wait=true.

Inputs: run_id (required), config_path (required), seed, wait, +7 more. Returns: object

get_configA

Read a YAML training configuration file.

Args: config_path: Path to the config file (relative to config dir or absolute).

Inputs: config_path (required). Returns: object

get_metricsA

Read TensorBoard scalar metrics from a training run.

Args: run_id: The run to query. behavior_name: Specific behavior to read (auto-detected if omitted). metric_keys: Specific metric keys to read (defaults to reward, losses, LR). last_n: Number of most recent data points per metric (default 20). Use -1 for all.

Inputs: run_id (required), last_n, metric_keys, behavior_name. Returns: object

get_run_statusA

Get detailed status of a training run including step progress, reward trend, and checkpoints.

Args: run_id: The run to query. last_n_rewards: Number of recent reward data points to include in the trend. last_n_checkpoints: Number of recent checkpoints to include.

Inputs: run_id (required), last_n_rewards, last_n_checkpoints. Returns: object

get_training_logsA

Get recent stdout/stderr output from an active training run.

Args: run_id: The run to query. last_n_lines: Number of most recent log lines to return.

Inputs: run_id (required), last_n_lines. Returns: object

list_runsA

List known training runs with their status.

Args: status_filter: Filter by status: 'running', 'completed', 'failed', or 'stopped'. last_n: Number of most recent runs to return (default 20). Use -1 for all.

Inputs: last_n, status_filter. Returns: object

resume_trainingA

Resume a previously stopped/completed training run.

If config_path is not provided, reads the saved configuration.yaml from the previous run. By default, blocks until ready (same as force_training).

Args: run_id: The run_id to resume. config_path: Config file path (auto-detected from previous run if omitted). num_envs: Number of parallel Unity environment instances. no_graphics: Disable graphics rendering. torch_device: PyTorch device. time_scale: Unity time scale multiplier. wait: Block until ready (default true). Editor mode: waits for 'press Play'. Batch mode: waits for connection. wait_timeout: Max seconds to wait when wait=true.

Inputs: run_id (required), wait, num_envs, time_scale, +4 more. Returns: object

stop_trainingA

Gracefully stop a running training run (sends SIGINT so the model is saved).

Args: run_id: The run to stop. timeout: Seconds to wait for graceful shutdown before force-killing.

Inputs: run_id (required), timeout. Returns: object

update_configA

Deep-merge updates into an existing YAML config file. Only specified keys are changed.

Args: config_path: Path to the config file (relative to config dir or absolute). updates: Dictionary of updates to deep-merge into the config.

Inputs: updates (required), config_path (required). Returns: object

wait_for_completionA

Block until a training run finishes. Use this to chain runs automatically: start skill A, wait_for_completion, then start skill B. This WILL freeze the conversation until training ends or timeout. Default timeout is 4 hours.

Args: run_id: The run to wait for. timeout: Max seconds to wait (default 14400 = 4 hours). poll_interval: Seconds between internal status checks (default 60).

Inputs: run_id (required), timeout, poll_interval. Returns: object

wait_for_first_metricsA

Block until the training run produces its first TensorBoard metric data point. Use this right after starting training to know when data starts flowing. Typically takes 1-2 minutes.

Args: run_id: The run to watch. timeout: Max seconds to wait. poll_interval: Seconds between checks.

Inputs: run_id (required), timeout, poll_interval. Returns: object

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.9/5.0

    Scored across 18 tools

    Disambiguation4/5

    Most tools target distinct resources/actions: launching, stopping, resuming, config, waiting, checking, logging, comparing. A coupple of overlaps exist, especially check_completion vs. wait_for_completion and the various check_* tools vs. get_run_status, but descriptions clearly separate blocking/non-blocking and specific conditions.

    Naming Consistency5/5

    All tool names follow a consistent snake_case verb_noun pattern: force_training, stop_training, update_config, check_step, get_metrics, list_runs, export_model. There are no style mixes or vague one-word names.

    Tool Count3/5

    18 tools is in the heavier range and the count is inflated by several near-duplicate monitoring utilities: check_step, check_reward, check_completion, check_checkpoint, wait_for_completion, and wait_for_first_metrics could potentially be consolidated. Still, the coverage is understandable for a training lifecycle server.

    Completeness4/5

    The server covers most of the training lifecycle: launch, resume, stop, configure, monitor, wait, list, compare, and export models. Minor gaps exist, such as no explicit delete/cleanup for run artifacts besides process cleanup, but core workflows are not dead-end.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables ML researchers to manage experiments across local and remote AutoDL GPU instances, including experiment creation, training launch, run polling, and report writing via Claude Code.
      1
      MIT
    • F
      license
      Not graded
      quality
      B
      maintenance
      Enables LLMs to manage and run machine learning training jobs on a remote server, including syncing code, submitting experiments, monitoring progress, reading TensorBoard metrics, and receiving completion notifications.
      -
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables a Claude Desktop or Claude Code session to start, drive, and supervise interactive Claude Code CLI worker runs, including sending prompts, reading terminal output, waiting for completion, stopping runs, and managing settings and permissions.
      MIT