diff --git a/crates/horizon-client/src/bin/horizon-ctl/commands.rs b/crates/horizon-client/src/bin/horizon-ctl/commands.rs index 230cbc880..5d5d3c7ed 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/commands.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/commands.rs @@ -32,16 +32,18 @@ pub enum Group { Move, Act, Screens, + Multiplayer, World, Scripting, } impl Group { - pub const ALL: [Group; 7] = [ + pub const ALL: [Group; 8] = [ Group::Session, Group::Observe, Group::Move, Group::Act, Group::Screens, + Group::Multiplayer, Group::World, Group::Scripting, ]; @@ -52,6 +54,7 @@ impl Group { Group::Move => "Move and look", Group::Act => "Act on the world", Group::Screens => "Screens, menus and chat", + Group::Multiplayer => "Multiplayer, LAN and friends", Group::World => "World and cheats", Group::Scripting => "Scripting and benchmarks", } @@ -117,6 +120,49 @@ const OVER: Param = flag( "turn with mouse motion spread over this many seconds (eased), as a player would", ); const FACE: Ty = Ty::Enum(&["down", "up", "north", "south", "west", "east"]); +const BOX: [Param; 6] = [ + 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"), +]; +const PAGES: Ty = Ty::Enum(&[ + "main", + "video", + "sound", + "controls", + "keybinds", + "controller", + "controller-binds", + "mouse", + "chat", + "accessibility", + "language", + "font", + "packs", + "mods", + "graphics", + "graphics-advanced", + "extras", + "horizon", + "shader-packs", +]); + +/// `--confirm`, required by destructive commands: the player agreed. +const CONFIRM: Param = Param { + name: "confirm", + ty: Ty::Bool, + required: true, + flag: true, + help: "true once the player agreed: it cannot be undone", +}; + +/// MCP tools that delete or overwrite the player's things (`destructiveHint`). +pub const DESTRUCTIVE: &[&str] = &["world-delete", "fill", "setblock"]; +/// MCP tools that reach other players or the network (`openWorldHint`): only when the player asks. +pub const OPEN_WORLD: &[&str] = &["connect", "lan", "friends", "chat", "command"]; 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)?) => { @@ -164,7 +210,19 @@ pub const COMMANDS: &[Cmd] = &[ &[flag("lines", Ty::Int, "how many lines of latest.log (default 100)"), flag("crash", Ty::Bool, "the newest crash report instead")], 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), + "Also what F3 shows: the overlay flags, the renderer, chunk streaming and memory.", ["horizon-ctl status"], &[], mcp: true, local: false), + cmd!("worlds", Session, "worlds", "the saved worlds, newest first: folder, name, mode, last played, version", + "folder is what open, world-rename, world-backup and world-delete take.", ["horizon-ctl worlds"], &[], mcp: true, local: false), + cmd!("world-rename", Session, "world-rename FOLDER NAME", "rename a world, as Edit World does (its folder stays)", + "Needs the title screen (no world open).", ["horizon-ctl world-rename Test \"My Base\""], + &[p("folder", Ty::Str, "world folder from worlds"), p("name", Ty::Rest, "the new name")], mcp: true, local: false), + cmd!("world-backup", Session, "world-backup FOLDER", "zip a world into backups/, as Edit World's Make Backup does", + "Needs the title screen. Replies once the zip is written, with its size.", ["horizon-ctl world-backup Test"], + &[p("folder", Ty::Str, "world folder from worlds")], mcp: true, local: false), + cmd!("world-delete", Session, "world-delete FOLDER --confirm", "delete a world for good, as Select World's Delete does", + "Needs the title screen and --confirm: ask the player first, it cannot be undone (world-backup keeps a copy).", + ["horizon-ctl world-delete Test --confirm"], + &[p("folder", Ty::Str, "world folder from worlds"), CONFIRM], mcp: true, 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"], @@ -190,10 +248,10 @@ pub const COMMANDS: &[Cmd] = &[ cmd!("light", Observe, "light X1 Y1 Z1 X2 Y2 Z2", "the stored sky and block light of a box", "At most 32768 blocks per request. One hex digit per block in `sky` and `block`, x fastest, then z, then y; `.` where no chunk is loaded.", ["horizon-ctl light 0 64 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), + &BOX, 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), + &BOX, 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"], @@ -264,12 +322,15 @@ pub const COMMANDS: &[Cmd] = &[ "down holds the key until key ... up, release or stop; wait does not release it. move, goto, jump, break and the other actions release the movement keys when they end.", ["horizon-ctl key space tap"], &[p("key", Ty::Str, "key name"), p("action", Ty::Enum(&["down", "up", "tap", "repeat"]), "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), + ["horizon-ctl mouse right click"], &[p("button", Ty::Enum(&["left", "right", "middle"]), "button"), p("action", Ty::Enum(&["down", "up", "click"]), "what to do")], mcp: true, local: false), + cmd!("interact-entity", Act, "interact-entity ID", "right-click an entity: trade with a villager, mount a horse, ride a boat, shear a sheep", + "Faces the entity (from entities), right-clicks it with the held item, waits two ticks and replies with the screen.", + ["horizon-ctl interact-entity 42"], &[p("id", Ty::Int, "entity id from entities")], mcp: true, local: true), cmd!("pad", Act, "pad BUTTON down|up|tap | pad stick left|right X Y | pad trigger left|right V | pad release | pad status", "a virtual controller: buttons, sticks and triggers as a real pad would send them", "Buttons by position: south east west north lb rb lt rt select start ls rs up down left right (south is Xbox A / PlayStation cross). Sticks run -1..1 with up positive and stay tilted until centred; triggers 0..1. Merged with any real controller; status lists the connected ones and what is held.", ["horizon-ctl pad south tap", "horizon-ctl pad stick left 0 1", "horizon-ctl pad trigger right 1", "horizon-ctl pad status"], - &[p("what", Ty::Str, "a button name, stick, trigger, release or status"), opt("a", Ty::Str, "down|up|tap, or left|right"), opt("b", Ty::Num, "stick X or trigger value"), opt("c", Ty::Num, "stick Y")], mcp: false, local: false), - cmd!("release", Act, "release", "release every key and mouse button", "", ["horizon-ctl release"], &[], mcp: false, local: false), + &[p("what", Ty::Str, "a button name, stick, trigger, release or status"), opt("a", Ty::Str, "down|up|tap, or left|right"), opt("b", Ty::Num, "stick X or trigger value"), opt("c", Ty::Num, "stick Y")], mcp: true, local: false), + cmd!("release", Act, "release", "release every key and mouse button", "", ["horizon-ctl release"], &[], mcp: true, 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)", "", @@ -317,7 +378,31 @@ pub const COMMANDS: &[Cmd] = &[ 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!("options", Screens, "options [PAGE]", "open the options screen, or one of its pages (Horizon's too)", + "Then ui lists its widgets and click, set and type change them, as with the mouse. options-set changes an options.txt value without the screen.", + ["horizon-ctl options video", "horizon-ctl options horizon"], &[opt("page", PAGES, "the page (default: the main options)")], mcp: true, local: false), + cmd!("book", Screens, "book [next|back|take|done]", "the open book or lectern: its page text, or press one of its buttons", + "", ["horizon-ctl book", "horizon-ctl book next"], &[opt("action", Ty::Enum(&["next", "back", "take", "done"]), "a button to press")], mcp: true, local: false), + cmd!("signedit", Screens, "signedit X Y Z [front|back]", "open the sign editor of the sign at X Y Z (then type and close)", + "", ["horizon-ctl signedit 3 64 1"], &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], opt("side", Ty::Enum(&["front", "back"]), "which side")], mcp: true, local: false), + cmd!("mount-menu", Screens, "mount-menu", "open the inventory of the horse, donkey, mule or llama being ridden", + "As the inventory key does while riding; also opens the nearest one's.", ["horizon-ctl mount-menu"], &[], 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), + // Multiplayer + cmd!("connect", Multiplayer, "connect ADDRESS [NAME]", "join a multiplayer server, or a friend's world by its invite code, from the title screen", + "ADDRESS is HOST[:PORT], or friend:CODE for an invite code. Only when the player asks: it reaches the network.", + ["horizon-ctl connect play.example.net", "horizon-ctl connect localhost:25565", "horizon-ctl connect friend:0B33K-Q405Q-..."], + &[p("address", Ty::Str, "HOST[:PORT] or friend:CODE"), opt("name", Ty::Str, "player name when offline")], mcp: true, local: false), + cmd!("disconnect", Multiplayer, "disconnect", "leave the server, back to the server list", "", ["horizon-ctl disconnect"], &[], mcp: true, local: false), + cmd!("servers", Multiplayer, "servers", "the Multiplayer screen's server list: name and address", + "Add, edit and remove them on the Multiplayer screen (click-button Multiplayer, then ui).", ["horizon-ctl servers"], &[], mcp: true, local: false), + cmd!("lan", Multiplayer, "lan open [PORT] [commands] [force] | lan close | lan status", "open the world to LAN (Open to LAN), stop, or see the guests", + "PORT 0 or none picks one; commands lets guests use cheats; force forces the game mode. Only when the player asks.", + ["horizon-ctl lan open", "horizon-ctl lan status", "horizon-ctl lan close"], + &[p("action", Ty::Enum(&["open", "close", "status"]), "what to do"), opt("port", Ty::Int, "port for open"), opt("commands", Ty::Bool, "allow cheats"), opt("force", Ty::Bool, "force the game mode")], mcp: true, local: false), + cmd!("friends", Multiplayer, "friends host|stop|status", "Play with Friends: share the open world behind an invite code, stop, or see who joined", + "status gives the code: share it only when the player asks. Friends join with connect friend:CODE.", + ["horizon-ctl friends host", "horizon-ctl friends status"], &[p("action", Ty::Enum(&["host", "stop", "status"]), "what to do")], mcp: true, 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), @@ -325,8 +410,20 @@ pub const COMMANDS: &[Cmd] = &[ &[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!("summon", World, "summon KIND [X Y Z] [baby]", "spawn a mob (in front of the player without a position)", "Replies with its id.", ["horizon-ctl summon cow", "horizon-ctl summon pig 10 64 3 baby"], + &[p("kind", Ty::Str, "mob type"), opt("x", Ty::Num, "X"), opt("y", Ty::Num, "Y"), opt("z", Ty::Num, "Z"), opt("baby", Ty::Bool, "a baby")], mcp: true, local: false), + cmd!("effect", World, "effect ID SECONDS [AMPLIFIER] | effect clear", "give a status effect, or clear them all", "", ["horizon-ctl effect speed 30 1", "horizon-ctl effect clear"], + &[p("id", Ty::Str, "effect id such as speed, or clear"), opt("seconds", Ty::Num, "duration"), opt("amplifier", Ty::Int, "level - 1 (default 0)")], mcp: true, local: false), + cmd!("effects", World, "effects", "the player's active status effects", "", ["horizon-ctl effects"], &[], mcp: true, local: false), + cmd!("xp", World, "xp LEVELS", "add experience levels (negative removes)", "", ["horizon-ctl xp 30"], &[p("levels", Ty::Int, "levels to add")], mcp: true, local: false), + cmd!("enchant", World, "enchant ID LEVEL", "enchant the held item (a book stores it)", "", ["horizon-ctl enchant sharpness 5"], + &[p("id", Ty::Str, "enchantment id"), p("level", Ty::Int, "level")], mcp: true, local: false), + cmd!("potion", World, "potion ITEM POTION", "give a potion item", "", ["horizon-ctl potion splash_potion healing"], + &[p("item", Ty::Enum(&["potion", "splash_potion", "lingering_potion", "tipped_arrow"]), "which item"), p("potion", Ty::Str, "potion id")], mcp: true, local: false), + cmd!("fill", World, "fill X1 Y1 Z1 X2 Y2 Z2 BLOCK", "set a box of loaded blocks", "", ["horizon-ctl fill 0 64 0 4 64 4 glass"], + &[BOX[0], BOX[1], BOX[2], BOX[3], BOX[4], BOX[5], p("block", Ty::Str, "block state")], mcp: true, local: false), + cmd!("container", World, "container X Y Z [ITEM COUNT]", "list a container's items, or add items to it", "", ["horizon-ctl container 3 64 1", "horizon-ctl container 3 64 1 diamond 3"], + &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], opt("item", Ty::Str, "item to add"), opt("count", Ty::Int, "how many")], mcp: true, 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)", "Keys and mouse buttons held with key ... down or mouse ... down stay held while it waits. Release them with key ... up, release or stop.", @@ -340,8 +437,8 @@ pub const COMMANDS: &[Cmd] = &[ 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!("bench", Scripting, "bench SECONDS", "reset frame stats, wait, reply with the summary", "", ["horizon-ctl bench 10"], &[p("seconds", Ty::Num, "how long to measure")], mcp: true, local: false), + cmd!("stats", Scripting, "stats [reset]", "frame-time summary since the last reset", "", ["horizon-ctl stats"], &[opt("reset", Ty::Bool, "start counting again")], mcp: true, local: false), cmd!("fly", Scripting, "fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH [raw]]", "fly the camera along a line, then reply with the frame summary", "The reply's tick_ms and tick_ms_max are the world's smoothed tick time over the flight (the server thread's when single player runs on one). With raw, the reply also lists every frame time in milliseconds (frame_ms).", ["horizon-ctl fly 0 100 0 500 100 0 20"], &[], mcp: false, local: false), @@ -402,6 +499,73 @@ pub fn detail(c: &Cmd) -> String { out } +/// The generated reference, docs/horizon-ctl-commands.md (`horizon-ctl help --markdown`). +pub fn markdown() -> String { + let cell = |s: &str| s.replace('|', "\\|"); + let mut out = String::from( + "\n\ + # horizon-ctl commands\n\n\ + Every command `horizon-ctl` takes, its MCP tool in `horizon-ctl mcp` (the launcher's \ + `horizon-launcher mcp` offers the same tools as `game_`, all but `launch`) and its \ + arguments. Positional arguments come first, in order; `--flags` after them. \ + `horizon-ctl help --game` lists the game's own commands, test hooks included. \ + Design rules and the full inventory: [agent-control.md](agent-control.md).\n", + ); + for group in Group::ALL { + out.push_str(&format!( + "\n## {}\n\n| Command | MCP tool | What it does | Arguments |\n| --- | --- | --- | --- |\n", + group.title() + )); + for c in COMMANDS.iter().filter(|c| c.group == group) { + let tool = if c.mcp { + let mut t = format!("`{}`", tool_name(c)); + if DESTRUCTIVE.contains(&c.name) { + t.push_str(" (destructive)"); + } else if OPEN_WORLD.contains(&c.name) { + t.push_str(" (network)"); + } + t + } else { + "CLI only".to_owned() + }; + let args: Vec = c + .params + .iter() + .map(|p| { + let ty = match p.ty { + Ty::Int => "integer".to_owned(), + Ty::Num => "number".to_owned(), + Ty::Str => "string".to_owned(), + Ty::Rest => "text".to_owned(), + Ty::Bool => "boolean".to_owned(), + Ty::Enum(v) => v.join(", "), + }; + let name = if p.flag { + format!("--{}", p.name) + } else { + p.name.to_owned() + }; + let need = if p.required { ", required" } else { "" }; + format!("`{name}` ({ty}{need}): {}", cell(p.help)) + }) + .collect(); + out.push_str(&format!( + "| `{}` | {} | {} | {} |\n", + cell(c.usage), + tool, + cell(&capitalize(c.summary)), + if args.is_empty() { + "none".to_owned() + } else { + args.join("
") + } + )); + } + } + out +} + fn capitalize(s: &str) -> String { let mut chars = s.chars(); chars @@ -640,6 +804,43 @@ mod tests { assert_eq!(tool_name(find("look-at-entity").unwrap()), "look_at_entity"); } + #[test] + fn the_generated_reference_is_up_to_date() { + let path = concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../docs/horizon-ctl-commands.md" + ); + let on_disk = std::fs::read_to_string(path).unwrap_or_default(); + assert!( + on_disk == markdown(), + "docs/horizon-ctl-commands.md is out of date: run `horizon-ctl help --markdown > docs/horizon-ctl-commands.md`" + ); + for c in COMMANDS { + assert!( + on_disk.contains(&format!("`{}", c.usage.replace('|', "\\|"))), + "{} undocumented", + c.name + ); + } + } + + #[test] + fn destructive_and_network_tools_exist() { + for name in DESTRUCTIVE.iter().chain(OPEN_WORLD) { + assert!(find(name).is_some_and(|c| c.mcp), "{name}"); + } + let delete = find("world-delete").unwrap(); + assert_eq!( + line_for(delete, &json!({ "folder": "A", "confirm": true })).unwrap(), + ["world-delete", "A", "--confirm"] + ); + let lan = find("lan").unwrap(); + assert_eq!( + line_for(lan, &json!({ "action": "open", "commands": true })).unwrap(), + ["lan", "open", "commands"] + ); + } + #[test] fn help_mentions_every_command() { let text = overview(); diff --git a/crates/horizon-client/src/bin/horizon-ctl/main.rs b/crates/horizon-client/src/bin/horizon-ctl/main.rs index 27d9d5ba1..9c2cab8fa 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/main.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/main.rs @@ -183,6 +183,18 @@ impl Session { thread::sleep(Duration::from_secs_f64(seconds.max(0.0))); self.game(&format!("key {key} up")) } + "interact-entity" => { + let id = match words { + [_, id] if id.parse::().is_ok() => id, + _ => return Err(Failure::usage(format!("usage: {}", usage(name)))), + }; + self.game(&format!("look-at entity {id}"))?; + self.game("mouse right click")?; + self.game("wait 2")?; + let mut screen = self.game("screen")?; + screen["ok"] = json!(true); + Ok(screen) + } "logs" => logs(&horizon_client::logging::game_home(), &words[1..]), "wait-ready" => { let limit = if words.len() > 1 { @@ -417,6 +429,10 @@ fn main() -> ExitCode { print!("{}", commands::overview()); 0 } + Some("help") if args.get(1).is_some_and(|a| a == "--markdown") => { + print!("{}", commands::markdown()); + 0 + } Some("help") if args.get(1).is_none_or(|a| a != "--game") => match args.get(1) { None => { print!("{}", commands::overview()); diff --git a/crates/horizon-client/src/bin/horizon-ctl/mcp.rs b/crates/horizon-client/src/bin/horizon-ctl/mcp.rs index 8d67953a5..ae30b7498 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/mcp.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/mcp.rs @@ -23,7 +23,13 @@ fn tools() -> Vec { 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 }) + let mut tool = json!({ "name": commands::tool_name(c), "description": description, "inputSchema": schema }); + if commands::DESTRUCTIVE.contains(&c.name) { + tool["annotations"] = json!({ "destructiveHint": true }); + } else if commands::OPEN_WORLD.contains(&c.name) { + tool["annotations"] = json!({ "openWorldHint": true }); + } + tool }) .collect() } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index ce9183cac..d43b04cac 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -126,6 +126,7 @@ mod remote_vehicles; mod render_control; mod render_tick; mod respawn_anchor; +mod saves_control; mod saving; mod scoreboard; mod screens; diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 6c5eec301..d25cb21ce 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -165,6 +165,9 @@ impl Game<'_> { if let Some(value) = self.events_command(&words, reply)? { return Ok(value); } + if let Some(value) = self.saves_control(&words, line, reply)? { + return Ok(value); + } if let Some(value) = self.options_control(&words, line)? { return Ok(Some(value)); } @@ -192,6 +195,7 @@ impl Game<'_> { .chain(super::ui_control::HELP) .chain(super::options::CONTROL_HELP) .chain(super::events::HELP) + .chain(super::saves_control::HELP) .chain(super::pad::HELP) .collect::>() }))), "setblock" | "fill" | "particle" | "signedit" => self.render_command(&words), diff --git a/crates/horizon-client/src/game/saves_control.rs b/crates/horizon-client/src/game/saves_control.rs new file mode 100644 index 000000000..5c0f0c6fa --- /dev/null +++ b/crates/horizon-client/src/game/saves_control.rs @@ -0,0 +1,123 @@ +//! Worlds and the multiplayer server list from the control socket: what the Select World, Edit +//! World and Multiplayer screens do, by world folder. Changing a world needs the title screen +//! (no world open), as those screens do; deleting one needs `--confirm`. +use super::Game; +use horizon_client::{Result, title}; +use serde_json::{Value, json}; +use std::{path::PathBuf, sync::mpsc::Sender, time::UNIX_EPOCH}; + +pub(super) const HELP: &[&str] = &[ + "worlds the saved worlds, newest first: folder, name, mode, last played, version", + "world-rename FOLDER NAME rename a world (Edit World; its folder stays)", + "world-backup FOLDER zip a world into backups/ (Edit World > Make Backup)", + "world-delete FOLDER --confirm delete a world for good (Select World > Delete)", + "servers the multiplayer server list (servers.dat): name and address", +]; + +fn saves() -> Result { + Ok(std::env::current_dir()?.join("saves")) +} + +impl Game<'_> { + /// Some(reply) for these commands (Some(None): the reply comes later), None for others. + pub(super) fn saves_control( + &mut self, + words: &[&str], + line: &str, + reply: &Sender, + ) -> Result>> { + let folder = || { + words + .get(1) + .copied() + .ok_or_else(|| format!("{} FOLDER: the folder from worlds", words[0])) + }; + let on_title = || { + if self.title.is_some() { + Ok(()) + } else { + Err(format!( + "{} needs the title screen: save and leave the world first (pause, then Save and Quit to Title)", + words[0] + )) + } + }; + let value = match words[0] { + "worlds" => { + let worlds: Vec = title::list_worlds(&saves()?) + .iter() + .map(|w| { + json!({ + "folder": w.folder, + "name": w.name, + "mode": if w.creative { "creative" } else { "survival" }, + "last_played": w.modified.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64), + "commands": w.commands, + "version": w.version, + }) + }) + .collect(); + json!({ "worlds": worlds }) + } + "world-rename" => { + on_title()?; + let folder = folder()?; + let name = line + .trim_start() + .strip_prefix("world-rename") + .and_then(|rest| rest.trim_start().strip_prefix(folder)) + .map(str::trim) + .filter(|n| !n.is_empty()) + .ok_or("world-rename FOLDER NAME: missing the new name")?; + title::world_management::rename(&saves()?, folder, name)?; + if let Some(title) = self.title.as_mut() { + title.worlds_changed(); + } + json!({ "ok": true, "folder": folder, "name": name }) + } + "world-delete" => { + on_title()?; + let folder = folder()?; + if !words.contains(&"--confirm") { + return Err(format!( + "world-delete deletes {folder} for good: ask the player, then add --confirm" + ) + .into()); + } + title::world_management::delete(&saves()?, folder)?; + if let Some(title) = self.title.as_mut() { + title.worlds_changed(); + } + json!({ "ok": true, "deleted": folder }) + } + "world-backup" => { + on_title()?; + let folder = folder()?.to_owned(); + let saves = saves()?; + let backups = title::world_management::backups_path(&saves); + // A big world takes a while to zip: off the game thread, as Make Backup does. + let reply = reply.clone(); + std::thread::spawn(move || { + let answer = match title::world_management::backup(&saves, &folder) { + Ok(bytes) => { + json!({ "ok": true, "folder": folder, "backups": backups, "bytes": bytes }) + } + Err(e) => json!({ "error": format!("backup of {folder} failed: {e}") }), + }; + let _ = reply.send(answer.to_string()); + }); + return Ok(Some(None)); + } + "servers" => { + let file = horizon_client::multiplayer::servers_file(&saves()?); + let servers: Vec = horizon_protocol::servers::load(&file) + .iter() + .map(|s| json!({ "name": s.name, "address": s.ip })) + .collect(); + json!({ "servers": servers }) + } + _ => return Ok(None), + }; + Ok(Some(Some(value))) + } +} diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index 8a04df67e..b4958c600 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -15,7 +15,7 @@ use std::{ mod create_world; #[cfg(test)] mod tests; -mod world_management; +pub mod world_management; pub use create_world::{DIFFICULTIES, WorldOptions}; /// SelectWorldScreen's `HeaderAndFooterLayout(8 + 9 + 8 + 20 + 4, 60)`. @@ -500,6 +500,14 @@ impl Title { } } /// The worlds, newest first, cached for two seconds (drawn every frame). + /// Saves changed behind the screens' back (agent control renamed or deleted a world): the + /// list shows them again. + pub fn worlds_changed(&mut self) { + if matches!(self.mode, Mode::Select { .. }) { + self.return_to_list(None); + } + *self.recent.borrow_mut() = None; + } pub fn recent_worlds(&self) -> Vec { let mut recent = self.recent.borrow_mut(); match &*recent { diff --git a/crates/horizon-client/src/title/world_management.rs b/crates/horizon-client/src/title/world_management.rs index d5fc9bc58..abdd35505 100644 --- a/crates/horizon-client/src/title/world_management.rs +++ b/crates/horizon-client/src/title/world_management.rs @@ -23,7 +23,7 @@ fn world_path(saves: &Path, folder: &str) -> crate::Result { Ok(path) } -pub(super) fn rename(saves: &Path, folder: &str, name: &str) -> crate::Result<()> { +pub fn rename(saves: &Path, folder: &str, name: &str) -> crate::Result<()> { let path = world_path(saves, folder)?.join("level.dat"); let mut root = read_dat(&path).ok_or("Could not read level.dat")?; let Some(Tag::Compound(data)) = root.get_mut("Data") else { @@ -45,7 +45,7 @@ pub(super) fn reset_icon(saves: &Path, folder: &str) -> crate::Result<()> { /// file briefly held by a virus scanner, say) is retried up to five times, /// half a second apart, as vanilla does. Only the named folder directly in /// `saves` is touched: symbolic links inside it are removed, never followed. -pub(super) fn delete(saves: &Path, folder: &str) -> crate::Result<()> { +pub fn delete(saves: &Path, folder: &str) -> crate::Result<()> { let world = world_path(saves, folder)?; let lock = crate::save::SessionLock::acquire(&world)?; let lock_path = world.join("session.lock"); @@ -86,7 +86,7 @@ fn remove_contents(world: &Path, lock: &Path) -> io::Result<()> { Ok(()) } -pub(super) fn backups_path(saves: &Path) -> PathBuf { +pub fn backups_path(saves: &Path) -> PathBuf { saves.parent().unwrap_or(saves).join("backups") } @@ -112,7 +112,7 @@ pub(super) fn open_folder(path: &Path) -> crate::Result<()> { Ok(()) } -pub(super) fn backup(saves: &Path, folder: &str) -> crate::Result { +pub fn backup(saves: &Path, folder: &str) -> crate::Result { let world = world_path(saves, folder)?; let backups = backups_path(saves); fs::create_dir_all(&backups)?; diff --git a/docs/horizon-ctl-commands.md b/docs/horizon-ctl-commands.md new file mode 100644 index 000000000..c53016824 --- /dev/null +++ b/docs/horizon-ctl-commands.md @@ -0,0 +1,140 @@ + +# horizon-ctl commands + +Every command `horizon-ctl` takes, its MCP tool in `horizon-ctl mcp` (the launcher's `horizon-launcher mcp` offers the same tools as `game_`, all but `launch`) and its arguments. Positional arguments come first, in order; `--flags` after them. `horizon-ctl help --game` lists the game's own commands, test hooks included. Design rules and the full inventory: [agent-control.md](agent-control.md). + +## Session + +| Command | MCP tool | What it does | Arguments | +| --- | --- | --- | --- | +| `launch [--world NAME] [--seed N] [--creative] [--version TAG] [--game PATH] [--wait] [GAME ARGS...]` | `launch` | Start Horizon with the control socket and wait until it answers | `--world` (string): world folder to open or create
`--seed` (string): seed for a new world
`--creative` (boolean): creative mode for a new world
`--version` (string): an installed launcher version tag such as v2026.10.13
`--game` (string): path to a horizon-client binary
`--wait` (boolean): also wait until the world is ready (default in MCP)
`--offscreen` (boolean): render without showing a window (screenshots still work): locked or headless sessions | +| `wait-for screen NAME\|widget ID\|loaded\|chat TEXT\|event KIND [--timeout S] [--since SEQ]` | `wait_for` | Wait until the game reaches a state, then reply | `--timeout` (number): seconds (default 30)
`--since` (integer): chat and event: count from this event seq
`condition` (screen, widget, loaded, chat, event, required): what to wait for
`value` (text): the screen name, widget id, chat text or event kind | +| `wait-ready [SECONDS]` | `wait_ready` | Wait until the player has spawned and no chunks are pending | `seconds` (number): how long to wait (default 120) | +| `logs [--lines N] [--crash]` | `logs` | The end of the game's log, or its newest crash report | `--lines` (integer): how many lines of latest.log (default 100)
`--crash` (boolean): the newest crash report instead | +| `status` | `status` | Game, renderer and streaming state (the scripting socket's original summary) | none | +| `worlds` | `worlds` | The saved worlds, newest first: folder, name, mode, last played, version | none | +| `world-rename FOLDER NAME` | `world_rename` | Rename a world, as Edit World does (its folder stays) | `folder` (string, required): world folder from worlds
`name` (text, required): the new name | +| `world-backup FOLDER` | `world_backup` | Zip a world into backups/, as Edit World's Make Backup does | `folder` (string, required): world folder from worlds | +| `world-delete FOLDER --confirm` | `world_delete` (destructive) | Delete a world for good, as Select World's Delete does | `folder` (string, required): world folder from worlds
`--confirm` (boolean, required): true once the player agreed: it cannot be undone | +| `open WORLD [SEED] [creative]` | `open` | Open or create a world from the title screen | `world` (string, required): world folder
`seed` (integer): seed for a new world
`mode` (creative): creative for a creative world | +| `save` | `save` | Save the world | none | +| `quit` | `quit` | Save and exit the game | none | +| `screenshot PATH` | `screenshot` | Write the next rendered frame as a PNG | none | + +## Observe (JSON state) + +| Command | MCP tool | What it does | Arguments | +| --- | --- | --- | --- | +| `events [--since SEQ]` | `events` | What happened since SEQ, oldest first: screens, chat, deaths, respawns, items gained or lost, dimensions, worlds | `--since` (integer): only events after this seq | +| `state` | `state` | Player, world, screen and crosshair target in one reply | none | +| `looking-at` | `looking_at` | The block or entity under the crosshair | none | +| `entities [RADIUS] [TYPE]` | `entities` | Mobs, dropped items and experience orbs near the player, nearest first | `radius` (number): search radius in blocks (default 32)
`type` (string): entity type filter | +| `block X Y Z` | `block` | The block state at a position | `x` (integer, required): block X
`y` (integer, required): block Y
`z` (integer, required): block Z | +| `light X1 Y1 Z1 X2 Y2 Z2` | `light` | The stored sky and block light of a box | `x1` (integer, required): corner X
`y1` (integer, required): corner Y
`z1` (integer, required): corner Z
`x2` (integer, required): opposite X
`y2` (integer, required): opposite Y
`z2` (integer, required): opposite Z | +| `blocks X1 Y1 Z1 X2 Y2 Z2` | `blocks` | The non-air blocks of a box, with counts per block | `x1` (integer, required): corner X
`y1` (integer, required): corner Y
`z1` (integer, required): corner Z
`x2` (integer, required): opposite X
`y2` (integer, required): opposite Y
`z2` (integer, required): opposite Z | +| `find-block BLOCK [RADIUS]` | `find_block` | The nearest loaded blocks of a kind | `block` (string, required): block id such as oak_log
`radius` (integer): search radius (default 32) | +| `inventory` | `inventory` | Hotbar, main inventory, armor, offhand, carried stack and item counts | none | +| `screen` | `screen` | The open screen or title menu, its buttons and its slots | none | +| `messages [N]` | `messages` | Recent chat and system messages, the title and the action bar | `n` (integer): how many chat lines (default 20) | +| `menu` | CLI only | The open menu's slots and carried stack, with station details | none | + +## Move and look + +| Command | MCP tool | What it does | Arguments | +| --- | --- | --- | --- | +| `move forward\|back\|left\|right SECONDS [--sprint] [--sneak] [--jump]` | `move` | Walk in a direction relative to the view for a time | `direction` (forward, back, left, right, required): direction relative to the view
`seconds` (number, required): how long to walk
`--sprint` (boolean): sprint
`--sneak` (boolean): sneak
`--jump` (boolean): keep jumping | +| `goto X Y Z [--near R] [--sprint] [--direct] [--timeout S]` | `goto` | Walk to a position, finding a path through loaded terrain | `x` (number, required): X coordinate
`y` (number, required): Y coordinate
`z` (number, required): Z coordinate
`--near` (number): arrive within this many blocks (default 0.6)
`--sprint` (boolean): sprint
`--direct` (boolean): walk straight when no path is found
`--timeout` (number): give up after this many seconds (default 60) | +| `jump` | `jump` | Jump once and reply when landed | none | +| `look YAW PITCH` | `look` | Set the view direction in degrees | `yaw` (number, required): yaw in degrees
`pitch` (number, required): pitch in degrees (-90 up .. 90 down) | +| `turn DYAW DPITCH [--over S]` | `turn` | Rotate the view by an amount | `dyaw` (number, required): yaw change in degrees
`dpitch` (number, required): pitch change in degrees
`--over` (number): turn with mouse motion spread over this many seconds (eased), as a player would | +| `mouse-move DX DY` | `mouse_move` | Move the mouse: relative motion that turns the view like a player's mouse | `dx` (number, required): horizontal motion (positive turns right)
`dy` (number, required): vertical motion (positive looks down) | +| `look-at X Y Z \| look-at block X Y Z [FACE] \| look-at entity ID [--over S]` | `look_at` | Turn to face a point, a block (a visible face of it) or an entity | `x` (number, required): X coordinate
`y` (number, required): Y coordinate
`z` (number, required): Z coordinate
`--over` (number): turn with mouse motion spread over this many seconds (eased), as a player would | +| `look-at-block X Y Z [FACE] [--over S]` | `look_at_block` | Aim the crosshair at a block (same as look-at block) | `x` (integer, required): block X
`y` (integer, required): block Y
`z` (integer, required): block Z
`face` (down, up, north, south, west, east): which face to aim at
`--over` (number): turn with mouse motion spread over this many seconds (eased), as a player would | +| `look-at-entity ID [--over S]` | `look_at_entity` | Face an entity (same as look-at entity) | `id` (integer, required): entity id from entities
`--over` (number): turn with mouse motion spread over this many seconds (eased), as a player would | +| `tp X Y Z` | `tp` | Teleport the player | `x` (number, required): X coordinate
`y` (number, required): Y coordinate
`z` (number, required): Z coordinate | + +## Act on the world + +| Command | MCP tool | What it does | Arguments | +| --- | --- | --- | --- | +| `break X Y Z [--timeout S]` | `break` | Mine a block, holding the attack button until it breaks | `x` (integer, required): block X
`y` (integer, required): block Y
`z` (integer, required): block Z
`--timeout` (number): give up after this many seconds (default 30) | +| `place X Y Z [--item ITEM]` | `place` | Place the held item (or ITEM from the hotbar) at an empty position | `x` (integer, required): block X
`y` (integer, required): block Y
`z` (integer, required): block Z
`--item` (string): hotbar item to select first | +| `interact X Y Z [FACE]` | `interact` | Right-click a block: open a chest or crafting table, press a button, open a door | `x` (integer, required): block X
`y` (integer, required): block Y
`z` (integer, required): block Z
`face` (down, up, north, south, west, east): which face to click | +| `use-item [--hold SECONDS]` | `use_item` | Right-click with the held item: eat, drink, throw, draw a bow | `--hold` (number): hold the button this long | +| `attack [ID]` | `attack` | Swing at what the crosshair targets (after facing entity ID) | `id` (integer): entity id to face first | +| `select SLOT\|ITEM` | `select` | Select a hotbar slot 1-9, or the hotbar slot holding ITEM | `slot` (string, required): 1-9 or an item id | +| `drop [all]` | `drop` | Drop one of the held item, or the whole stack | `all` (boolean): drop the whole stack | +| `hold KEY SECONDS` | CLI only | Press a key, wait, release it | `key` (string, required): key name
`seconds` (number, required): how long | +| `key KEY down\|up\|tap\|repeat` | `key` | Press, release or auto-repeat a key (w a s d space shift ctrl e q esc f3 1-9 arrows ...) | `key` (string, required): key name
`action` (down, up, tap, repeat, required): what to do | +| `mouse left\|right\|middle down\|up\|click` | `mouse` | Press or release a mouse button in the world | `button` (left, right, middle, required): button
`action` (down, up, click, required): what to do | +| `interact-entity ID` | `interact_entity` | Right-click an entity: trade with a villager, mount a horse, ride a boat, shear a sheep | `id` (integer, required): entity id from entities | +| `pad BUTTON down\|up\|tap \| pad stick left\|right X Y \| pad trigger left\|right V \| pad release \| pad status` | `pad` | A virtual controller: buttons, sticks and triggers as a real pad would send them | `what` (string, required): a button name, stick, trigger, release or status
`a` (string): down\|up\|tap, or left\|right
`b` (number): stick X or trigger value
`c` (number): stick Y | +| `release` | `release` | Release every key and mouse button | none | +| `stop` | `stop` | Cancel the running action (goto, break...) and release every key | none | + +## Screens, menus and chat + +| Command | MCP tool | What it does | Arguments | +| --- | --- | --- | --- | +| `open-inventory` | `open_inventory` | Open the inventory screen (crafting grid 100-103, result 200) | none | +| `click-slot SLOT [right] [shift]` | `click_slot` | Click a slot of the open inventory or menu | `slot` (integer, required): slot id
`right` (boolean): right-click
`shift` (boolean): shift-click | +| `close` | `close` | Close the open menu and return to the game | none | +| `ui` | `ui` | Every widget of the open screen: id, kind, label, bounds, value | none | +| `click ID [right\|middle] [shift]` | `click` | Click a widget of ui by its id, as the mouse would | `id` (string, required): widget id from ui
`right` (boolean): right-click
`middle` (boolean): middle-click
`shift` (boolean): shift-click (slots) | +| `set ID VALUE` | `set` | Move a slider of ui to VALUE (0..1), as a click on its track | `id` (string, required): slider id from ui
`value` (number, required): 0..1 along the track | +| `options-get [KEY...]` | `options_get` | The game's options (options.txt) by key, with their type and range or choices | `keys` (text): option keys (default: all) | +| `options-set KEY VALUE` | `options_set` | Set one option, apply it at once and save options.txt, as the options screen does | `key` (string, required): option key from options-get
`value` (text, required): the new value | +| `click-button LABEL` | `click_button` | Click a button of the open screen or title menu by its label | `label` (text, required): button label | +| `click-at X Y [right]` | `click_at` | Click at GUI pixel X Y of the window (screen gives button rectangles) | `x` (number, required): GUI x
`y` (number, required): GUI y
`right` (boolean): right-click | +| `drag-at [right] X Y X Y...` | `drag_at` | Press at the first GUI point, move through the others, release at the last | `points` (text, required): right, then GUI x y pairs | +| `scroll-at X Y STEPS` | `scroll_at` | Turn the mouse wheel at GUI pixel X Y (positive scrolls up) | `x` (number, required): GUI x
`y` (number, required): GUI y
`steps` (number, required): wheel steps | +| `type [--field name\|seed] [--replace] TEXT` | `type` | Type into the focused text field (chat box, world name, anvil, sign...) | `--field` (name, seed): create-world field to type into
`--replace` (boolean): clear the field first
`text` (text, required): text to type | +| `chat TEXT` | `chat` (network) | Send a chat line (or a /command) as if typed | `text` (text, required): message | +| `command TEXT` | `command` (network) | Run a command (the leading / is optional) | `command` (text, required): command line | +| `respawn` | `respawn` | Respawn from the death screen | none | +| `pause` | `pause` | Open the pause menu | none | +| `resume` | `resume` | Leave the pause menu | none | +| `options [PAGE]` | `options` | Open the options screen, or one of its pages (Horizon's too) | `page` (main, video, sound, controls, keybinds, controller, controller-binds, mouse, chat, accessibility, language, font, packs, mods, graphics, graphics-advanced, extras, horizon, shader-packs): the page (default: the main options) | +| `book [next\|back\|take\|done]` | `book` | The open book or lectern: its page text, or press one of its buttons | `action` (next, back, take, done): a button to press | +| `signedit X Y Z [front\|back]` | `signedit` | Open the sign editor of the sign at X Y Z (then type and close) | `x` (integer, required): block X
`y` (integer, required): block Y
`z` (integer, required): block Z
`side` (front, back): which side | +| `mount-menu` | `mount_menu` | Open the inventory of the horse, donkey, mule or llama being ridden | none | +| `chat-log [N]` | CLI only | The newest N chat messages | none | + +## Multiplayer, LAN and friends + +| Command | MCP tool | What it does | Arguments | +| --- | --- | --- | --- | +| `connect ADDRESS [NAME]` | `connect` (network) | Join a multiplayer server, or a friend's world by its invite code, from the title screen | `address` (string, required): HOST[:PORT] or friend:CODE
`name` (string): player name when offline | +| `disconnect` | `disconnect` | Leave the server, back to the server list | none | +| `servers` | `servers` | The Multiplayer screen's server list: name and address | none | +| `lan open [PORT] [commands] [force] \| lan close \| lan status` | `lan` (network) | Open the world to LAN (Open to LAN), stop, or see the guests | `action` (open, close, status, required): what to do
`port` (integer): port for open
`commands` (boolean): allow cheats
`force` (boolean): force the game mode | +| `friends host\|stop\|status` | `friends` (network) | Play with Friends: share the open world behind an invite code, stop, or see who joined | `action` (host, stop, status, required): what to do | + +## World and cheats + +| Command | MCP tool | What it does | Arguments | +| --- | --- | --- | --- | +| `give ITEM [COUNT]` | `give` | Add items to the inventory | `item` (string, required): item id
`count` (integer): how many (default 1) | +| `time TICKS` | `time` | Set the time of day (0 sunrise, 6000 noon, 13000 night) | `ticks` (integer, required): day time | +| `setblock X Y Z BLOCK[props]` | `setblock` (destructive) | Set a block (with neighbour updates) | `x` (integer, required): block X
`y` (integer, required): block Y
`z` (integer, required): block Z
`block` (string, required): block state such as oak_stairs[facing=east] | +| `summon KIND [X Y Z] [baby]` | `summon` | Spawn a mob (in front of the player without a position) | `kind` (string, required): mob type
`x` (number): X
`y` (number): Y
`z` (number): Z
`baby` (boolean): a baby | +| `effect ID SECONDS [AMPLIFIER] \| effect clear` | `effect` | Give a status effect, or clear them all | `id` (string, required): effect id such as speed, or clear
`seconds` (number): duration
`amplifier` (integer): level - 1 (default 0) | +| `effects` | `effects` | The player's active status effects | none | +| `xp LEVELS` | `xp` | Add experience levels (negative removes) | `levels` (integer, required): levels to add | +| `enchant ID LEVEL` | `enchant` | Enchant the held item (a book stores it) | `id` (string, required): enchantment id
`level` (integer, required): level | +| `potion ITEM POTION` | `potion` | Give a potion item | `item` (potion, splash_potion, lingering_potion, tipped_arrow, required): which item
`potion` (string, required): potion id | +| `fill X1 Y1 Z1 X2 Y2 Z2 BLOCK` | `fill` (destructive) | Set a box of loaded blocks | `x1` (integer, required): corner X
`y1` (integer, required): corner Y
`z1` (integer, required): corner Z
`x2` (integer, required): opposite X
`y2` (integer, required): opposite Y
`z2` (integer, required): opposite Z
`block` (string, required): block state | +| `container X Y Z [ITEM COUNT]` | `container` | List a container's items, or add items to it | `x` (integer, required): block X
`y` (integer, required): block Y
`z` (integer, required): block Z
`item` (string): item to add
`count` (integer): how many | +| `render-distance N` | CLI only | Chunks, 2..64 | `chunks` (integer, required): render distance | +| `wait TICKS` | `wait` | Wait until TICKS game ticks have passed (20 per second) | `ticks` (integer, required): game ticks | + +## Scripting and benchmarks + +| Command | MCP tool | What it does | Arguments | +| --- | --- | --- | --- | +| `script [FILE] [--keep-going]` | CLI only | Run commands from FILE (or stdin), one per line | none | +| `sleep SECONDS` | CLI only | Wait (in scripts) | none | +| `mcp` | CLI only | Serve the Model Context Protocol on stdin/stdout, one tool per command | none | +| `bench SECONDS` | `bench` | Reset frame stats, wait, reply with the summary | `seconds` (number, required): how long to measure | +| `stats [reset]` | `stats` | Frame-time summary since the last reset | `reset` (boolean): start counting again | +| `fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH [raw]]` | CLI only | Fly the camera along a line, then reply with the frame summary | none | diff --git a/tools/agent_control_e2e.py b/tools/agent_control_e2e.py index f4c7acaa9..46695e8c3 100644 --- a/tools/agent_control_e2e.py +++ b/tools/agent_control_e2e.py @@ -52,10 +52,13 @@ POSITIONAL = { 'click_button': ['label'], 'type': ['text'], 'wait': ['ticks'], 'wait_ready': ['seconds'], 'command': ['command'], 'look_at_block': ['x', 'y', 'z'], 'click': ['id'], 'set': ['id', 'value'], 'give': ['item', 'count'], 'options_get': ['keys'], 'options_set': ['key', 'value'], - 'wait_for': ['condition', 'value'], + 'wait_for': ['condition', 'value'], 'open': ['world', 'seed', 'mode'], 'select': ['slot'], + 'summon': ['kind', 'x', 'y', 'z'], 'interact_entity': ['id'], 'effect': ['id', 'seconds', 'amplifier'], + 'xp': ['levels'], 'options': ['page'], 'lan': ['action'], 'world_backup': ['folder'], + 'world_rename': ['folder', 'name'], 'world_delete': ['folder'], } # Booleans the game takes as bare words. -BARE = {'click_slot': ['right', 'shift'], 'click': ['right', 'middle', 'shift']} +BARE = {'click_slot': ['right', 'shift'], 'click': ['right', 'middle', 'shift'], 'summon': ['baby']} class Failed(Exception): @@ -567,8 +570,54 @@ def suggestions_scenario(d, out): return {'completions': len(cases)} +def manage_scenario(d, out): + # The commands that close the audit's gaps: status (F3), entities by right-click, effects and xp, + # LAN status, options pages by name, then from the title screen the worlds list, Make Backup, + # rename and a delete that needs the player's confirmation. + d('open', world='Manage', seed=7) + d('wait_for', condition='loaded', timeout=400) + assert d('status')['player'] is not None + d('give', item='bucket') + d('select', slot='bucket') + pos = d('state')['position'] + cow = d('summon', kind='cow', x=pos[0], y=pos[1], z=pos[2] + 2)['id'] + d('wait', ticks=5) + d('interact_entity', id=cow) + items = {s.get('item') for s in d('inventory')['hotbar'] if s} + assert 'minecraft:milk_bucket' in items, items + d('effect', id='speed', seconds=30, amplifier=1) + effects = json.dumps(d('effects')) + assert 'speed' in effects, effects + d('xp', levels=5) + assert d('lan', action='status') is not None + d('options', page='horizon') + assert 'graphics' in widgets(d), widgets(d).keys() + d('key', key='esc', action='tap') + d('pause') + d('click', id='save-and-quit-to-title') + d('wait_for', condition='screen', value='title', timeout=60) + worlds = {w['folder']: w for w in d('worlds')['worlds']} + assert worlds['Manage']['mode'] == 'survival', worlds + assert d('world_backup', folder='Manage')['bytes'] > 0 + assert (d.cwd / 'backups').is_dir() and any((d.cwd / 'backups').glob('*_Manage.zip')) + d('world_rename', folder='Manage', name='Renamed Base') + assert {w['folder']: w for w in d('worlds')['worlds']}['Manage']['name'] == 'Renamed Base' + try: + d('world_delete', folder='Manage') + raise AssertionError('deleted without --confirm') + except Failed as e: + assert 'confirm' in str(e), e + assert (d.cwd / 'saves/Manage').is_dir() + d('world_delete', folder='Manage', confirm=True) + assert not (d.cwd / 'saves/Manage').exists() + assert 'Manage' not in {w['folder'] for w in d('worlds')['worlds']} + assert d('servers')['servers'] == [] + return {'worlds': len(worlds)} + + SCENARIOS = {'survival': scenario, 'ui': ui_scenario, 'options': options_scenario, 'events': events_scenario, - 'consume': consume_scenario, 'pick': pick_scenario, 'suggestions': suggestions_scenario} + 'consume': consume_scenario, 'pick': pick_scenario, 'suggestions': suggestions_scenario, + 'manage': manage_scenario} def run(mode, ctl, out, resources, which='survival'):