The agent loop, embodied. A tool-using runtime + fail-closed safety pipeline + sim-first execution harness for embodied AI.
pip install ghostloop==1.1.0 Copy PIP instructions
A tool-using agent runtime, fail-closed safety pipeline, statistically-rigorous bench harness, and sim-first execution layer for embodied AI. Sister project to GhostLM.
Now live: pip install ghostloop · interactive demo · 12 releases · 411 tests · MIT.
Robotics in 2026 has two healthy ecosystems and a missing middle.
Nobody ships the layer in between: a runtime where a model emits high-level intents like move_to(0.4, 0.2, 0.1) or pick("widget-7"), those intents flow through a fail-closed safety pipeline, the survivors execute on a backend (sim or hardware), and every step is captured in a structured trace that can be replayed, audited, scored, mined, counterfactually re-played, or causally analysed.
That layer is ghostloop. The shape is borrowed from GhostAgent in GhostLM: tool registry, policy gates, structured trace, paired-comparison eval. The novel piece is binding it to robot primitives instead of CVE lookups, making the runtime backend-agnostic so the same agent loop drives a mock today, MuJoCo / PyBullet / Gymnasium right now, and ROS 2 / direct hardware later, and adding a layer of post-hoc analysis tooling (counterfactual replay, causal attribution, LLM-as-judge, property mining, adversarial fuzzing) that no other robotics framework ships.
policy registry pipeline backend post-hoc emits resolves gates executes analysis user goal ┌────────┐ ┌──────────┐ ┌──────────────┐ ┌──────────┐ ┌─────────────────┐ ────────► │ Intent │ ► │ Primitive │ ► │PolicyPipeline│ ► │ Backend │ ► │ counterfactual │ └────────┘ └──────────┘ └──────────────┘ └──────────┘ │ causal │ │ │ LLM-judge │ ▼ │ property mining │ ┌──────────────────────┐ │ adversarial │ │ Trace (JSONL) │ ───► │ trace query DSL │ └──────────────────────┘ │ energy ledger │ │ └─────────────────┘ ▼ ┌────────────────────────────────────┐ │ Bench: Wilson CI + McNemar + │ │ Cohen's h + Sim2Real transfer gap │ └────────────────────────────────────┘ Type Role Intent High-level structured command emitted by a policy: name, args, rationale. Primitive Backend-bound callable. Has a name, description, arg schema (LLM-tool-card friendly). PolicyPipeline Ordered list of PolicyGates. Fail-closed: any deny short-circuits. Backend Execution adapter. MockBackend / MuJoCoBackend / PyBulletBackend / GymnasiumBackend / ROS2Backend / RandomizedBackend. Trace Append-only event log with state_before / state_after / decision / result per step. JSONL writer + replay + query DSL. LLMPolicy / VLAPolicy Bridge any OpenAI-compatible chat endpoint or VLA action head to the registry. Mission DAG of Steps with prerequisites + retry semantics. Kahn-validated. bench Episode harness with Wilson 95% CIs, McNemar exact p, Cohen's h, paired comparison, sim2real transfer gap. properties Declarative invariants over traces, Always / Eventually / Until STL combinators + auto-mined candidates. judges LLM-as-judge + heuristic rule-based trace scoring. training Constrained-MDP rollout collector + Lagrangian multiplier + HER relabeling. New in v1.1.0 Real Cartesian control on MuJoCo arms. move_to on a UR5e or Panda now solves damped least-squares IK and drives the position actuators with gravity compensation (0.1 mm tracking). Unreachable targets fail closed with an ERROR and the arm does not move. Before 1.1, move_to on an arm wrote x/y/z into the first three joint angles. Backend plugin registry. create_backend("mujoco:ur5e"), ghostloop backends, and a ghostloop.backends entry-point group so other simulators ship adapters as their own packages. See docs/BACKENDS.md. Conformance kit. ghostloop.testing.assert_backend_conforms(spec) checks the properties the bench relies on: honest move_to results, fail-closed unreachable targets, NaN rejection, determinism. Cross-backend paired bench. ghostloop xbench --a mujoco:ur5e --b runs the same seeded episodes on two backends through a shared canonical workspace and writes a paired report (Wilson CIs, McNemar, Cohen's h, final-position divergence in mm), full provenance, and one JSONL trace per episode per side. Seeded, tolerance-aware presets. Every preset takes seed, tolerance and jitter; new preset_workspace_grid_27. Non-finite argument rejection. NaN compares false against every bound, so GeofenceGate, ObstacleAvoidanceGate and ForceCapGate allowed x=nan (including the string "nan" an LLM can emit). Every PolicyPipeline now denies NaN/inf arguments before any gate runs, and those gates are fixed on their own too. Native Claude policy. ClaudePolicy uses the official Anthropic SDK (pip install ghostloop[anthropic]) with server-side refusal fallback, prompt caching, one primitive per step and per-episode cost accounting. spend_summary(results) reports cost per completed task. OpenAI-compatible policy fixes. Tool results now answer the real tool_call_id (strict endpoints rejected the old placeholder), schemas carry real JSON types and optional arguments, token usage is tracked, and LLMPolicyConfig.for_provider(...) presets common endpoints. A concrete example of what the cross-backend bench is for: the same UR5e with gravity compensation turned off sags about 9 mm. At a 3.5 mm success radius that takes workspace_grid_27 from 81/81 to 7/81 (McNemar p = 1e-22), which is exactly the kind of engine sensitivity you want surfaced before trusting a sim result.
ghostloop xbench --preset workspace_grid_27 --a mujoco:ur5e --b mujoco:ur5e \ --b-arg gravity_compensation=false --seeds 0 1 2 --out-dir xbench-out What ships 80+ modules across twelve releases. Highlights:
13 abstractions in core.py (Intent / Primitive / Result / Decision / PolicyGate / PolicyPipeline / Backend / MockBackend / TraceEvent / Trace / Runtime / Registry / DecisionAction). async_runtime.py mirrors them with awaitable gates + a control_loop(rate_hz).
DenyListGate, RateLimitGate, GeofenceGate, ForceCapGate, HumanInTheLoopGate, ObstacleAvoidanceGate, RetryPolicy, CooldownGate, TimeWindowGate, ActionSmoothingGate (velocity / acceleration limits), plus the LLMPolicy, ClaudePolicy and VLAPolicy adapters. All fail-closed, and every pipeline rejects NaN/inf arguments before the first gate.
All of them are built by spec through create_backend(...) / ghostloop backends; third-party simulators register through the ghostloop.backends entry point.
WorkspaceModel with axis-aligned boxes + spheres, HalfSpace / ConvexPolytope / signed_distance for SDF queries, workspace_from_urdf(...) to auto-build from a URDF, plus project_to_workspace / project_to_sdf for safe-action repair when a policy violates constraints.
There are three ways to run ghostloop, in order of effort. Start with the zero-install path, prove the safety pipeline, then promote to your real arm.
git clone https://github.com/joemunene-by/ghostloop cd ghostloop # Run the canonical pick-and-place demo on MockBackend. PYTHONPATH=. python3 examples/pick_and_place.py # Run a paired-comparison bench (Wilson CI + McNemar + Cohen's h). PYTHONPATH=. python3 examples/bench_with_without_geofence.py # Full test suite: 411 tests; backend and model tests skip cleanly without their extras. PYTHONPATH=. python3 -m pytest tests/ No dependencies beyond Python 3.10+. This proves the runtime, the safety pipeline, the bench harness, and the trace recorder, exactly the same code you'll point at a real arm later.
ghostloop ships a single MCP server (examples/mcp_robot.py) that works with every MCP-aware client, the protocol is universal, so the same server speaks to Claude Desktop, Cursor, Continue, Cline, Zed, Gemini CLI, and any future client. Pick what you control via GHOSTLOOP_PROFILE:
Each preset bundles morphology-appropriate primitives, conservative workspace + force + velocity caps, HITL on the dangerous primitives, and a robot-specific instructions block the LLM gets as a system prompt. See examples/custom_robot.yaml for the YAML schema and examples/custom_robot_primitives.py for how to plug in your own actions (dispense_pill, alert_nurse, whatever your hardware does) without forking ghostloop.
Two transports, picked via GHOSTLOOP_TRANSPORT:
Step 1. Verify the example boots (any OS, any profile):
# Default (Franka arm) python3 examples/mcp_robot.py --selfcheck # Quadruped GHOSTLOOP_PROFILE=spot python3 examples/mcp_robot.py --selfcheck # Drone GHOSTLOOP_PROFILE=tello python3 examples/mcp_robot.py --selfcheck # Custom YAML GHOSTLOOP_PROFILE=examples/custom_robot.yaml python3 examples/mcp_robot.py --selfcheck Step 2. Install the MCP transport package:
pip install ghostloop[mcp] # or: pip install mcp Step 3. Wire it into your client. The same { command, args, env } block works for every desktop MCP client, only the path to the config file differs:
Paste this block into the config file (replace the absolute path; pick a profile that matches your robot):
{ "mcpServers": { "ghostloop": { "command": "python3", "args": ["/absolute/path/to/ghostloop/examples/mcp_robot.py"], "env": { "GHOSTLOOP_PROFILE": "franka_arm", "GHOSTLOOP_BACKEND": "mock", "GHOSTLOOP_TRANSPORT": "stdio", "GHOSTLOOP_INSTRUCTIONS": "Optional: extra robot-specific guidance appended to the profile's instructions block." } } } } On Windows, swap python3 for python (or the absolute path to your interpreter, e.g. C:\Python313\python.exe). On macOS, use python3 from Homebrew or pyenv. Continue + Zed use YAML / JSONC respectively but the field shape is identical.
Step 4. Restart the client. New conversations get the tools: list_primitives, step, move_to(x, y, z), pick(object_id), place(), scan(radius), state, recent_trace(n). Try: "Use the ghostloop tools to move to (0.4, 0.0, 0.5), then scan with radius 0.3, then move to (0.6, 0.2, 0.5)." Watch the geofence reject targets outside [-0.6, 0.6].
Upgrade from mock to real physics (MuJoCo), one env var:
"env": { "GHOSTLOOP_BACKEND": "mujoco", "GHOSTLOOP_MUJOCO_MODEL": "/absolute/path/to/franka_panda.xml" } (pip install ghostloop[mujoco] first.)
"env": { "GHOSTLOOP_BACKEND": "ros2", "GHOSTLOOP_ROS2_NODE": "ghostloop_arm", "GHOSTLOOP_CMD_VEL": "/franka/cmd", "GHOSTLOOP_JOINT_STATES": "/franka/joint_states", "GHOSTLOOP_FORCE_TORQUE": "/franka/wrench" } Prerequisites: ROS 2 (apt install ros-humble-desktop on Ubuntu, the Robotology Mac install on macOS, WSL2 + Ubuntu on Windows), your arm's ROS 2 driver running, and source /opt/ros/humble/setup.bash (or setup.zsh / setup.ps1) in the same shell that launches the client so the subprocess inherits $AMENT_PREFIX_PATH.
Before pointing this at a real robot: edit your profile (or copy a preset to YAML and tweak it), set workspace_bounds / max_force_n / max_velocity / max_acceleration to your hardware's safe envelope, list dangerous primitives under hitl_primitives so the operator approves each call interactively, and write robot-specific guidance into the instructions: block (e.g. "never reach behind the base", "battery below 20% triggers automatic land"). Read the trace logs for the first dozen episodes; relax HITL only after you trust the model's behaviour.
Two ways to add a robot ghostloop doesn't already know about:
A. YAML profile (no Python required), copy examples/custom_robot.yaml, edit it, and point GHOSTLOOP_PROFILE at the path. The schema covers categories of standard primitives, your own custom primitives, composite macros, instructions for the LLM, workspace + force + velocity caps, denied / HITL operations, and the backend kind. The shipped sample defines a hospital medication-delivery robot, mobile base + arm, with custom dispense_pill and alert_nurse primitives and a deliver_room macro composed from existing primitives:
name: medbot_floor3 morphology: mobile_arm categories: [mobile_base, dexterous, sensing, generic] instructions: | You are MedBot, hospital floor-3 medication delivery. NEVER drive faster than 0.4 m/s. ALWAYS stop before extending the arm. ... workspace_bounds: [[-15, -15, 0], [15, 15, 1.6]] max_velocity: 0.4 hitl_primitives: [set_gripper, dispense_pill] custom_primitives: - module: examples.custom_robot_primitives factory: dispense_pill - module: examples.custom_robot_primitives factory: alert_nurse composites: - name: deliver_room steps: [goto, take_photo, dispense_pill, alert_nurse] backend: kind: ros2 kwargs: { node_name: medbot, cmd_vel_topic: /medbot/cmd_vel } B. Code, build a RobotProfile programmatically. Useful when your robot needs runtime state (a calibration matrix, a credential, dynamically-resolved topic names) that doesn't fit YAML:
from ghostloop.profiles import RobotProfile, build_runtime_from_profile from ghostloop.primitives import drive, set_gripper from my_robot.primitives import dispense_pill, alert_nurse profile = RobotProfile( name="medbot", morphology="mobile_arm", primitives=[drive(), set_gripper(), dispense_pill(), alert_nurse()], instructions="You are MedBot...", workspace_bounds=((-15, -15, 0), (15, 15, 1.6)), max_velocity=0.4, hitl_primitives=["dispense_pill"], backend_kind="ros2", backend_kwargs={"node_name": "medbot", "cmd_vel_topic": "/medbot/cmd_vel"}, ) runtime = build_runtime_from_profile(profile) Custom Primitive factories follow a stable contract: a function returning Primitive(name, call, description, arg_schema). The call body talks to your hardware however you need it to, ROS 2 publisher, vendor SDK, raw serial, REST endpoint. See examples/custom_robot_primitives.py for two worked examples (dispense_pill, alert_nurse).
For mobile chat apps (and any client that doesn't run on the same machine as the robot), run ghostloop's MCP server as a long-running HTTP service on the robot host:
# macOS / Linux GHOSTLOOP_BACKEND=mock GHOSTLOOP_TRANSPORT=streamable-http \ GHOSTLOOP_HOST=0.0.0.0 GHOSTLOOP_PORT=8765 \ python3 examples/claude_desktop_mcp_arm.py # Windows PowerShell $env:GHOSTLOOP_TRANSPORT='streamable-http'; $env:GHOSTLOOP_HOST='0.0.0.0'; $env:GHOSTLOOP_PORT='8765' python examples\claude_desktop_mcp_arm.py Then configure remote-MCP-capable clients with the URL form (no command/args):
{ "mcpServers": { "ghostloop": { "url": "http://your-robot-host.local:8765/mcp" } } } Mobile MCP clients (Claude iOS once it ships remote MCP, plus the growing crop of third-party MCP-aware iOS / Android chat apps) connect via the same URL, no app-side install. For a custom mobile app, use any MCP TypeScript / Swift / Kotlin SDK from modelcontextprotocol.io. The HTTP wire format is the same.
Bind to 0.0.0.0 only on a private network or behind authentication. The default 127.0.0.1 is loopback-only (safer). For internet-exposed setups, put a reverse proxy with TLS + auth in front, or use the production dashboard's StaticTokenAuth pattern.
Already have a model running and don't want to bother with MCP? examples/direct_llm_arm.py skips the protocol entirely and uses ghostloop's LLMPolicy to drive any OpenAI-compatible chat endpoint via native function calling. Tested against:
OPENAI_BASE_URL=https://api.openai.com/v1 OPENAI_API_KEY=sk-... \ OPENAI_MODEL=gpt-4o-mini \ python3 examples/direct_llm_arm.py # Or local Ollama: OPENAI_BASE_URL=http://localhost:11434/v1 OPENAI_API_KEY=ollama \ OPENAI_MODEL=qwen2.5:14b \ python3 examples/direct_llm_arm.py Same Backend choice (Mock / MuJoCo / ROS 2), same safety pipeline, same trace recorder. Only the LLM-to-tool plumbing differs: in-process via LLMPolicy instead of MCP wire protocol.
For everything else, bench harnesses, training loops, post-hoc analysis, use ghostloop as a library. Examples below.
from ghostloop import Intent, MockBackend, PolicyPipeline, PrimitiveRegistry, Runtime from ghostloop.policies import GeofenceGate, LLMPolicyConfig, llm_policy_loop from ghostloop.primitives import move_to, pick, place, scan registry = PrimitiveRegistry([move_to(), scan(), pick(), place()]) runtime = Runtime( backend=MockBackend(), registry=registry, policy_pipeline=PolicyPipeline(gates=[ GeofenceGate(min_corner=(-1, -1, 0), max_corner=(1, 1, 1)), ]), ) summary = llm_policy_loop( registry=registry, runtime=runtime, goal="Pick widget-7 from (0.4, 0.2, 0.1) and place it at (-0.4, 0.2, 0.1).", config=LLMPolicyConfig(base_url="http://localhost:11434/v1", model="qwen2.5:14b"), max_steps=16, ) runtime.trace.write_jsonl("episode.jsonl") Drive Claude natively from ghostloop.policies import ClaudePolicy, ClaudePolicyConfig, llm_policy_loop policy = ClaudePolicy(registry=registry, config=ClaudePolicyConfig(effort="medium")) summary = llm_policy_loop(registry, runtime, goal="Reach (0.4, 0.2, 0.1), then scan.", policy=policy) print(summary["terminated"], summary["usage"], summary["cost_usd"]) Defaults to claude-opus-5-5 with server-side refusal fallback on. Set fallbacks=False for platforms that don't support it (Bedrock, Vertex, Foundry).
from ghostloop import PolicyPipeline, PrimitiveRegistry, Runtime, Intent from ghostloop.backends import create_backend binding = create_backend("mujoco:ur5e") # Menagerie model, IK control, gravity comp runtime = Runtime(backend=binding.backend, registry=PrimitiveRegistry(binding.primitives), policy_pipeline=PolicyPipeline()) runtime.step(Intent("move_to", {"x": 0.5, "y": 0.2, "z": 0.3})) # metres, robot base frame runtime.step(Intent("move_to", {"x": 3.0, "y": 0.0, "z": 0.0})) # ERROR: unreachable, arm stays put Models from the MuJoCo Menagerie drop in directly. UR5e, UR10e and Panda have IK defaults; any other MJCF works with MuJoCoBackend(model_path=..., site=..., control="ik").
from ghostloop.bench.catalogue import PRESETS from ghostloop.bench.cross import cross_backend_compare report = cross_backend_compare(PRESETS["reach_8"], "mujoco:ur5e", "yoursim:ur5e", seeds=[0, 1, 2], tolerance=0.01) report.write("xbench-out") # report.md, report.json, traces/a/*.jsonl, traces/b/*.jsonl Both sides run the same seeded targets in a canonical frame mapped onto the embodiment's workspace, so episodes pair one to one. Any registered backend works; see docs/BACKENDS.md to add one.
The thesis: as VLA models become the policy substrate, the runtime around them needs the same rigor we already apply to LLM tool use, plus the analytical tooling, counterfactuals, causal attribution, judge models, that LLM safety has been building for years. ghostloop is that runtime.
Built by Joe Munene at Complex Developers. Sibling to GhostLM, secure-mcp, ghostguard, CyberBench.
All 2 files in this release have provenance metadata.
dev mujoco pybullet gym ros2 mcp anthropic otel dashboard
robotics agent embodied-ai vla tool-use policy-gates safety mujoco ros2 mcp
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 20, 2026.
All 2 files in this release have been uploaded with provenance metadata.
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.




