From 24a70e84a86f5ad315610e7bb023ffc45ea7a907 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 21:57:09 +0200 Subject: [PATCH] horizon-ctl: help for every command, launch from the launcher, MCP server One command table drives horizon-ctl help, COMMAND --help (with examples) and the MCP tools. Replies stay one JSON line; errors are error objects with exit status 1 (game), 2 (usage) or 3 (unreachable). script runs a file or stdin with shell-like quoting. launch finds the game beside horizon-ctl or the newest launcher install (--version, --game), with its prepared resources and the game home, and --wait waits for the world. horizon-ctl mcp serves MCP over stdio in the launcher's style, one tool per command, with the screenshot returned as an image. Existing commands and replies are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../src/bin/horizon-ctl/commands.rs | 578 +++++++++++++++++ .../src/bin/horizon-ctl/launch.rs | 386 ++++++++++++ .../src/bin/horizon-ctl/main.rs | 582 +++++++++++++----- .../horizon-client/src/bin/horizon-ctl/mcp.rs | 238 +++++++ 4 files changed, 1635 insertions(+), 149 deletions(-) create mode 100644 crates/horizon-client/src/bin/horizon-ctl/commands.rs create mode 100644 crates/horizon-client/src/bin/horizon-ctl/launch.rs create mode 100644 crates/horizon-client/src/bin/horizon-ctl/mcp.rs diff --git a/crates/horizon-client/src/bin/horizon-ctl/commands.rs b/crates/horizon-client/src/bin/horizon-ctl/commands.rs new file mode 100644 index 000000000..91969d0c9 --- /dev/null +++ b/crates/horizon-client/src/bin/horizon-ctl/commands.rs @@ -0,0 +1,578 @@ +//! Every command horizon-ctl knows: its usage, help, examples and arguments. +//! The same table prints `help`, checks `COMMAND --help` and describes the +//! MCP tools, so the CLI and the MCP server always offer the same commands. +use serde_json::{Map, Value, json}; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Ty { + Int, + Num, + Str, + Bool, + /// One of these words. + Enum(&'static [&'static str]), + /// The rest of the line, spaces included. + Rest, +} + +#[derive(Clone, Copy)] +pub struct Param { + pub name: &'static str, + pub ty: Ty, + pub required: bool, + /// Sent as `--name value` (`--name` alone for booleans), not by position. + pub flag: bool, + pub help: &'static str, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Group { + Session, + Observe, + Move, + Act, + Screens, + World, + Scripting, +} +impl Group { + pub const ALL: [Group; 7] = [ + Group::Session, + Group::Observe, + Group::Move, + Group::Act, + Group::Screens, + Group::World, + Group::Scripting, + ]; + pub fn title(self) -> &'static str { + match self { + Group::Session => "Session", + Group::Observe => "Observe (JSON state)", + Group::Move => "Move and look", + Group::Act => "Act on the world", + Group::Screens => "Screens, menus and chat", + Group::World => "World and cheats", + Group::Scripting => "Scripting and benchmarks", + } + } +} + +pub struct Cmd { + pub name: &'static str, + /// What the game receives instead of `name` (aliases such as look-at-block). + pub wire: Option<&'static str>, + pub group: Group, + pub usage: &'static str, + pub summary: &'static str, + pub details: &'static str, + pub examples: &'static [&'static str], + pub params: &'static [Param], + /// Offered as an MCP tool. + pub mcp: bool, + /// Runs in horizon-ctl itself, not in the game. + pub local: bool, +} + +const fn p(name: &'static str, ty: Ty, help: &'static str) -> Param { + Param { + name, + ty, + required: true, + flag: false, + help, + } +} +const fn opt(name: &'static str, ty: Ty, help: &'static str) -> Param { + Param { + name, + ty, + required: false, + flag: false, + help, + } +} +const fn flag(name: &'static str, ty: Ty, help: &'static str) -> Param { + Param { + name, + ty, + required: false, + flag: true, + help, + } +} +const XYZ: [Param; 3] = [ + p("x", Ty::Num, "X coordinate"), + p("y", Ty::Num, "Y coordinate"), + p("z", Ty::Num, "Z coordinate"), +]; +const BLOCK_XYZ: [Param; 3] = [ + p("x", Ty::Int, "block X"), + p("y", Ty::Int, "block Y"), + p("z", Ty::Int, "block Z"), +]; +const FACE: Ty = Ty::Enum(&["down", "up", "north", "south", "west", "east"]); + +macro_rules! cmd { + ($name:expr, $group:ident, $usage:expr, $summary:expr, $details:expr, [$($ex:expr),* $(,)?], $params:expr, mcp: $mcp:expr, local: $local:expr $(, wire: $wire:expr)?) => { + Cmd { + name: $name, + wire: cmd!(@wire $($wire)?), + group: Group::$group, + usage: $usage, + summary: $summary, + details: $details, + examples: &[$($ex),*], + params: $params, + mcp: $mcp, + local: $local, + } + }; + (@wire) => { None }; + (@wire $w:expr) => { Some($w) }; +} + +pub const COMMANDS: &[Cmd] = &[ + // Session + cmd!("launch", Session, "launch [--world NAME] [--seed N] [--creative] [--version TAG] [--game PATH] [--wait] [GAME ARGS...]", + "start Horizon with the control socket and wait until it answers", + "Finds the game in this order: --game PATH; a horizon-client next to horizon-ctl (a build folder, a release folder or a launcher install); the newest version installed by the Horizon launcher (--version TAG picks one). Launcher installs run with their prepared resources and keep saves in the game home ($HORIZON_HOME, else ~/.local/share/horizon). --wait also waits until the player has spawned and chunks are loaded. Other arguments go to the game (horizon-client --help lists them). The game's output goes to a .log file beside the socket.", + ["horizon-ctl launch --world Survival --seed 42 --wait", "horizon-ctl launch --world Flat --creative --render-distance 8"], + &[flag("world", Ty::Str, "world folder to open or create"), flag("seed", Ty::Str, "seed for a new world"), flag("creative", Ty::Bool, "creative mode for a new world"), + flag("version", Ty::Str, "an installed launcher version tag such as v2026.10.13"), flag("game", Ty::Str, "path to a horizon-client binary"), + flag("wait", Ty::Bool, "also wait until the world is ready (default in MCP)")], + mcp: true, local: true), + cmd!("wait-ready", Session, "wait-ready [SECONDS]", "wait until the player has spawned and no chunks are pending", + "Polls status every 250 ms; replies with the status, or an error after SECONDS (default 120).", + ["horizon-ctl wait-ready 300"], &[opt("seconds", Ty::Num, "how long to wait (default 120)")], mcp: true, local: true), + cmd!("status", Session, "status", "game, renderer and streaming state (the scripting socket's original summary)", + "", ["horizon-ctl status"], &[], mcp: false, local: false), + cmd!("open", Session, "open WORLD [SEED] [creative]", "open or create a world from the title screen", + "Opens saves/WORLD, creating it with SEED (and creative mode) when it doesn't exist.", + ["horizon-ctl open Test 12345", "horizon-ctl open Build 0 creative"], + &[p("world", Ty::Str, "world folder"), opt("seed", Ty::Int, "seed for a new world"), opt("mode", Ty::Enum(&["creative"]), "creative for a creative world")], mcp: true, local: false), + cmd!("save", Session, "save", "save the world", "", ["horizon-ctl save"], &[], mcp: true, local: false), + cmd!("quit", Session, "quit", "save and exit the game", "", ["horizon-ctl quit"], &[], mcp: true, local: false), + cmd!("screenshot", Session, "screenshot PATH", "write the next rendered frame as a PNG", + "Relative paths are taken from horizon-ctl's directory. Over MCP the image is returned directly.", + ["horizon-ctl screenshot view.png"], &[], mcp: true, local: false), + // Observe + cmd!("state", Observe, "state", "player, world, screen and crosshair target in one reply", + "position, block_pos, eye, yaw, pitch, velocity, on_ground, health, food, saturation, xp, effects, gamemode, dimension, time, weather, the screen or title menu, the held item, what the crosshair points at and whether an action is running.", + ["horizon-ctl state"], &[], mcp: true, local: false), + cmd!("looking-at", Observe, "looking-at", "the block or entity under the crosshair", + "kind is block, entity or none; a block has pos, state, face, point and distance; an entity has id, type, health and distance.", + ["horizon-ctl looking-at"], &[], mcp: true, local: false), + cmd!("entities", Observe, "entities [RADIUS] [TYPE]", "mobs, dropped items and experience orbs near the player, nearest first", + "RADIUS defaults to 32. TYPE filters by entity type (pig, minecraft:item, ...). Mobs have an id for look-at entity and attack.", + ["horizon-ctl entities", "horizon-ctl entities 16 cow", "horizon-ctl entities 8 item"], + &[opt("radius", Ty::Num, "search radius in blocks (default 32)"), opt("type", Ty::Str, "entity type filter")], mcp: true, local: false), + cmd!("block", Observe, "block X Y Z", "the block state at a position", "", + ["horizon-ctl block 10 64 -3"], &BLOCK_XYZ, mcp: true, local: false), + cmd!("blocks", Observe, "blocks X1 Y1 Z1 X2 Y2 Z2", "the non-air blocks of a box, with counts per block", + "At most 32768 blocks per request.", ["horizon-ctl blocks 0 60 0 15 70 15"], + &[p("x1", Ty::Int, "corner X"), p("y1", Ty::Int, "corner Y"), p("z1", Ty::Int, "corner Z"), p("x2", Ty::Int, "opposite X"), p("y2", Ty::Int, "opposite Y"), p("z2", Ty::Int, "opposite Z")], mcp: true, local: false), + cmd!("find-block", Observe, "find-block BLOCK [RADIUS]", "the nearest loaded blocks of a kind", + "Searches a cube of RADIUS (default 32, at most 64) around the player; returns the count and the 16 nearest.", + ["horizon-ctl find-block oak_log", "horizon-ctl find-block diamond_ore 48"], + &[p("block", Ty::Str, "block id such as oak_log"), opt("radius", Ty::Int, "search radius (default 32)")], mcp: true, local: false), + cmd!("inventory", Observe, "inventory", "hotbar, main inventory, armor, offhand, carried stack and item counts", + "Slots carry the ids click-slot takes: 0-8 hotbar, 9-35 inventory, 500-503 armor (head to feet), 504 offhand. Stacks with components list them as SNBT.", + ["horizon-ctl inventory"], &[], mcp: true, local: false), + cmd!("screen", Observe, "screen", "the open screen or title menu, its buttons and its slots", + "buttons are what click-button takes; slots are what click-slot takes (crafting grid 100-103 in the inventory, 100-108 at a crafting table, result 200, containers from 300, stations from 600). On the title screen, menu has the mode, worlds and the create-world fields.", + ["horizon-ctl screen"], &[], mcp: true, local: false), + cmd!("messages", Observe, "messages [N]", "recent chat and system messages, the title and the action bar", + "N defaults to 20; chat is newest first.", ["horizon-ctl messages 5"], &[opt("n", Ty::Int, "how many chat lines (default 20)")], mcp: true, local: false), + cmd!("menu", Observe, "menu", "the open menu's slots and carried stack, with station details", "", + ["horizon-ctl menu"], &[], mcp: false, local: false), + // Move + cmd!("move", Move, "move forward|back|left|right SECONDS [--sprint] [--sneak] [--jump]", "walk in a direction relative to the view for a time", + "Replies when done with the start and end positions.", + ["horizon-ctl move forward 2", "horizon-ctl move forward 1.5 --sprint --jump"], + &[p("direction", Ty::Enum(&["forward", "back", "left", "right"]), "direction relative to the view"), p("seconds", Ty::Num, "how long to walk"), + flag("sprint", Ty::Bool, "sprint"), flag("sneak", Ty::Bool, "sneak"), flag("jump", Ty::Bool, "keep jumping")], mcp: true, local: false), + cmd!("goto", Move, "goto X Y Z [--near R] [--sprint] [--direct] [--timeout S]", "walk to a position, finding a path through loaded terrain", + "A* over standable blocks (steps up one block, drops up to three, avoids lava, swims when it must), then steering with jumps when stuck. Without a path it fails at once (--direct walks straight at the target anyway, falls included). --near R stops within R blocks (use 1.5-3 to reach a block you then break). Replies with arrived, position and distance, or an error when stuck or out of time (default 60 s).", + ["horizon-ctl goto 120 70 -40", "horizon-ctl goto 8 64 3 --near 2 --sprint"], + &[XYZ[0], XYZ[1], XYZ[2], flag("near", Ty::Num, "arrive within this many blocks (default 0.6)"), flag("sprint", Ty::Bool, "sprint"), flag("direct", Ty::Bool, "walk straight when no path is found"), flag("timeout", Ty::Num, "give up after this many seconds (default 60)")], mcp: true, local: false), + cmd!("jump", Move, "jump", "jump once and reply when landed", "", ["horizon-ctl jump"], &[], mcp: true, local: false), + cmd!("look", Move, "look YAW PITCH", "set the view direction in degrees", + "Yaw 0 faces south (+Z), 90 west (-X), 180 north, -90 east; pitch 90 looks straight down.", + ["horizon-ctl look 90 10"], &[p("yaw", Ty::Num, "yaw in degrees"), p("pitch", Ty::Num, "pitch in degrees (-90 up .. 90 down)")], mcp: true, local: false), + cmd!("turn", Move, "turn DYAW DPITCH", "rotate the view by an amount", "", ["horizon-ctl turn 45 0"], + &[p("dyaw", Ty::Num, "yaw change"), p("dpitch", Ty::Num, "pitch change")], mcp: false, local: false), + cmd!("look-at", Move, "look-at X Y Z | look-at block X Y Z [FACE] | look-at entity ID", "turn to face a point, a block (a visible face of it) or an entity", + "look-at block aims at a face the crosshair can reach and fails when none is visible.", + ["horizon-ctl look-at 10.5 65 3.5", "horizon-ctl look-at block 10 64 3 up", "horizon-ctl look-at entity 42"], + &XYZ, mcp: true, local: false), + cmd!("look-at-block", Move, "look-at-block X Y Z [FACE]", "aim the crosshair at a block (same as look-at block)", "", + ["horizon-ctl look-at-block 10 64 3"], &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], opt("face", FACE, "which face to aim at")], mcp: true, local: false, wire: "look-at block"), + cmd!("look-at-entity", Move, "look-at-entity ID", "face an entity (same as look-at entity)", "", + ["horizon-ctl look-at-entity 42"], &[p("id", Ty::Int, "entity id from entities")], mcp: true, local: false, wire: "look-at entity"), + cmd!("tp", Move, "tp X Y Z", "teleport the player", "", ["horizon-ctl tp 0 80 0"], &XYZ, mcp: true, local: false), + // Act + cmd!("break", Act, "break X Y Z [--timeout S]", "mine a block, holding the attack button until it breaks", + "Aims at a visible face (the block must be within reach: use goto --near 2 first), mines with the held item, then waits up to a second for the drops. Replies with block_before, block, ticks, drops and picked_up (inventory change).", + ["horizon-ctl break 10 64 3"], &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], flag("timeout", Ty::Num, "give up after this many seconds (default 30)")], mcp: true, local: false), + cmd!("place", Act, "place X Y Z [--item ITEM]", "place the held item (or ITEM from the hotbar) at an empty position", + "Clicks the face of a solid neighbour touching X Y Z. Replies with the block placed and the inventory change.", + ["horizon-ctl place 10 64 4 --item oak_planks"], &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], flag("item", Ty::Str, "hotbar item to select first")], mcp: true, local: false), + cmd!("interact", Act, "interact X Y Z [FACE]", "right-click a block: open a chest or crafting table, press a button, open a door", + "Replies with the screen afterwards and whether the block changed.", ["horizon-ctl interact 5 64 2"], + &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], opt("face", FACE, "which face to click")], mcp: true, local: false), + cmd!("use-item", Act, "use-item [--hold SECONDS]", "right-click with the held item: eat, drink, throw, draw a bow", + "Hold for 1.7 s to eat.", ["horizon-ctl use-item --hold 1.7"], &[flag("hold", Ty::Num, "hold the button this long")], mcp: true, local: false), + cmd!("attack", Act, "attack [ID]", "swing at what the crosshair targets (after facing entity ID)", + "Replies with the target's health before and after.", ["horizon-ctl attack", "horizon-ctl attack 42"], + &[opt("id", Ty::Int, "entity id to face first")], mcp: true, local: false), + cmd!("select", Act, "select SLOT|ITEM", "select a hotbar slot 1-9, or the hotbar slot holding ITEM", "", + ["horizon-ctl select 3", "horizon-ctl select oak_planks"], &[p("slot", Ty::Str, "1-9 or an item id")], mcp: true, local: false), + cmd!("drop", Act, "drop [all]", "drop one of the held item, or the whole stack", "", ["horizon-ctl drop", "horizon-ctl drop all"], + &[opt("all", Ty::Bool, "drop the whole stack")], mcp: true, local: false), + cmd!("hold", Act, "hold KEY SECONDS", "press a key, wait, release it", "Keys as for key.", ["horizon-ctl hold w 2"], + &[p("key", Ty::Str, "key name"), p("seconds", Ty::Num, "how long")], mcp: false, local: true), + cmd!("key", Act, "key KEY down|up|tap", "press or release a key (w a s d space shift ctrl e q esc f3 1-9 arrows ...)", "", + ["horizon-ctl key space tap"], &[p("key", Ty::Str, "key name"), p("action", Ty::Enum(&["down", "up", "tap"]), "what to do")], mcp: true, local: false), + cmd!("mouse", Act, "mouse left|right|middle down|up|click", "press or release a mouse button in the world", "", + ["horizon-ctl mouse right click"], &[p("button", Ty::Enum(&["left", "right", "middle"]), "button"), p("action", Ty::Enum(&["down", "up", "click"]), "what to do")], mcp: false, local: false), + cmd!("release", Act, "release", "release every key and mouse button", "", ["horizon-ctl release"], &[], mcp: false, local: false), + cmd!("stop", Act, "stop", "cancel the running action (goto, break...) and release every key", "", ["horizon-ctl stop"], &[], mcp: true, local: false), + // Screens + cmd!("open-inventory", Screens, "open-inventory", "open the inventory screen (crafting grid 100-103, result 200)", "", + ["horizon-ctl open-inventory"], &[], mcp: true, local: false), + cmd!("click-slot", Screens, "click-slot SLOT [right] [shift]", "click a slot of the open inventory or menu", + "SLOT ids as listed by screen: 0-8 hotbar, 9-35 inventory, 100+ crafting grid, 200 result, 300+ container, 500-503 armor, 504 offhand, 600+ station. A left click picks up or puts down the carried stack; right puts down one item; shift moves the stack across.", + ["horizon-ctl click-slot 36", "horizon-ctl click-slot 100 right", "horizon-ctl click-slot 200 shift"], + &[p("slot", Ty::Int, "slot id"), opt("right", Ty::Bool, "right-click"), opt("shift", Ty::Bool, "shift-click")], mcp: true, local: false), + cmd!("close", Screens, "close", "close the open menu and return to the game", "", ["horizon-ctl close"], &[], mcp: true, local: false), + cmd!("click-button", Screens, "click-button LABEL", "click a button of the open screen or title menu by its label", + "Case-insensitive; a unique part of the label is enough. screen lists the buttons.", + ["horizon-ctl click-button Singleplayer", "horizon-ctl click-button \"Create New World\"", "horizon-ctl click-button respawn"], + &[p("label", Ty::Rest, "button label")], mcp: true, local: false), + cmd!("click-at", Screens, "click-at X Y [right]", "click at GUI pixel X Y of the window (screen gives button rectangles)", "", + ["horizon-ctl click-at 200 120"], &[p("x", Ty::Num, "GUI x"), p("y", Ty::Num, "GUI y"), opt("right", Ty::Bool, "right-click")], mcp: true, local: false), + cmd!("type", Screens, "type [--field name|seed] [--replace] TEXT", "type into the focused text field (chat box, world name, anvil, sign...)", + "On the title's create-world screen, --field name|seed picks the field and --replace clears it first; type \\b deletes one character.", + ["horizon-ctl type hello everyone", "horizon-ctl type --field name --replace Agent World", "horizon-ctl type --field seed 12345"], &[flag("field", Ty::Enum(&["name", "seed"]), "create-world field to type into"), flag("replace", Ty::Bool, "clear the field first"), p("text", Ty::Rest, "text to type")], mcp: true, local: false), + cmd!("chat", Screens, "chat TEXT", "send a chat line (or a /command) as if typed", "", ["horizon-ctl chat hello"], + &[p("text", Ty::Rest, "message")], mcp: true, local: false), + cmd!("command", Screens, "command TEXT", "run a command (the leading / is optional)", "", + ["horizon-ctl command time set day", "horizon-ctl command /give @s oak_log 4"], &[p("command", Ty::Rest, "command line")], mcp: true, local: false), + cmd!("respawn", Screens, "respawn", "respawn from the death screen", "", ["horizon-ctl respawn"], &[], mcp: true, local: false), + cmd!("pause", Screens, "pause", "open the pause menu", "", ["horizon-ctl pause"], &[], mcp: true, local: false), + cmd!("resume", Screens, "resume", "leave the pause menu", "", ["horizon-ctl resume"], &[], mcp: true, local: false), + cmd!("chat-log", Screens, "chat-log [N]", "the newest N chat messages", "", ["horizon-ctl chat-log 5"], &[], mcp: false, local: false), + // World + cmd!("give", World, "give ITEM [COUNT]", "add items to the inventory", "", ["horizon-ctl give oak_log 16"], + &[p("item", Ty::Str, "item id"), opt("count", Ty::Int, "how many (default 1)")], mcp: true, local: false), + cmd!("time", World, "time TICKS", "set the time of day (0 sunrise, 6000 noon, 13000 night)", "", ["horizon-ctl time 6000"], + &[p("ticks", Ty::Int, "day time")], mcp: true, local: false), + cmd!("setblock", World, "setblock X Y Z BLOCK[props]", "set a block (with neighbour updates)", "", ["horizon-ctl setblock 0 64 0 stone"], + &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], p("block", Ty::Str, "block state such as oak_stairs[facing=east]")], mcp: true, local: false), + cmd!("summon", World, "summon KIND [X Y Z] [baby]", "spawn a mob", "", ["horizon-ctl summon cow"], &[p("kind", Ty::Str, "mob type")], mcp: true, local: false), + cmd!("effect", World, "effect ID SECONDS [AMPLIFIER] | effect clear", "give a status effect", "", ["horizon-ctl effect speed 30 1"], &[], mcp: false, local: false), + cmd!("render-distance", World, "render-distance N", "chunks, 2..64", "", ["horizon-ctl render-distance 8"], &[p("chunks", Ty::Int, "render distance")], mcp: false, local: false), + cmd!("wait", World, "wait TICKS", "wait until TICKS game ticks have passed (20 per second)", "", ["horizon-ctl wait 40"], + &[p("ticks", Ty::Int, "game ticks")], mcp: true, local: false), + // Scripting + cmd!("script", Scripting, "script [FILE] [--keep-going]", "run commands from FILE (or stdin), one per line", + "Lines are split like a shell (quotes keep spaces); # starts a comment; sleep SECONDS waits. Stops at the first error unless --keep-going. horizon-ctl - is the older form: read stdin and keep going.", + ["horizon-ctl script play.txt", "printf 'state\\ngoto 0 64 0\\n' | horizon-ctl script"], &[], mcp: false, local: true), + cmd!("sleep", Scripting, "sleep SECONDS", "wait (in scripts)", "", ["sleep 0.5"], &[], mcp: false, local: true), + cmd!("mcp", Scripting, "mcp", "serve the Model Context Protocol on stdin/stdout, one tool per command", + "Add it to an MCP client as a stdio server: command horizon-ctl, args [\"mcp\"] (with --socket PATH first if needed). The screenshot tool returns the image.", + ["horizon-ctl mcp"], &[], mcp: false, local: true), + cmd!("bench", Scripting, "bench SECONDS", "reset frame stats, wait, reply with the summary", "", ["horizon-ctl bench 10"], &[], mcp: false, local: false), + cmd!("stats", Scripting, "stats [reset]", "frame-time summary since the last reset", "", ["horizon-ctl stats"], &[], mcp: false, local: false), + cmd!("fly", Scripting, "fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH]", "fly the camera along a line, then reply with the frame summary", "", + ["horizon-ctl fly 0 100 0 500 100 0 20"], &[], mcp: false, local: false), +]; + +pub fn find(name: &str) -> Option<&'static Cmd> { + COMMANDS.iter().find(|c| c.name == name) +} + +/// `horizon-ctl help`. +pub fn overview() -> String { + let mut out = String::from( + "horizon-ctl: play and script a running Horizon from the command line.\n\n\ + usage: horizon-ctl [--socket PATH] [--timeout SECONDS] [--pretty] COMMAND [ARGS...]\n\ + \x20 horizon-ctl COMMAND --help (or: horizon-ctl help COMMAND)\n", + ); + for group in Group::ALL { + out.push_str(&format!("\n{}:\n", group.title())); + for c in COMMANDS.iter().filter(|c| c.group == group) { + out.push_str(&format!(" {:<16} {}\n", c.name, c.summary)); + } + } + out.push_str( + "\nEvery reply is one JSON line. Errors are {\"error\": \"...\"}; the exit status is 0 on\n\ + success, 1 when the game replied with an error, 2 for a usage error and 3 when the\n\ + game cannot be reached or started. Actions (goto, break, place...) block until done.\n\ + horizon-ctl help --game lists the running game's own commands, test hooks included.\n\ + The socket is $HORIZON_CONTROL, else $XDG_RUNTIME_DIR/horizon-control.sock (on Windows\n\ + %TEMP%\\horizon-control.json, a localhost TCP port with a token; any path ending in .json\n\ + uses that transport).\n\n\ + First steps:\n\ + \x20 horizon-ctl launch --world Test --seed 1 --wait\n\ + \x20 horizon-ctl state\n\ + \x20 horizon-ctl find-block oak_log\n\ + \x20 horizon-ctl goto X Y Z --near 2 && horizon-ctl break X Y Z\n\ + \x20 horizon-ctl inventory\n", + ); + out +} + +/// `horizon-ctl COMMAND --help`. +pub fn detail(c: &Cmd) -> String { + let mut out = format!( + "usage: horizon-ctl {}\n\n{}.\n", + c.usage, + capitalize(c.summary) + ); + if !c.details.is_empty() { + out.push('\n'); + out.push_str(&wrap(c.details, 78)); + } + if !c.examples.is_empty() { + out.push_str("\nExamples:\n"); + for e in c.examples { + out.push_str(&format!(" {e}\n")); + } + } + out +} + +fn capitalize(s: &str) -> String { + let mut chars = s.chars(); + chars + .next() + .map(|c| c.to_uppercase().chain(chars).collect()) + .unwrap_or_default() +} + +fn wrap(text: &str, width: usize) -> String { + let mut out = String::new(); + let mut line = String::new(); + for word in text.split_whitespace() { + if !line.is_empty() && line.len() + 1 + word.len() > width { + out.push_str(&line); + out.push('\n'); + line.clear(); + } + if !line.is_empty() { + line.push(' '); + } + line.push_str(word); + } + if !line.is_empty() { + out.push_str(&line); + out.push('\n'); + } + out +} + +/// The MCP tool name of a command (`look-at-block` gives `look_at_block`). +pub fn tool_name(c: &Cmd) -> String { + c.name.replace('-', "_") +} + +/// The JSON schema of a command's arguments. +pub fn schema(c: &Cmd) -> Value { + let mut props = Map::new(); + let mut required = Vec::new(); + for p in c.params { + let mut s = match p.ty { + Ty::Int => json!({ "type": "integer" }), + Ty::Num => json!({ "type": "number" }), + Ty::Str | Ty::Rest => json!({ "type": "string" }), + Ty::Bool => json!({ "type": "boolean" }), + Ty::Enum(values) => json!({ "type": "string", "enum": values }), + }; + s["description"] = json!(p.help); + props.insert(p.name.to_owned(), s); + if p.required { + required.push(p.name); + } + } + json!({ "type": "object", "properties": props, "required": required }) +} + +/// The command line for an MCP call's arguments: positional values in order, +/// then `--flag value` options. +pub fn line_for(c: &Cmd, args: &Value) -> Result, String> { + let mut words: Vec = c + .wire + .unwrap_or(c.name) + .split(' ') + .map(str::to_owned) + .collect(); + let mut flags = Vec::new(); + let mut gap: Option<&str> = None; + let mut rest: Option = None; + for p in c.params { + let value = args.get(p.name).filter(|v| !v.is_null()); + let text = match value { + None => { + if p.required { + return Err(format!("{} is required", p.name)); + } + if !p.flag { + gap.get_or_insert(p.name); + } + continue; + } + Some(Value::Bool(b)) => { + if p.ty != Ty::Bool { + return Err(format!("{} must be a {}", p.name, ty_name(p.ty))); + } + if *b { + if p.flag { + flags.push(format!("--{}", p.name)); + } else { + words.push(p.name.to_owned()); + } + } + continue; + } + Some(Value::String(s)) => s.clone(), + Some(Value::Number(n)) => n.to_string(), + Some(other) => { + return Err(format!( + "{} must be a {}, not {other}", + p.name, + ty_name(p.ty) + )); + } + }; + match p.ty { + Ty::Int if text.parse::().is_err() => { + return Err(format!("{} must be an integer, not {text}", p.name)); + } + Ty::Num if text.parse::().is_err() => { + return Err(format!("{} must be a number, not {text}", p.name)); + } + Ty::Enum(values) if !values.contains(&text.as_str()) => { + return Err(format!("{} must be one of {values:?}, not {text}", p.name)); + } + _ => {} + } + if p.flag { + flags.push(format!("--{}", p.name)); + flags.push(text); + } else { + if let Some(missing) = gap { + return Err(format!("{} needs {missing} to be given too", p.name)); + } + if p.ty == Ty::Rest { + rest = Some(text); + } else if text.contains(char::is_whitespace) || text.is_empty() { + return Err(format!("{} must be a single word", p.name)); + } else { + words.push(text); + } + } + } + // Options go before free text, which runs to the end of the line. + words.extend(flags); + words.extend(rest); + Ok(words) +} + +fn ty_name(ty: Ty) -> &'static str { + match ty { + Ty::Int => "integer", + Ty::Num => "number", + Ty::Bool => "boolean", + _ => "string", + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_are_unique_and_documented() { + let mut seen = std::collections::HashSet::new(); + for c in COMMANDS { + assert!(seen.insert(c.name), "duplicate command {}", c.name); + assert!( + c.usage.starts_with(c.name.split('-').next().unwrap()), + "{}", + c.name + ); + assert!( + !c.summary.is_empty() && !c.examples.is_empty(), + "{}", + c.name + ); + } + } + + #[test] + fn mcp_arguments_become_command_lines() { + let goto = find("goto").unwrap(); + let words = line_for( + goto, + &json!({ "x": 1.5, "y": 64, "z": -3, "near": 2, "sprint": true }), + ) + .unwrap(); + assert_eq!( + words, + ["goto", "1.5", "64", "-3", "--near", "2", "--sprint"] + ); + assert!( + line_for(goto, &json!({ "x": 1, "y": 2 })) + .unwrap_err() + .contains("z is required") + ); + assert!(line_for(goto, &json!({ "x": "a", "y": 2, "z": 3 })).is_err()); + let block = find("look-at-block").unwrap(); + assert_eq!( + line_for(block, &json!({ "x": 1, "y": 2, "z": 3, "face": "up" })).unwrap(), + ["look-at", "block", "1", "2", "3", "up"] + ); + assert!( + line_for( + block, + &json!({ "x": 1, "y": 2, "z": 3, "face": "sideways" }) + ) + .is_err() + ); + let button = find("click-button").unwrap(); + assert_eq!( + line_for(button, &json!({ "label": "Create New World" })).unwrap(), + ["click-button", "Create New World"] + ); + let slot = find("click-slot").unwrap(); + assert_eq!( + line_for(slot, &json!({ "slot": 200, "shift": true })).unwrap(), + ["click-slot", "200", "shift"] + ); + let open = find("open").unwrap(); + assert!( + line_for(open, &json!({ "world": "A", "mode": "creative" })) + .unwrap_err() + .contains("seed") + ); + } + + #[test] + fn schemas_list_required_parameters() { + let s = schema(find("break").unwrap()); + assert_eq!(s["required"], json!(["x", "y", "z"])); + assert_eq!(s["properties"]["timeout"]["type"], "number"); + assert_eq!(tool_name(find("look-at-entity").unwrap()), "look_at_entity"); + } + + #[test] + fn help_mentions_every_command() { + let text = overview(); + for c in COMMANDS { + assert!(text.contains(c.name)); + assert!(detail(c).contains("usage: horizon-ctl")); + } + } +} diff --git a/crates/horizon-client/src/bin/horizon-ctl/launch.rs b/crates/horizon-client/src/bin/horizon-ctl/launch.rs new file mode 100644 index 000000000..984b634af --- /dev/null +++ b/crates/horizon-client/src/bin/horizon-ctl/launch.rs @@ -0,0 +1,386 @@ +//! `horizon-ctl launch`: find a Horizon to start and start it with a control +//! socket. Mirrors where the launcher puts things (launcher/src/backend.rs): +//! versions under `/versions/`, each with its prepared +//! resources in `.local/horizon-client/` and run from the +//! game home, where saves and options.txt live. +use std::{ + path::{Path, PathBuf}, + process::{Command, Stdio}, + thread, + time::{Duration, Instant}, +}; + +use serde_json::{Value, json}; + +#[cfg(windows)] +const CLIENT: &str = "horizon-client.exe"; +#[cfg(not(windows))] +const CLIENT: &str = "horizon-client"; + +/// The platform data folder (what the `dirs` crate's data_dir gives). +fn data_dir() -> PathBuf { + let env = |k: &str| { + std::env::var_os(k) + .filter(|v| !v.is_empty()) + .map(PathBuf::from) + }; + let home = env("HOME").or_else(|| env("USERPROFILE")); + if cfg!(windows) { + if let Some(d) = env("APPDATA") { + return d; + } + } else if cfg!(target_os = "macos") { + if let Some(h) = &home { + return h.join("Library/Application Support"); + } + } else if let Some(d) = env("XDG_DATA_HOME") { + return d; + } else if let Some(h) = &home { + return h.join(".local/share"); + } + std::env::temp_dir() +} +pub fn launcher_home() -> PathBuf { + match std::env::var_os("HORIZON_LAUNCHER_HOME").filter(|h| !h.is_empty()) { + Some(h) => PathBuf::from(h), + None => data_dir().join("horizon-launcher"), + } +} +pub fn game_home() -> PathBuf { + match std::env::var_os("HORIZON_HOME").filter(|h| !h.is_empty()) { + Some(h) => PathBuf::from(h), + None => data_dir().join("horizon"), + } +} + +/// `v2026.10.13.1` gives [2026, 10, 13, 1]; a pre-release suffix is ignored. +pub fn version_parts(tag: &str) -> Vec { + tag.trim_start_matches('v') + .split('-') + .next() + .unwrap_or("") + .split('.') + .map(|p| p.parse().unwrap_or(0)) + .collect() +} + +/// Installed launcher versions, newest first. +pub fn installed(versions: &Path) -> Vec { + let mut tags: Vec = std::fs::read_dir(versions) + .into_iter() + .flatten() + .flatten() + .filter(|e| e.path().join(".installed").exists() && e.path().join(CLIENT).exists()) + .filter_map(|e| e.file_name().into_string().ok()) + .collect(); + tags.sort_by_key(|t| std::cmp::Reverse(version_parts(t))); + tags +} + +/// A folder's prepared resources, as the launcher prepares them. +pub fn prepared_resources(dir: &Path) -> Option { + let version = std::fs::read_to_string(dir.join("research-lock.json")) + .ok() + .and_then(|t| serde_json::from_str::(&t).ok()) + .and_then(|v| v["minecraft"]["version"].as_str().map(str::to_owned)) + .unwrap_or_else(|| "26.3".into()); + let resources = dir.join(".local/horizon-client").join(version); + resources + .join("horizon-resources.json") + .exists() + .then_some(resources) +} + +#[derive(Debug, PartialEq)] +pub struct Install { + pub game: PathBuf, + /// Passed as --resources unless the caller gave their own. + pub resources: Option, + /// The working directory (the game home for prepared installs). + pub cwd: Option, + pub source: &'static str, + pub version: Option, +} + +/// Which game to start: an explicit binary, the one beside horizon-ctl, or a +/// launcher install. +pub fn find( + game: Option<&Path>, + version: Option<&str>, + beside: Option<&Path>, + launcher: &Path, +) -> Result { + let prepared = |dir: &Path, source, version| { + let resources = prepared_resources(dir); + Install { + game: dir.join(CLIENT), + cwd: resources.as_ref().map(|_| game_home()), + resources, + source, + version, + } + }; + if let Some(game) = game { + if !game.is_file() { + return Err(format!("{} is not a file", game.display())); + } + let dir = game.parent().unwrap_or(Path::new(".")); + let mut install = prepared(dir, "--game", None); + install.game = game.to_owned(); + return Ok(install); + } + let versions = launcher.join("versions"); + if version.is_none() + && let Some(dir) = beside + && dir.join(CLIENT).is_file() + { + return Ok(prepared(dir, "beside horizon-ctl", None)); + } + let tags = installed(&versions); + let tag = match version { + Some(v) => { + let want = if v.starts_with('v') { v.to_owned() } else { format!("v{v}") }; + tags.iter() + .find(|t| **t == want || **t == v) + .cloned() + .ok_or_else(|| format!("version {v} is not installed in {} (installed: {tags:?})", versions.display()))? + } + None => tags.first().cloned().ok_or_else(|| { + format!( + "no Horizon found: no horizon-client beside horizon-ctl and no version installed by the launcher in {}. Install one with the launcher (horizon-launcher install latest) or pass --game PATH.", + versions.display() + ) + })?, + }; + let dir = versions.join(&tag); + let install = prepared(&dir, "launcher", Some(tag.clone())); + if install.resources.is_none() { + return Err(format!( + "{tag} is installed but not prepared; prepare it in the launcher first (horizon-launcher prepare {tag})" + )); + } + Ok(install) +} + +pub struct Options { + pub game: Option, + pub version: Option, + pub wait: bool, + pub game_args: Vec, +} + +pub fn parse(args: &[String]) -> Result { + let mut o = Options { + game: None, + version: None, + wait: false, + game_args: Vec::new(), + }; + let mut i = 0; + while i < args.len() { + let value = |i: usize| { + args.get(i + 1) + .cloned() + .ok_or_else(|| format!("{} needs a value", args[i])) + }; + match args[i].as_str() { + "--game" => { + o.game = Some(value(i)?.into()); + i += 1; + } + "--version" => { + o.version = Some(value(i)?); + i += 1; + } + "--wait" | "--wait-ready" => o.wait = true, + other => o.game_args.push(other.to_owned()), + } + i += 1; + } + Ok(o) +} + +/// Start the game and wait for its control endpoint; Ok(reply) or Err(reply). +pub fn launch(socket: &Path, args: &[String]) -> Result { + let o = parse(args).map_err(|e| json!({ "error": e, "kind": "usage" }))?; + if horizon_client::control::connect(socket).is_ok() { + return Err(json!({ + "error": format!("a game is already listening on {}; quit it first or pass another --socket", socket.display()), + "kind": "connection", + })); + } + let exe = std::env::current_exe().ok(); + let beside = exe.as_deref().and_then(Path::parent); + let install = find( + o.game.as_deref(), + o.version.as_deref(), + beside, + &launcher_home(), + ) + .map_err(|e| json!({ "error": e, "kind": "launch" }))?; + let log = socket.with_extension("log"); + let file = std::fs::File::create(&log) + .map_err(|e| json!({ "error": format!("{}: {e}", log.display()), "kind": "launch" }))?; + let mut cmd = Command::new(&install.game); + let gave_resources = o.game_args.iter().any(|a| a == "--resources"); + if let Some(resources) = install.resources.as_ref().filter(|_| !gave_resources) { + cmd.arg("--resources").arg(resources); + } + if let Some(cwd) = &install.cwd { + let _ = std::fs::create_dir_all(cwd); + cmd.current_dir(cwd); + } + let stderr = file + .try_clone() + .map_err(|e| json!({ "error": e.to_string(), "kind": "launch" }))?; + let mut child = cmd + .args(&o.game_args) + .arg("--control-socket") + .arg(socket) + .stdin(Stdio::null()) + .stdout(file) + .stderr(stderr) + .spawn() + .map_err( + |e| json!({ "error": format!("{}: {e}", install.game.display()), "kind": "launch" }), + )?; + let deadline = Instant::now() + Duration::from_secs(300); + let info = json!({ + "pid": child.id(), + "socket": socket, + "log": log, + "game": install.game, + "source": install.source, + "version": install.version, + "resources": install.resources, + "home": install.cwd, + }); + while Instant::now() < deadline { + if horizon_client::control::connect(socket).is_ok() { + let mut reply = json!({ "ok": true }); + reply + .as_object_mut() + .unwrap() + .extend(info.as_object().unwrap().clone()); + return Ok(reply); + } + if let Ok(Some(status)) = child.try_wait() { + let tail = std::fs::read_to_string(&log).unwrap_or_default(); + let tail: Vec<&str> = tail.lines().rev().take(15).collect(); + return Err(json!({ + "error": format!("the game exited ({status}) before opening the control socket"), + "kind": "launch", + "log_tail": tail.into_iter().rev().collect::>(), + "log": log, + })); + } + thread::sleep(Duration::from_millis(100)); + } + Err( + json!({ "error": "control socket did not open within 300 seconds", "kind": "launch", "log": log }), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("horizon-ctl-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + fn fake_version(versions: &Path, tag: &str, prepared: bool) -> PathBuf { + let dir = versions.join(tag); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join(CLIENT), "").unwrap(); + std::fs::write(dir.join(".installed"), "").unwrap(); + std::fs::write( + dir.join("research-lock.json"), + r#"{"minecraft":{"version":"26.3"}}"#, + ) + .unwrap(); + if prepared { + let res = dir.join(".local/horizon-client/26.3"); + std::fs::create_dir_all(&res).unwrap(); + std::fs::write(res.join("horizon-resources.json"), "{}").unwrap(); + } + dir + } + + #[test] + fn versions_sort_newest_first() { + let home = temp("sort"); + let versions = home.join("versions"); + for tag in ["v2026.9.30", "v2026.10.13", "v2026.10.13.1", "v2026.10.2"] { + fake_version(&versions, tag, true); + } + assert_eq!( + installed(&versions), + ["v2026.10.13.1", "v2026.10.13", "v2026.10.2", "v2026.9.30"] + ); + let install = find(None, None, None, &home).unwrap(); + assert_eq!(install.version.as_deref(), Some("v2026.10.13.1")); + assert!( + install + .resources + .unwrap() + .ends_with(".local/horizon-client/26.3") + ); + assert_eq!(install.cwd, Some(game_home())); + let picked = find(None, Some("2026.10.2"), None, &home).unwrap(); + assert_eq!(picked.version.as_deref(), Some("v2026.10.2")); + assert!(find(None, Some("v1.0"), None, &home).is_err()); + let _ = std::fs::remove_dir_all(home); + } + + #[test] + fn a_game_beside_ctl_wins_and_dev_builds_keep_the_directory() { + let home = temp("beside"); + fake_version(&home.join("versions"), "v2026.10.13", true); + let build = temp("build"); + std::fs::write(build.join(CLIENT), "").unwrap(); + let install = find(None, None, Some(&build), &home).unwrap(); + assert_eq!(install.source, "beside horizon-ctl"); + assert_eq!((install.resources, install.cwd), (None, None)); + // --version always means a launcher install. + assert_eq!( + find(None, Some("v2026.10.13"), Some(&build), &home) + .unwrap() + .source, + "launcher" + ); + let _ = std::fs::remove_dir_all(home); + let _ = std::fs::remove_dir_all(build); + } + + #[test] + fn unprepared_or_missing_installs_explain_themselves() { + let home = temp("unprepared"); + assert!( + find(None, None, None, &home) + .unwrap_err() + .contains("no Horizon found") + ); + fake_version(&home.join("versions"), "v2026.10.13", false); + assert!( + find(None, None, None, &home) + .unwrap_err() + .contains("not prepared") + ); + let _ = std::fs::remove_dir_all(home); + } + + #[test] + fn launch_options_pass_the_rest_to_the_game() { + let args: Vec = ["--world", "A", "--version", "v1", "--wait", "--seed", "3"] + .map(String::from) + .to_vec(); + let o = parse(&args).unwrap(); + assert_eq!(o.version.as_deref(), Some("v1")); + assert!(o.wait); + assert_eq!(o.game_args, ["--world", "A", "--seed", "3"]); + assert!(parse(&["--game".to_owned()]).is_err()); + } +} diff --git a/crates/horizon-client/src/bin/horizon-ctl/main.rs b/crates/horizon-client/src/bin/horizon-ctl/main.rs index 962a4885d..193f84410 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/main.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/main.rs @@ -1,66 +1,235 @@ -//! horizon-ctl: drive a running Horizon client through its control socket. +//! horizon-ctl: play and script a running Horizon client through its control +//! socket, from a shell, a script or an AI agent (`horizon-ctl mcp`). #![forbid(unsafe_code)] +mod commands; +mod launch; +mod mcp; + use std::{ io::{BufRead, BufReader, Write}, path::{Path, PathBuf}, - process::{Command, ExitCode, Stdio}, + process::ExitCode, thread, time::{Duration, Instant}, }; -use horizon_client::control::UnixStream; +use horizon_client::control::Stream; +use serde_json::{Value, json}; -const USAGE: &str = "usage: horizon-ctl [--socket PATH] COMMAND [ARGS...] +/// Exit statuses. +const GAME_ERROR: u8 = 1; +const USAGE: u8 = 2; +const UNREACHABLE: u8 = 3; -Local commands: - launch [GAME ARGS...] start horizon-client with a control socket and wait for it - hold KEY SECONDS press KEY, wait, release it - wait-ready [SECONDS] wait until the player has spawned and no chunks are pending - - run commands from stdin, one per line (\"sleep S\" waits locally) +/// A failure, with the exit status it maps to. +#[derive(Debug)] +pub struct Failure { + pub reply: Value, + pub status: u8, +} +impl Failure { + fn usage(message: impl Into) -> Self { + Self { + reply: json!({ "error": message.into(), "kind": "usage" }), + status: USAGE, + } + } + fn unreachable(message: impl Into) -> Self { + Self { + reply: json!({ "error": message.into(), "kind": "connection" }), + status: UNREACHABLE, + } + } +} -Game commands (run \"horizon-ctl help\" against a running game for the full list): - status, key, mouse, look, turn, tp, hotbar, give, render-distance, time, - screenshot PATH, stats, bench SECONDS, open, save, quit - -Replies are JSON lines; the exit status is 1 when the reply has an \"error\". -The socket defaults to $HORIZON_CONTROL or $XDG_RUNTIME_DIR/horizon-control.sock."; - -struct Client { - writer: UnixStream, - reader: BufReader, +pub struct Client { + writer: Stream, + reader: BufReader, } impl Client { - fn connect(path: &Path) -> Result { - let stream = UnixStream::connect(path).map_err(|e| { - format!( - "cannot connect to {} ({e}); is the game running with --control?", + fn connect(path: &Path, timeout: Option) -> Result { + let stream = horizon_client::control::connect(path).map_err(|e| { + Failure::unreachable(format!( + "cannot connect to {} ({e}); is the game running with --control? Start one with: horizon-ctl launch --world NAME", path.display() - ) + )) })?; - let reader = BufReader::new(stream.try_clone().map_err(|e| e.to_string())?); + stream + .set_read_timeout(timeout) + .map_err(|e| Failure::unreachable(e.to_string()))?; + let reader = BufReader::new( + stream + .try_clone() + .map_err(|e| Failure::unreachable(e.to_string()))?, + ); Ok(Self { writer: stream, reader, }) } - fn send(&mut self, line: &str) -> Result { - writeln!(self.writer, "{line}").map_err(|e| e.to_string())?; + /// Send one line and read its JSON reply. + fn send(&mut self, line: &str) -> Result { + writeln!(self.writer, "{line}").map_err(|e| Failure::unreachable(e.to_string()))?; let mut reply = String::new(); - if self - .reader - .read_line(&mut reply) - .map_err(|e| e.to_string())? - == 0 - { - return Err("the game closed the connection".into()); + let n = self.reader.read_line(&mut reply).map_err(|e| { + Failure::unreachable( + if matches!( + e.kind(), + std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut + ) { + "timed out waiting for the game's reply (--timeout)".to_owned() + } else { + e.to_string() + }, + ) + })?; + if n == 0 { + return Err(Failure::unreachable("the game closed the connection")); } - Ok(reply.trim_end().to_owned()) + serde_json::from_str(reply.trim_end()).map_err(|_| Failure { + reply: json!({ "error": "the game sent a reply that is not JSON", "reply": reply.trim_end() }), + status: GAME_ERROR, + }) } } -fn is_error(reply: &str) -> bool { - serde_json::from_str::(reply).map_or(true, |v| v.get("error").is_some()) +/// Global options and the connection, opened on first use. +pub struct Session { + pub socket: PathBuf, + pub timeout: Option, + client: Option, +} + +impl Session { + pub fn new(socket: PathBuf, timeout: Option) -> Self { + Self { + socket, + timeout, + client: None, + } + } + fn client(&mut self) -> Result<&mut Client, Failure> { + if self.client.is_none() { + self.client = Some(Client::connect(&self.socket, self.timeout)?); + } + Ok(self.client.as_mut().unwrap()) + } + /// Send a line to the game; a reply with "error" is a failure. + pub fn game(&mut self, line: &str) -> Result { + let result = self.client()?.send(line); + if result.as_ref().is_err_and(|f| f.status == UNREACHABLE) { + // Reconnect next time (the game may have restarted). + self.client = None; + } + let reply = result?; + if reply.get("error").is_some() { + return Err(Failure { + reply, + status: GAME_ERROR, + }); + } + Ok(reply) + } + + /// Run one command (CLI words); Ok(reply) or a failure. + pub fn run(&mut self, words: &[String]) -> Result { + let Some(name) = words.first().map(String::as_str) else { + return Err(Failure::usage("no command; try horizon-ctl help")); + }; + if words.iter().skip(1).any(|w| w == "--help" || w == "-h") { + return Err(Failure::usage( + "use horizon-ctl COMMAND --help outside scripts", + )); + } + let number = |i: usize, what: &str| -> Result { + words + .get(i) + .ok_or_else(|| Failure::usage(format!("missing {what}; usage: {}", usage(name))))? + .parse::() + .map_err(|_| { + Failure::usage(format!("{what} must be a number; usage: {}", usage(name))) + }) + }; + match name { + "sleep" => { + thread::sleep(Duration::from_secs_f64(number(1, "SECONDS")?.max(0.0))); + Ok(json!({ "ok": true })) + } + "launch" => { + let socket = self.socket.clone(); + let wait = words.iter().any(|w| w == "--wait" || w == "--wait-ready"); + let reply = launch::launch(&socket, &words[1..]).map_err(|reply| Failure { + status: if reply["kind"] == "usage" { + USAGE + } else { + UNREACHABLE + }, + reply, + })?; + if !wait { + return Ok(reply); + } + let mut ready = self.wait_ready(300.0)?; + ready["launch"] = reply; + Ok(ready) + } + "hold" => { + let (key, seconds) = match words { + [_, key, _] => (key.clone(), number(2, "SECONDS")?), + _ => return Err(Failure::usage(format!("usage: {}", usage(name)))), + }; + self.game(&format!("key {key} down"))?; + thread::sleep(Duration::from_secs_f64(seconds.max(0.0))); + self.game(&format!("key {key} up")) + } + "wait-ready" => { + let limit = if words.len() > 1 { + number(1, "SECONDS")? + } else { + 120.0 + }; + self.wait_ready(limit) + } + "help" if words.get(1).is_some_and(|w| w == "--game") => self.game("help"), + _ => { + let mut words = words.to_vec(); + if let Some(cmd) = commands::find(name) { + if cmd.local { + return Err(Failure::usage(format!( + "{name} runs only as horizon-ctl {name}, not inside a script" + ))); + } + if let Some(wire) = cmd.wire { + words.splice(0..1, wire.split(' ').map(str::to_owned)); + } + } + absolute_paths(&mut words); + self.game(&words.join(" ")) + } + } + } + + fn wait_ready(&mut self, limit: f64) -> Result { + let deadline = Instant::now() + Duration::from_secs_f64(limit.max(0.0)); + loop { + let status = self.game("status")?; + if !status["player"].is_null() && status["pending_chunks"] == 0 { + return Ok(status); + } + if Instant::now() > deadline { + return Err(Failure { + reply: json!({ "error": format!("not ready after {limit} seconds"), "status": status }), + status: GAME_ERROR, + }); + } + thread::sleep(Duration::from_millis(250)); + } + } +} + +fn usage(name: &str) -> String { + commands::find(name).map_or_else(|| name.to_owned(), |c| format!("horizon-ctl {}", c.usage)) } /// Screenshot paths are written by the game process: make them absolute here. @@ -73,132 +242,247 @@ fn absolute_paths(words: &mut [String]) { } } -fn run_line(client: &mut Client, words: &mut [String]) -> Result { - match words.first().map(String::as_str) { - Some("sleep") => { - let seconds: f64 = words - .get(1) - .ok_or("sleep SECONDS")? - .parse() - .map_err(|_| "sleep SECONDS")?; - thread::sleep(Duration::from_secs_f64(seconds)); - Ok(true) - } - Some("hold") => { - let (key, seconds) = match words { - [_, key, seconds] => ( - key.clone(), - seconds.parse::().map_err(|_| "hold KEY SECONDS")?, - ), - _ => return Err("hold KEY SECONDS".into()), - }; - let down = client.send(&format!("key {key} down"))?; - if is_error(&down) { - println!("{down}"); - return Ok(false); +/// Split a script line like a shell: quotes keep spaces, backslash escapes. +pub fn split_line(line: &str) -> Result, String> { + let mut words = Vec::new(); + let mut word = String::new(); + let mut in_word = false; + let mut quote: Option = None; + let mut chars = line.chars(); + while let Some(c) = chars.next() { + match (quote, c) { + (Some(q), c) if c == q => quote = None, + (Some('"'), '\\') => word.push(chars.next().unwrap_or('\\')), + (Some(_), c) => word.push(c), + (None, '"' | '\'') => { + quote = Some(c); + in_word = true; } - thread::sleep(Duration::from_secs_f64(seconds)); - let up = client.send(&format!("key {key} up"))?; - println!("{up}"); - Ok(!is_error(&up)) - } - Some("wait-ready") => { - let limit = words - .get(1) - .map_or(Ok(120.0), |s| s.parse::()) - .map_err(|_| "wait-ready [SECONDS]")?; - let deadline = Instant::now() + Duration::from_secs_f64(limit); - loop { - let reply = client.send("status")?; - let status: serde_json::Value = - serde_json::from_str(&reply).map_err(|e| e.to_string())?; - if !status["player"].is_null() && status["pending_chunks"] == 0 { - println!("{reply}"); - return Ok(true); - } - if Instant::now() > deadline { - println!( - "{{\"error\":\"not ready after {limit} seconds\",\"status\":{reply}}}" - ); - return Ok(false); - } - thread::sleep(Duration::from_millis(250)); + (None, '\\') => { + word.push(chars.next().unwrap_or('\\')); + in_word = true; + } + (None, '#') if !in_word => break, + (None, c) if c.is_whitespace() => { + if in_word { + words.push(std::mem::take(&mut word)); + in_word = false; + } + } + (None, c) => { + word.push(c); + in_word = true; } - } - _ => { - absolute_paths(words); - let reply = client.send(&words.join(" "))?; - println!("{reply}"); - Ok(!is_error(&reply)) } } + if quote.is_some() { + return Err("unterminated quote".into()); + } + if in_word { + words.push(word); + } + Ok(words) } -fn launch(socket: &Path, args: &[String]) -> Result { - let exe = std::env::current_exe().map_err(|e| e.to_string())?; - let game = exe.with_file_name("horizon-client"); - let log = socket.with_extension("log"); - let file = std::fs::File::create(&log).map_err(|e| format!("{}: {e}", log.display()))?; - let child = Command::new(&game) - .args(args) - .arg("--control-socket") - .arg(socket) - .stdin(Stdio::null()) - .stdout(file.try_clone().map_err(|e| e.to_string())?) - .stderr(file) - .spawn() - .map_err(|e| format!("{}: {e}", game.display()))?; - let deadline = Instant::now() + Duration::from_secs(300); - while Instant::now() < deadline { - if UnixStream::connect(socket).is_ok() { - println!( - "{}", - serde_json::json!({ "ok": true, "pid": child.id(), "socket": socket, "log": log }) - ); - return Ok(true); +fn print(value: &Value, pretty: bool) { + let text = if pretty { + serde_json::to_string_pretty(value).unwrap_or_default() + } else { + value.to_string() + }; + println!("{text}"); +} + +/// Run a script; the exit status of the first failure (or the last one with --keep-going). +fn script(session: &mut Session, reader: impl BufRead, keep_going: bool, pretty: bool) -> u8 { + let mut status = 0; + for (n, line) in reader.lines().enumerate() { + let Ok(line) = line else { break }; + let words = match split_line(&line) { + Ok(w) if w.is_empty() => continue, + Ok(w) => w, + Err(e) => { + print( + &json!({ "error": e, "kind": "usage", "line": n + 1 }), + pretty, + ); + status = USAGE; + if keep_going { + continue; + } + break; + } + }; + match session.run(&words) { + Ok(reply) => print(&reply, pretty), + Err(mut f) => { + f.reply["line"] = json!(n + 1); + print(&f.reply, pretty); + status = f.status; + if !keep_going || f.status == UNREACHABLE { + break; + } + } } - thread::sleep(Duration::from_millis(100)); } - println!( - "{}", - serde_json::json!({ "error": "control socket did not open within 300 seconds", "log": log }) - ); - Ok(false) + status } fn main() -> ExitCode { let mut args: Vec = std::env::args().skip(1).collect(); let mut socket = horizon_client::control::default_path(); - if args.first().map(String::as_str) == Some("--socket") && args.len() >= 2 { - socket = PathBuf::from(args.remove(1)); - args.remove(0); - } - let result = match args.first().map(String::as_str) { - None | Some("-h" | "--help") => { - println!("{USAGE}"); - return ExitCode::SUCCESS; - } - Some("launch") => launch(&socket, &args[1..]), - Some("-") => Client::connect(&socket).and_then(|mut client| { - let mut all_ok = true; - for line in std::io::stdin().lock().lines() { - let line = line.map_err(|e| e.to_string())?; - let mut words: Vec = line.split_whitespace().map(str::to_owned).collect(); - if words.is_empty() || words[0].starts_with('#') { - continue; - } - all_ok &= run_line(&mut client, &mut words)?; + let mut timeout = None; + let mut pretty = false; + // Global options before the command. + loop { + match args.first().map(String::as_str) { + Some("--socket") if args.len() >= 2 => { + socket = PathBuf::from(args.remove(1)); + args.remove(0); } - Ok(all_ok) - }), - Some(_) => Client::connect(&socket).and_then(|mut client| run_line(&mut client, &mut args)), - }; - match result { - Ok(true) => ExitCode::SUCCESS, - Ok(false) => ExitCode::from(1), - Err(e) => { - eprintln!("horizon-ctl: {e}"); - ExitCode::from(2) + Some("--timeout") if args.len() >= 2 => { + let Ok(s) = args[1].parse::() else { + print( + &json!({ "error": "--timeout takes seconds", "kind": "usage" }), + false, + ); + return ExitCode::from(USAGE); + }; + timeout = Some(Duration::from_secs_f64(s.max(0.001))); + args.drain(0..2); + } + Some("--pretty") => { + pretty = true; + args.remove(0); + } + _ => break, } } + let mut session = Session::new(socket, timeout); + let name = args.first().cloned(); + let status = match name.as_deref() { + None | Some("-h" | "--help") => { + print!("{}", commands::overview()); + 0 + } + Some("help") if args.get(1).is_none_or(|a| a != "--game") => match args.get(1) { + None => { + print!("{}", commands::overview()); + 0 + } + Some(c) => match commands::find(c) { + Some(cmd) => { + print!("{}", commands::detail(cmd)); + 0 + } + None => { + print( + &json!({ "error": format!("unknown command {c}; horizon-ctl help lists them, horizon-ctl help --game lists the game's own"), "kind": "usage" }), + pretty, + ); + USAGE + } + }, + }, + Some(c) if args.len() == 2 && matches!(args[1].as_str(), "--help" | "-h") => { + match commands::find(c) { + Some(cmd) => { + print!("{}", commands::detail(cmd)); + 0 + } + None => { + print( + &json!({ "error": format!("no help for {c}; horizon-ctl help --game lists the game's own commands"), "kind": "usage" }), + pretty, + ); + USAGE + } + } + } + Some("mcp") => match mcp::serve(&mut session) { + Ok(()) => 0, + Err(e) => { + eprintln!("horizon-ctl mcp: {e}"); + UNREACHABLE + } + }, + Some("-") => { + // The original form: stdin, keep going, status 1 if anything failed. + let status = script(&mut session, std::io::stdin().lock(), true, pretty); + if status == 0 { + 0 + } else { + status.min(GAME_ERROR).max(1) + } + } + Some("script") => { + let keep_going = args.iter().any(|a| a == "--keep-going"); + match args.iter().skip(1).find(|a| !a.starts_with("--")) { + Some(file) if file != "-" => match std::fs::File::open(file) { + Ok(f) => script(&mut session, BufReader::new(f), keep_going, pretty), + Err(e) => { + print( + &json!({ "error": format!("{file}: {e}"), "kind": "usage" }), + pretty, + ); + USAGE + } + }, + _ => script(&mut session, std::io::stdin().lock(), keep_going, pretty), + } + } + Some(_) => match session.run(&args) { + Ok(reply) => { + print(&reply, pretty); + 0 + } + Err(f) => { + print(&f.reply, pretty); + f.status + } + }, + }; + ExitCode::from(status) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn script_lines_split_like_a_shell() { + assert_eq!( + split_line("goto 1 2 3 --near 2").unwrap(), + ["goto", "1", "2", "3", "--near", "2"] + ); + assert_eq!( + split_line("click-button \"Create New World\"").unwrap(), + ["click-button", "Create New World"] + ); + assert_eq!( + split_line("type 'it''s' # comment").unwrap(), + ["type", "its"] + ); + assert_eq!(split_line("chat a\\ b").unwrap(), ["chat", "a b"]); + assert_eq!(split_line("chat issue#4").unwrap(), ["chat", "issue#4"]); + assert!(split_line(" # only a comment").unwrap().is_empty()); + assert!(split_line("type \"open").is_err()); + } + + #[test] + fn unreachable_games_fail_with_status_3() { + let mut s = Session::new(std::env::temp_dir().join("horizon-ctl-nobody.sock"), None); + let f = s.run(&["state".to_owned()]).unwrap_err(); + assert_eq!(f.status, UNREACHABLE); + assert_eq!(f.reply["kind"], "connection"); + let f = s.run(&["sleep".to_owned(), "x".to_owned()]).unwrap_err(); + assert_eq!(f.status, USAGE); + } + + #[test] + fn screenshot_paths_become_absolute() { + let mut words = vec!["screenshot".to_owned(), "a.png".to_owned()]; + absolute_paths(&mut words); + assert!(Path::new(&words[1]).is_absolute()); + } } diff --git a/crates/horizon-client/src/bin/horizon-ctl/mcp.rs b/crates/horizon-client/src/bin/horizon-ctl/mcp.rs new file mode 100644 index 000000000..492377fe7 --- /dev/null +++ b/crates/horizon-client/src/bin/horizon-ctl/mcp.rs @@ -0,0 +1,238 @@ +//! `horizon-ctl mcp`: the Model Context Protocol over stdin and stdout +//! (JSON-RPC 2.0, one message per line, like the launcher's `mcp`), so AI +//! agents can play Horizon. Each tool is a horizon-ctl command from the +//! shared table, run through the same `Session` as the CLI. +use crate::{Session, commands}; +use serde_json::{Value, json}; +use std::io::{BufRead, Write}; + +const PROTOCOL: &str = "2025-06-18"; + +fn tools() -> Vec { + commands::COMMANDS + .iter() + .filter(|c| c.mcp) + .map(|c| { + let mut description = format!("{}. Usage: horizon-ctl {}", capital(c.summary), c.usage); + if !c.details.is_empty() { + description.push_str(". "); + description.push_str(c.details); + } + let mut schema = commands::schema(c); + if c.name == "screenshot" { + schema = json!({ "type": "object", "properties": {} }); + description = "Capture the game window and return it as a PNG image.".into(); + } + json!({ "name": commands::tool_name(c), "description": description, "inputSchema": schema }) + }) + .collect() +} + +fn capital(s: &str) -> String { + let mut c = s.chars(); + c.next() + .map(|f| f.to_uppercase().chain(c).collect()) + .unwrap_or_default() +} + +/// Standard base64 (RFC 4648) for image content. +pub fn base64(bytes: &[u8]) -> String { + const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); + for chunk in bytes.chunks(3) { + let n = (u32::from(chunk[0]) << 16) + | (u32::from(*chunk.get(1).unwrap_or(&0)) << 8) + | u32::from(*chunk.get(2).unwrap_or(&0)); + for i in 0..4 { + if i <= chunk.len() { + out.push(ALPHABET[(n >> (18 - 6 * i) & 63) as usize] as char); + } else { + out.push('='); + } + } + } + out +} + +impl Session { + /// One tool call: (content blocks, is_error). + fn call(&mut self, name: &str, args: &Value) -> (Vec, bool) { + let text = |v: &Value| json!({ "type": "text", "text": serde_json::to_string_pretty(v).unwrap_or_default() }); + let Some(cmd) = commands::COMMANDS + .iter() + .find(|c| c.mcp && commands::tool_name(c) == name) + else { + return ( + vec![text(&json!({ "error": format!("unknown tool {name}") }))], + true, + ); + }; + if cmd.name == "screenshot" { + let path = std::env::temp_dir().join(format!("horizon-ctl-{}.png", std::process::id())); + let result = self + .run(&["screenshot".to_owned(), path.display().to_string()]) + .and_then(|reply| { + std::fs::read(&path) + .map(|png| (reply, png)) + .map_err(|e| crate::Failure { + reply: json!({ "error": format!("{}: {e}", path.display()) }), + status: 1, + }) + }); + let _ = std::fs::remove_file(&path); + return match result { + Ok((reply, png)) => ( + vec![ + json!({ "type": "image", "data": base64(&png), "mimeType": "image/png" }), + text(&reply), + ], + false, + ), + Err(f) => (vec![text(&f.reply)], true), + }; + } + let mut words = match commands::line_for(cmd, args) { + Ok(w) => w, + Err(e) => return (vec![text(&json!({ "error": e, "kind": "usage" }))], true), + }; + if cmd.name == "launch" { + // An agent wants a world it can play once the call returns. + if args.get("wait").and_then(Value::as_bool) != Some(false) + && !words.contains(&"--wait".to_owned()) + { + words.push("--wait".into()); + } + words.push("--no-pause".into()); + } + match self.run(&words) { + Ok(reply) => (vec![text(&reply)], false), + Err(f) => (vec![text(&f.reply)], true), + } + } + + fn handle(&mut self, method: &str, params: &Value) -> Result { + match method { + "initialize" => Ok(json!({ + "protocolVersion": params.get("protocolVersion").and_then(Value::as_str).unwrap_or(PROTOCOL), + "capabilities": { "tools": {} }, + "serverInfo": { "name": "horizon-ctl", "version": env!("CARGO_PKG_VERSION") }, + "instructions": "Play Horizon, a Rust reimplementation of Minecraft Java Edition. Start with launch (it finds the game installed by the Horizon launcher and opens or creates a world), then read the world with state, inventory, screen, entities and find_block, and act with goto, look_at_block, break, place, interact, click_slot and click_button. Actions block until they finish and report what happened. Coordinates are block coordinates; yaw 0 faces south (+Z).", + })), + "ping" => Ok(json!({})), + "tools/list" => Ok(json!({ "tools": tools() })), + "tools/call" => { + let name = params + .get("name") + .and_then(Value::as_str) + .ok_or((-32602, "name is required".to_string()))?; + if !tools().iter().any(|t| t["name"] == name) { + return Err((-32602, format!("Unknown tool {name}"))); + } + let args = params.get("arguments").cloned().unwrap_or(json!({})); + let (content, error) = self.call(name, &args); + Ok(json!({ "content": content, "isError": error })) + } + _ => Err((-32601, format!("Method not found: {method}"))), + } + } +} + +pub fn serve(session: &mut Session) -> Result<(), String> { + let stdin = std::io::stdin(); + let mut stdout = std::io::stdout(); + for line in stdin.lock().lines() { + let Ok(line) = line else { break }; + if line.trim().is_empty() { + continue; + } + let reply = match serde_json::from_str::(&line) { + Err(e) => Some( + json!({ "jsonrpc": "2.0", "id": null, "error": { "code": -32700, "message": e.to_string() } }), + ), + Ok(msg) => { + let method = msg + .get("method") + .and_then(Value::as_str) + .unwrap_or_default(); + let params = msg.get("params").cloned().unwrap_or(json!({})); + // Notifications (no id) get no reply. + msg.get("id").cloned().map(|id| match session.handle(method, ¶ms) { + Ok(result) => json!({ "jsonrpc": "2.0", "id": id, "result": result }), + Err((code, message)) => json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } }), + }) + } + }; + if let Some(reply) = reply { + writeln!(stdout, "{reply}") + .and_then(|_| stdout.flush()) + .map_err(|e| e.to_string())?; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn base64_matches_rfc_4648() { + assert_eq!(base64(b""), ""); + assert_eq!(base64(b"f"), "Zg=="); + assert_eq!(base64(b"fo"), "Zm8="); + assert_eq!(base64(b"foo"), "Zm9v"); + assert_eq!(base64(b"foobar"), "Zm9vYmFy"); + } + + #[test] + fn tools_have_schemas_and_unique_names() { + let list = tools(); + let mut names = std::collections::HashSet::new(); + for t in &list { + assert!(names.insert(t["name"].as_str().unwrap().to_owned())); + assert_eq!(t["inputSchema"]["type"], "object"); + } + for want in [ + "launch", + "state", + "goto", + "break_block", + "place", + "click_slot", + "click_button", + "screenshot", + "inventory", + ] { + let want = if want == "break_block" { "break" } else { want }; + assert!(names.contains(want), "{want}"); + } + } + + #[test] + fn protocol_basics() { + let mut s = Session::new(std::env::temp_dir().join("horizon-ctl-mcp-test.sock"), None); + let init = s + .handle("initialize", &json!({ "protocolVersion": "2025-03-26" })) + .unwrap(); + assert_eq!(init["protocolVersion"], "2025-03-26"); + assert!(s.handle("nope", &json!({})).is_err()); + let r = s + .handle( + "tools/call", + &json!({ "name": "goto", "arguments": { "x": 1 } }), + ) + .unwrap(); + assert_eq!(r["isError"], true); + assert!( + r["content"][0]["text"] + .as_str() + .unwrap() + .contains("y is required") + ); + // No game: a connection error, reported as a tool error. + let r = s + .handle("tools/call", &json!({ "name": "state", "arguments": {} })) + .unwrap(); + assert_eq!(r["isError"], true); + } +}