mujoco-mcp
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@mujoco-mcp load the pendulum sample and step it 100 times with control 0.2"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
mujoco-mcp
MCP server that lets clients load, inspect, and control MuJoCo models, with an optional native interactive window. Multiple independent named sessions, compact JSON responses, deterministic stepping, and real-time viewer playback. Supports stdio and Streamable HTTP. Headless use requires no display or GPU.
Use from another project (including KaizenHand)
This repository is the MuJoCo MCP infrastructure, not the consuming application. It provides physics, contact force/torque, per-step force guarding, seeded conditions/noise, trajectory capture, provenance, and full-state snapshots. The other project owns its MJCF model, control FSM/strategies, retry policy, incident storage, approvals, statistics, dashboard, and physical-rig adapter.
make install
make server-headless # HTTP MCP at http://127.0.0.1:8000/mcp
# If another server is already using 8000:
make server-headless PORT=8001 # http://127.0.0.1:8001/mcpConnect with Streamable HTTP, then load your project's model through mujoco_load_model(file_path=...). No preloaded demo or viewer is required. See the external-project integration guide for a runnable client, configuration fields, force semantics, trace/snapshot replay, and scope boundaries. Existing servers must be restarted to expose newly added tools; restarting discards their in-memory sessions.
Related MCP server: playtest-mcp
Connect on this Mac
The project environment is installed in .venv with MuJoCo 3.13.0, matching the installed DMG app. The Python package includes its own engine and native viewer. The MCP server opens a window sharing its model and state; it cannot attach to an already-open standalone MuJoCo.app window. You can use the same XML/MJB model file in either application.
Start the server in a terminal and leave it running:
./start.sh --transport streamable-http --port 8000 --viewer --sample pendulumConnect your MCP client with transport Streamable HTTP and URL http://127.0.0.1:8000/mcp. The repository's .mcp.json already points to this endpoint for clients that read that format. This is an MCP endpoint, not a browser dashboard. It is reachable from clients on this Mac; a cloud-hosted client cannot reach your Mac's loopback address.
The server starts with session main, displaying a paused pendulum. Try these tool calls:
mujoco_list_sessions({})
mujoco_set_running({"session_id":"main","running":true,"ctrl":[0.5]})
mujoco_set_running({"session_id":"main","running":false})
mujoco_step({"session_id":"main","nsteps":100,"ctrl":[0.2]})
mujoco_get_state({"session_id":"main"})Use the MCP play/pause tools for playback. State responses include viewer_open, running, and runtime_error. Closing the window pauses the session but keeps its state available; mujoco_open_viewer reopens it. One window per server is supported; close that viewer before opening another session. Reset pauses playback and clears runtime errors. Sessions are in memory and end when the server stops.
Verify the connection without changing the model:
.venv/bin/python projects/http_client.pyTo use your own model at startup:
./start.sh --transport streamable-http --viewer --model /absolute/path/to/robot.xmlCtrl+C stops the server and closes its viewer. Restart with the same command when needed; no login/background service is installed.
For clients that only support stdio, use projects/mcp-stdio.json. That configuration starts its own independent server and viewer when the client connects. Its absolute launcher path is configured for this checkout; update it if you move the project.
The launcher automatically uses mjpython on macOS, as required by the native passive viewer. The DMG app itself does not need to be running.
Install
uv sync --extra dev # recommended: reproduce the tested environment from uv.lock
# Or install with pip in a Python environment:
pip install . # runtime
pip install -e ".[dev]" # development + testsRequires Python >= 3.10; this checkout selects Python 3.12. Dependencies: mujoco, mcp, numpy. The MCP SDK is constrained to v1 because this server uses FastMCP; v2 has incompatible APIs.
Run
mujoco-mcp # stdio (default)
mujoco-mcp --transport streamable-http --port 8000 # HTTP, binds 127.0.0.1
./start.sh --viewer --sample cartpole # stdio + native viewer on macOS
./start.sh --transport streamable-http --viewer --play # HTTP + playing pendulumTools
Tool | Purpose | Key args |
| Create a session from a model | exactly one of |
| Joints, actuators, sensors, geoms, contact pairs, mocap bodies, options |
|
| Reset to configured experiment start, model default, or keyframe; clear stop/error |
|
| Advance physics, optionally setting ctrl first |
|
| Read state without stepping |
|
| Overwrite qpos / qvel / ctrl / time, then |
|
| Enumerate active sessions | — |
| Free a session |
|
| Display a session in a native MuJoCo window |
|
| Close the window and pause, retaining the model/state |
|
| Play/pause the visible session, optionally update controls |
|
| All external rigid contacts on a body subtree; world force and torque |
|
| Step with force-limit stop and optional trajectory recording |
|
| Set seeded conditions, friction, bias and observation noise; reset |
|
| Compiled-model/config/code hashes, versions, source label |
|
| Capture unrounded full integration state for continuation |
|
| Restore matching model/config/engine state and guard status |
|
Conventions:
Responses are compact JSON strings.
ctrlfollows actuator order. Forqpos/qvel, use joint types andqpos_adr/dof_adrfrommujoco_model_info: free and ball joints occupy multiple entries.ctrlis either a full vector in actuator order or{actuator_name: value}for a subset; it persists on the session until changed.includeselects state blocks:qpos,qvel,ctrl,sensors(the default four),sensors_raw(without configured observation noise),bodies(world-frame pos/quat),contacts(geom pairs, penetration depth, normal force; capped at 20). Wrench/guard calculations use all contacts, not this display cap.precision(default 5) rounds state views. Guarded traces use 9 decimals for state; wrench values and snapshots are unrounded. Use snapshots for exact continuation, not roundedget_stateresults.Batch physics into one call:
nsteps=500is 1 s at the default 0.002 timestep. Avoid step-per-call loops.Pause real-time playback before calling
mujoco_step. Its returned sensors/body poses are recomputed at the final state. Usemujoco_set_running(running=true, ctrl=...)to update controls during playback.Force limits apply only during
mujoco_step_guarded, not ordinary stepping/playback. Once tripped, the stop blocks every stepping path until reset (including experiment reconfiguration) or restoration of a pre-stop snapshot. Detection is at physics-step boundaries and does not guarantee zero overshoot or physical-robot safety.
Bundled samples
Sample | System | Actuators | Keyframes |
| torque-limited pendulum |
|
|
| cart with unactuated pole |
|
|
| planar 2-link arm (gravity-free) with tip site sensor |
| — |
| free box falling onto a plane (contact demo) | — | — |
Embedding in your orchestrator
projects/agent_client.py is a complete working loop: it spawns the server over stdio, loads the cartpole, and balances the pole from sensor feedback through nothing but MCP tool calls. Core pattern:
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
params = StdioServerParameters(command="mujoco-mcp")
async with stdio_client(params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
tools = (await session.list_tools()).tools
result = await session.call_tool(
"mujoco_step", {"session_id": "sim1", "nsteps": 500, "ctrl": [0.3]}
)To surface the tools to a Claude (or any tool-calling) model, map them 1:1 and route tool_use back through the session:
anthropic_tools = [
{"name": t.name, "description": t.description, "input_schema": t.inputSchema}
for t in tools
]
result = await session.call_tool(block.name, block.input)
tool_result_content = result.content[0].textErrors come back with isError=true and an actionable message (valid session ids, actuator order, allowed values), so they are safe to feed straight back to the model as tool_result with is_error=true.
Loading your own models
file_path: any MJCF.xml(relative includes/assets resolve normally) or compiled.mjb, resolved on the machine running the server.MuJoCo Menagerie:
git clone https://github.com/google-deepmind/mujoco_menagerie, thenfile_path=".../mujoco_menagerie/franka_emika_panda/scene.xml".xml_string: for models generated on the fly by the agent.
Configuration
Env var | Default | Effect |
| 16 | Max concurrent sessions |
| unset (any path) | Colon-separated allowlist of directories |
Claude Code / Claude Desktop
For Claude Code, the project's .mcp.json connects to the running HTTP server:
{"mcpServers":{"mujoco":{"type":"http","url":"http://127.0.0.1:8000/mcp"}}}For stdio clients such as Claude Desktop, copy the mujoco entry from projects/mcp-stdio.json into the client's MCP configuration. The client then launches its own server; the manually started HTTP server is not used. The launcher uses absolute paths, so it works even if the client starts in a different directory.
Notes
Deterministic manual stepping: same model + same reset + same ctrl/step sequence reproduces the trajectory. Real-time playback uses wall-clock scheduling and is not a deterministic control interface.
Divergence (non-finite state) is detected after stepping and returned as an error with recovery guidance instead of NaN payloads.
State lives in server memory; run one server process per trusted consumer. stdio has no auth; streamable HTTP binds
127.0.0.1— put a reverse proxy with auth in front before exposing it.
Tests
.venv/bin/python -m pytest
# Opens actual native windows; requires a logged-in desktop:
MUJOCO_MCP_TEST_VIEWER=1 .venv/bin/python -m pytest tests/test_viewer_integration.pyCovers every tool, error paths (unknown session/actuator/keyframe, wrong vector lengths, divergence, path allowlist), determinism, contact-force sanity, and an end-to-end stdio client session. Viewer checks cover shared state, real-time play/pause, window closure, session cleanup, and automatic pause on instability. The opt-in GUI integration test exercises the actual native window over MCP, including closing and reopening it.
Experiment tests cover seeded noise, atomic configuration, geom/pair friction, actuator bias, mocap poses, full-state snapshot continuation, non-cancelling contact loads, force-stop latching, and bounded trace sampling. Both stdio and an isolated HTTP server are exercised. A 100-trial headless box-drop batch checks transport and physics plumbing; it is not evidence that an external connector model or recovery strategy has been validated.
Available Tools
17 toolsmujoco_close_sessionADestructive
Close a session and free its model and data. The session_id becomes invalid immediately.
Returns JSON: {closed, remaining: [session_ids]}.
Inputs: session_id (required). Returns: result
mujoco_close_viewerAIdempotent
Close this session's window and pause playback, keeping its state loaded.
Inputs: session_id (required). Returns: result
mujoco_configure_experimentADestructiveIdempotent
Configure generic trial conditions and reset to the realized seeded start.
Close viewer first. Supports named geom friction [sliding,torsional,rolling],
named explicit pair_friction [sliding1,sliding2,torsional,rolling1,rolling2],
hinge/slide initial joint_offsets and Gaussian joint_noise_std (rad/m), mocap
body poses (m, wxyz), additive ctrl_bias in actuator input units, and named
sensor_noise_std in each sensor's units. Noise affects observations only;
physical state and force guarding remain raw. Missing options return to model
defaults. Repeating the same config reproduces initial conditions. metadata
stores caller tags such as trial_id/param_version, without enforcing policy.
Inputs: config (required), session_id (required). Returns: result
mujoco_get_provenanceARead-onlyIdempotent
Return compiled-model SHA-256, engine/server versions, code hash and experiment config.
Source label is always sim. The consuming project supplies its own strategy, parameter version and code commit; arbitrary caller tags are metadata only.
Inputs: session_id (required). Returns: result
mujoco_get_snapshotARead-onlyIdempotent
Get unrounded mjSTATE_INTEGRATION plus step/noise counters and guard status.
Includes act, warm-start, applied forces, mocap and other integration inputs,
beyond qpos/qvel. Persist this JSON in your project. Pause before capture.
Inputs: session_id (required). Returns: result
mujoco_get_stateARead-onlyIdempotent
Read the current state of a session without advancing physics.
Returns JSON with the requested blocks: qpos/qvel/ctrl (vectors in model order),
sensors ({name: value}), bodies ({name: {pos, quat}} world-frame), contacts
({ncon, listed, contacts: [{geom1, geom2, pos, dist, normal_force}]}, capped at 20).
Inputs: session_id (required), include, precision. Returns: result
mujoco_get_wrenchARead-onlyIdempotent
Measure ALL external contacts on a non-world body and its descendants.
Raw resultant force (N) and torque (N m) are in world axes. Torque is about
the requested body's origin. force_N sums contact magnitudes (opposing forces
do not cancel). This is contact-only, not a general wrist F/T sensor.
observed_force_xyz_N adds configured noise; raw force and guard stay unchanged.
Inputs: body_name (required), session_id (required). Returns: result
mujoco_list_sessionsARead-onlyIdempotent
List all active simulation sessions.
Returns JSON: {count, sessions: [{session_id, source, time, steps_taken, nq, nu}]}.
Inputs: no named parameters. Returns: result
mujoco_load_modelA
Load a MuJoCo model into a new simulation session. Provide exactly ONE of sample | file_path | xml_string.
Returns JSON: {session_id, source, nq, nv, nu, nsensor, nkey, timestep,
joints: [names], actuators: [names], sensors: [names], keyframes: [names]}.
The name arrays define the element order of qpos/qvel/ctrl vectors used by every other tool.
Next: mujoco_step to advance physics, mujoco_get_state to read, mujoco_model_info for ranges/types.
Inputs: sample, file_path, session_id, xml_string. Returns: result
mujoco_model_infoARead-onlyIdempotent
Detailed structure of a loaded model: joint types/ranges, actuator ctrlranges, sensors, bodies, options.
Returns JSON: {session_id, source, sizes: {nq, nv, nu, na, nbody, njnt, ngeom, nsensor, nkey},
options: {timestep, gravity, integrator},
joints: [{name, type, range|null, qpos_adr, dof_adr}],
actuators: [{name, ctrlrange|null, gear}],
sensors: [{name, type, dim}], bodies: [names], keyframes: [names]}.
Use before choosing ctrl values (respect ctrlrange) or interpreting qpos/qvel layout.
Inputs: session_id (required). Returns: result
mujoco_open_viewerAIdempotent
Open a native MuJoCo window sharing this session's model and state.
Starts paused; call mujoco_step or mujoco_set_running next. One window per
server: close the current viewer before displaying another session. This
opens a new controlled window; it does not attach to the standalone DMG app.
On macOS launch the server via start.sh or mjpython.
Inputs: session_id (required). Returns: result
mujoco_resetAIdempotent
Reset a session to its initial state (or a named keyframe) and zero the step counter.
Without a keyframe, restores the configured seeded start (if any), else model defaults.
Clears force guard and runtime errors. Identical full states and control sequences
reproduce trajectories with the same model, engine and stepping schedule.
Returns the post-reset state JSON (same shape as mujoco_get_state).
Inputs: session_id (required), keyframe, precision. Returns: result
mujoco_restore_snapshotADestructiveIdempotent
Restore a paused session; requires identical compiled model, config and engine version.
Restores exact integration state, step/noise counters and guard status. A snapshot taken before a force stop clears the latch; a tripped one retains it.
Inputs: snapshot (required), session_id (required). Returns: result
mujoco_set_runningAIdempotent
Play/pause the visible session at approximately real-time speed.
Open a viewer first. Optional ctrl changes persist; this can update controls
during playback. Pause before deterministic mujoco_step calls. Closing the
window or resetting pauses playback. Instability pauses automatically and
appears in runtime_error; call mujoco_reset to recover.
Inputs: running (required), session_id (required), ctrl. Returns: result
mujoco_set_stateAIdempotent
Overwrite parts of a session's state (qpos, qvel, ctrl, time), then recompute derived quantities.
Only provided fields change. Runs mj_forward so sensors/body poses reflect the new state
without advancing time. Returns the resulting state JSON. Useful for setting initial
conditions or visual replay. Use snapshots, not rounded state views, for exact continuation.
Inputs: session_id (required), ctrl, qpos, qvel, +2 more. Returns: result
mujoco_stepA
Advance the simulation. Optionally set actuator controls first; ctrl persists across later steps.
Returns the post-step state JSON: {session_id, time, steps_taken, qpos, qvel, ctrl, sensors, ...}
filtered by `include`. Batch steps in one call (e.g. nsteps=500 for 1s at timestep 0.002)
instead of many single-step calls. Errors and suggests mujoco_reset if the state diverges.
Inputs: session_id (required), ctrl, nsteps, include, +1 more. Returns: result
mujoco_step_guardedA
Advance a paused session, measuring all contacts after every physics step.
Stops at the first force-limit exceedance. guard.peak_force_N is the maximum
summed contact load on body_name (including descendants); opposite contact
forces do not cancel. World-frame resultant force and torque are also returned.
The guard detects an exceedance, it cannot guarantee zero overshoot. No hard
real-time or physical safety certification is implied. A tripped session is
latched until reset or snapshot restore. Optional record_every samples a JSON
trace every N steps (0 disables; maximum 2000 frames). Initial, terminal and
trip states are always captured; peak_force_N tracks all steps, not samples.
Persist returned trace/provenance in the consuming project for replay/evidence.
Inputs: body_name (required), session_id (required), force_limit (required), ctrl, +2 more. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 17 tools
Each tool maps to a distinct responsibility: session lifecycle, model inspection, stepping, state access, snapshots, viewer control, contact measurement, experiment configuration, and provenance. Even the paired tools like step/step_guarded and get_state/get_snapshot are clearly separated by their exact purpose and behavior.
All tools consistently use the mujoco_ prefix with a clear snake_case verb_noun pattern (load_model, get_state, close_session, set_running, restore_snapshot). There are no mixed naming conventions or vague generic verbs.
17 tools is slightly above the typical well-scoped range, but the count is justified by the breadth of the domain: session management, physics stepping, state access, snapshot handling, viewer control, and experiment configuration. A few tools could potentially be consolidated, but none feel redundant.
The tool set covers the full simulation lifecycle: load, inspect, step, read/write state, reset, snapshot/restore, run experiments, measure contacts, and close sessions. It also includes reproducibility-oriented tools like provenance and snapshots, so agents can execute and evidence a complete MuJoCo workflow without obvious dead ends.
Maintenance
Related MCP Connectors
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to control Unreal E…
QuLab MCP remote server (Streamable HTTP) for computational science and lab tools.
Remote MCP server for notes, tasks, kanban boards and docs - the Slates agentic workspace
JW3.ai remote MCP server for market reads and confirm-gated trading execution.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceMCP server exposing UniRoboSim evidence, simulation state, camera images, and optional explicit control of owned simulation sessions.-
- AlicenseNot gradedqualityCmaintenanceEnables MCP clients to run autonomous game playtesting, evaluate the agent against seeded bugs, list bug flags, and interactively reset, step, and view game sessions.MIT
- AlicenseNot gradedqualityBmaintenanceExposes a local simulated two-arm robot to TUI agents through stateful, serialized MCP tools that start trials, return camera images and joint state, jog the arm or move joints within bounded limits, and finish runs with scored metrics and native Inspect log paths. Agents can therefore drive and record robotic manipulation rollouts in Chrome-visible MuJoCo physics without any robot hardware or policy weights.1AGPL 3.0
- AlicenseNot gradedqualityBmaintenanceEnables MCP clients to connect to running Abaqus/CAE windows over multi-port TCP sockets, discover and switch sessions, and execute Python, model, job, ODB, and viewport operations targeted by session_id.MIT