diff --git a/launcher/README.md b/launcher/README.md index 6cfafe590..e12ed2439 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -174,27 +174,35 @@ scripts and tests). ## AI agents (MCP) -`horizon-launcher mcp` is a Model Context Protocol server over stdio. To use it from Claude Code: +`horizon-launcher mcp` is a Model Context Protocol server over stdio. `horizon-launcher +agent-config` prints the config for Claude Code, Codex, Cursor and any MCP client, and the +command that adds it; for Claude Code: - claude mcp add horizon -- horizon-launcher mcp + claude mcp add --scope user horizon -- horizon-launcher mcp -(with the full path to the binary if it is not on your `PATH`). Its tools: `list_versions`, -`install_version`, `remove_version`, `prepare_resources`, `launch_client`, `start_server`, -`server_command`, `server_log`, `stop_server`, `patch_notes`, `links`, `update_channel`, `logs`, -`check_updates`, `accounts`, `sign_in` (returns the link and code for the player; the sign-in -finishes in the background), `sign_out`, `select_account`, and for data collection -`data_collection`, `set_data_collection`, `data_preview`, `delete_my_data` and `report_bug` -(only with the player's say-so). -A server started through MCP stops (cleanly, with `stop`) when the session ends. Starting one -needs `accept_eula`, which an agent should only pass with the player's consent. +(with the full path to the binary if it is not on your `PATH`). Every CLI command is a tool of the +same name and arguments, generated from the CLI's definition (`src/cli_tools.rs`): `versions`, +`install`, `remove`, `prepare`, `settings`, `mods_search`, `mods_install`, `modpack_import`, +`servers_create`, `data_status`... A call runs that command with `--json` and returns its +output. Tools that delete something (`remove`, `mods_remove`, `modpack_remove`, +`servers_forget`, `account_sign_out`, `data_delete`) need `confirm: true`. The session runs a few +itself, under the CLI's names: `play`, `server` with `server_command`, `server_log` and +`server_stop`, `account_list` and `account_sign_in` (returns the link and code for the player; +the sign-in finishes in the background). A server started through MCP stops (cleanly, with +`stop`) when the session ends. Starting one needs `accept_eula`, which an agent should only pass +with the player's consent. -The same server also plays the game: `launch_client` starts it with a local control socket -(`world`, `creative` and `offscreen` are optional), and every `horizon-ctl` tool of the selected +The same server also plays the game: `play` starts it with a local control socket (`world`, +`creative`, `join` and `offscreen` are optional), and every `horizon-ctl` tool of the selected version is offered as `game_`: `game_state`, `game_ui` (every widget of the open screen), `game_click`, `game_goto`, `game_break`, `game_inventory`, `game_screenshot` (an image) and the -rest of [horizon-ctl's commands](../docs/agent-control.md). The launcher runs that version's -`horizon-ctl mcp` and passes the calls through; while no game runs, they answer with an error -saying to call `launch_client`. +rest of [horizon-ctl's commands](../docs/horizon-ctl-commands.md). The launcher runs that +version's `horizon-ctl mcp` and passes the calls through; while no game runs, they answer with an +error saying to call `play`. + +`horizon-launcher no-ai on` (the Settings page's No AI switch) hides and turns off every AI +feature: `mcp` and `agent-config` refuse, the game opens no control socket and `horizon-ctl` +refuses. Every other command keeps working. The window, the command line and the MCP server all call the same core, `src/backend.rs`. diff --git a/launcher/src/agents.rs b/launcher/src/agents.rs new file mode 100644 index 000000000..8eba00125 --- /dev/null +++ b/launcher/src/agents.rs @@ -0,0 +1,147 @@ +//! Connecting an AI agent (docs/agent-control.md): the launcher's MCP server, `horizon-launcher +//! mcp`, as each common client wants it configured. `horizon-launcher agent-config` prints it and +//! the Settings page's "Connect an AI agent" shows it. Nothing here runs a client's command: the +//! window runs one only when the player clicks its button, and shows it first. +use serde_json::{json, Value}; +use std::path::Path; + +/// The name the server is added under in every client. +pub const SERVER_NAME: &str = "horizon"; + +pub struct Client { + /// `claude-code`, `codex`, `cursor` or `generic`. + pub id: &'static str, + pub name: &'static str, + /// Where its configuration lives. + pub file: &'static str, + /// What goes in that file. + pub config: String, + /// The client's own command that adds the server, when it has a CLI: (program, arguments). + pub add: Option<(&'static str, Vec)>, +} + +impl Client { + /// The add command as a shell line, to show and to copy. + pub fn add_line(&self) -> Option { + self.add + .as_ref() + .map(|(program, args)| shell_line(program, args)) + } +} + +/// The `mcpServers` JSON most clients read (Claude Code's .mcp.json, Cursor, Claude Desktop...). +fn mcp_servers_json(exe: &Path) -> String { + let config = json!({ "mcpServers": { SERVER_NAME: { "command": exe, "args": ["mcp"] } } }); + serde_json::to_string_pretty(&config).unwrap_or_default() +} + +/// A TOML basic string. +fn toml_string(s: &str) -> String { + format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")) +} + +/// The clients, for the launcher at `exe`. +pub fn clients(exe: &Path) -> Vec { + let exe_text = exe.display().to_string(); + let add = |args: &[&str]| -> Vec { + let mut words: Vec = args.iter().map(|s| (*s).to_owned()).collect(); + words.extend([exe_text.clone(), "mcp".into()]); + words + }; + vec![ + Client { + id: "claude-code", + name: "Claude Code", + file: "~/.claude.json (or .mcp.json in a project)", + config: mcp_servers_json(exe), + add: Some(( + "claude", + add(&["mcp", "add", "--scope", "user", SERVER_NAME, "--"]), + )), + }, + Client { + id: "codex", + name: "Codex", + file: "~/.codex/config.toml", + config: format!( + "[mcp_servers.{SERVER_NAME}]\ncommand = {}\nargs = [\"mcp\"]\n", + toml_string(&exe_text) + ), + add: Some(("codex", add(&["mcp", "add", SERVER_NAME, "--"]))), + }, + Client { + id: "cursor", + name: "Cursor", + file: "~/.cursor/mcp.json", + config: mcp_servers_json(exe), + add: None, + }, + Client { + id: "generic", + name: "Any MCP client", + file: "its MCP settings (a stdio server)", + config: mcp_servers_json(exe), + add: None, + }, + ] +} + +/// `program args...` quoted for a POSIX shell where a word needs it. +pub fn shell_line(program: &str, args: &[String]) -> String { + let quote = |w: &str| { + if !w.is_empty() + && w.chars() + .all(|c| c.is_ascii_alphanumeric() || "-_./:=@".contains(c)) + { + w.to_owned() + } else { + format!("'{}'", w.replace('\'', "'\\''")) + } + }; + std::iter::once(program) + .chain(args.iter().map(String::as_str)) + .map(quote) + .collect::>() + .join(" ") +} + +/// Everything `agent-config --json` prints. +pub fn json(exe: &Path) -> Value { + json!({ + "server": { "name": SERVER_NAME, "command": exe, "args": ["mcp"] }, + "clients": clients(exe).iter().map(|c| json!({ + "id": c.id, "name": c.name, "file": c.file, "config": c.config, "add": c.add_line(), + })).collect::>(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn configs_name_the_launcher_and_quote_its_path() { + let exe = Path::new("/Applications/Horizon Launcher.app/Contents/MacOS/horizon-launcher"); + let all = clients(exe); + let claude = &all[0]; + assert_eq!( + claude.add_line().unwrap(), + "claude mcp add --scope user horizon -- '/Applications/Horizon Launcher.app/Contents/MacOS/horizon-launcher' mcp" + ); + let parsed: Value = serde_json::from_str(&claude.config).unwrap(); + assert_eq!(parsed["mcpServers"]["horizon"]["args"], json!(["mcp"])); + assert_eq!( + parsed["mcpServers"]["horizon"]["command"], + exe.display().to_string() + ); + let codex = &all[1]; + assert!(codex + .config + .contains("command = \"/Applications/Horizon Launcher.app")); + assert_eq!( + toml_string(r#"C:\Horizon\"x".exe"#), + r#""C:\\Horizon\\\"x\".exe""# + ); + assert!(all.iter().any(|c| c.id == "cursor" && c.add.is_none())); + } +} diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index 7ca348a3a..aba6c7ae1 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -253,6 +253,12 @@ enum Cmd { Play { #[arg(long)] version: Option, + /// Open or create this world (a folder under saves) at once + #[arg(long)] + world: Option, + /// Creative mode for a new world + #[arg(long)] + creative: bool, /// Join a friend's world with its invite code #[arg(long)] join: Option, @@ -288,6 +294,16 @@ enum Cmd { #[arg(value_parser = ["stable", "alpha"])] channel: Option, }, + /// Show the launcher's settings, or set one (the Settings page): selected-version TAG, + /// minecraft-dir PATH, server-dir PATH ("default" resets a folder), install-new-versions + /// on|off, opening-animation on|off + Settings { + #[arg(value_parser = SETTING_KEYS)] + key: Option, + /// The new value (with KEY) + #[arg(requires = "key")] + value: Option, + }, /// Show or set the extra arguments the game starts with (for example --server-thread); /// quotes group a word with spaces in it GameArgs { @@ -346,6 +362,13 @@ enum Cmd { /// Serve the Model Context Protocol on stdin and stdout, for AI agents (refused while No AI /// is on) Mcp, + /// How to connect an AI agent (Claude Code, Codex, Cursor, any MCP client) to `mcp`: the + /// config to paste and the command that adds it (refused while No AI is on) + AgentConfig { + /// Only this client + #[arg(long, value_parser = ["claude-code", "codex", "cursor", "generic"])] + client: Option, + }, /// Show or set No AI: on hides and turns off every AI feature (the companion, agent control, /// horizon-ctl and both MCP servers); off, the default, makes them available NoAi { @@ -362,12 +385,75 @@ enum Cmd { }, } +/// The CLI's definition, for the MCP tools generated from it (cli_tools.rs). +pub fn command() -> clap::Command { + ::command() +} + +/// The commands that exist for AI agents: hidden and refused while No AI is on. Every other +/// command stays: the launcher, packagers and scripts need them, and none drives the game. +pub const AI_COMMANDS: [&str; 2] = ["mcp", "agent-config"]; + +/// The keys `settings` sets. +const SETTING_KEYS: [&str; 5] = [ + "selected-version", + "minecraft-dir", + "server-dir", + "install-new-versions", + "opening-animation", +]; + +fn on_off(value: &str) -> Result { + match value { + "on" | "true" => Ok(true), + "off" | "false" => Ok(false), + _ => Err(format!("{value}: say on or off")), + } +} + +fn set_setting(s: &mut backend::Settings, key: &str, value: &str) -> Result<(), String> { + let folder = |value: &str| (value != "default").then(|| PathBuf::from(value)); + match key { + "selected-version" => s.selected = Some(backend::resolve_version(Some(value))?), + "minecraft-dir" => s.minecraft_dir = folder(value), + "server-dir" => s.server_dir = folder(value), + "install-new-versions" => s.install_new_versions = Some(on_off(value)?), + "opening-animation" => s.skip_opening = !on_off(value)?, + _ => return Err(format!("No setting {key}.")), + } + Ok(()) +} + +/// Every launcher setting, as `settings` shows them. +fn settings_json(s: &backend::Settings) -> serde_json::Value { + serde_json::json!({ + "selected_version": backend::resolve_version(None).ok(), + "minecraft_dir": s.minecraft_dir, + "server_dir": backend::server_dir(None), + "install_new_versions": s.install_new_versions.unwrap_or(true), + "opening_animation": !s.skip_opening, + "update_channel": s.update_channel.name(), + "game_args": s.game_args, + "desktop_entry": s.desktop_entry.unwrap_or(true), + "no_ai": backend::no_ai(), + }) +} + /// Runs a subcommand and returns the exit code, or None when the window should open. pub fn run() -> Option { - let cli = Cli::parse(); + use clap::FromArgMatches; + let no_ai = backend::no_ai(); + let mut definition = command(); + if no_ai { + // Hidden from the help too; a call still gets the refusal below. + for name in AI_COMMANDS { + definition = definition.mut_subcommand(name, |c| c.hide(true)); + } + } + let cli = Cli::from_arg_matches(&definition.get_matches()).unwrap_or_else(|e| e.exit()); let command = cli.command?; let result = match command { - Cmd::Mcp if backend::no_ai() => Err(horizon_core::no_ai::REFUSAL.into()), + Cmd::Mcp | Cmd::AgentConfig { .. } if no_ai => Err(horizon_core::no_ai::REFUSAL.into()), Cmd::Mcp => crate::mcp::serve(), command => execute(command, cli.json), }; @@ -505,11 +591,23 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { } println!("{tag} is prepared."); } - Cmd::Play { version, join, arg } => { + Cmd::Play { + version, + world, + creative, + join, + arg, + } => { let mut cmd = backend::client(&backend::resolve_version(version.as_deref())?)?; if let Some(code) = join { backend::join_friend(&mut cmd, &code)?; } + if let Some(world) = world { + cmd.arg("--world").arg(world); + } + if creative { + cmd.arg("--creative"); + } cmd.args(arg); attached(cmd)? } @@ -575,6 +673,55 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { println!("No AI is off: AI features are available."); } } + Cmd::AgentConfig { client } => { + use horizon_launcher::agents; + let exe = backend::exe_path(); + if as_json { + let mut all = agents::json(exe); + if let Some(id) = &client { + all["clients"] = all["clients"] + .as_array() + .into_iter() + .flatten() + .filter(|c| c["id"] == id.as_str()) + .cloned() + .collect(); + } + json(all); + return Ok(()); + } + for c in agents::clients(exe) + .iter() + .filter(|c| client.as_ref().is_none_or(|id| id == c.id)) + { + println!("{}", c.name); + if let Some(line) = c.add_line() { + println!(" Add it with: {line}"); + } + println!(" Or put this in {}:", c.file); + for line in c.config.lines() { + println!(" {line}"); + } + println!(); + } + println!("Then ask your agent to say hello: it can call the links tool, or play."); + } + Cmd::Settings { key, value } => { + let mut settings = backend::Settings::load(); + if let Some(key) = key { + let value = value.ok_or("settings KEY VALUE: the value is missing")?; + set_setting(&mut settings, &key, &value)?; + settings.save(); + } + let all = settings_json(&settings); + if as_json { + json(all); + } else { + for (key, value) in all.as_object().into_iter().flatten() { + println!("{key}: {value}"); + } + } + } Cmd::UpdateChannel { channel } => { let mut settings = backend::Settings::load(); if let Some(channel) = channel.as_deref().and_then(backend::UpdateChannel::parse) { diff --git a/launcher/src/cli_tools.rs b/launcher/src/cli_tools.rs new file mode 100644 index 000000000..e5d9d5a20 --- /dev/null +++ b/launcher/src/cli_tools.rs @@ -0,0 +1,339 @@ +//! Every launcher CLI command as an MCP tool, generated from the CLI's own definition (clap) so the +//! two can't drift: the tool `mods_search` is `horizon-launcher mods search`, its arguments are the +//! command's (snake_case), and a call runs that command with `--json` as a child process and +//! returns what it printed. A few commands keep a process or a sign-in going for the session; +//! mcp.rs runs those itself under the same names (`play`, `server`, `account_sign_in`...). +use clap::{ArgAction, Command}; +use serde_json::{json, Map, Value}; + +/// CLI commands that are not generated tools: the MCP server itself; No AI, the player's switch +/// and never an agent's; and the ones mcp.rs runs in the session. +const NOT_TOOLS: &[&str] = &[ + "mcp", + "agent-config", + "no-ai", + "play", + "server", + "account sign-in", + "account list", +]; + +/// Commands that delete the player's things: their tools need `confirm: true`. +pub const DESTRUCTIVE: &[&str] = &[ + "remove", + "modpack remove", + "mods remove", + "servers forget", + "account sign-out", + "data delete", +]; + +/// Commands that send something or reach other people: only when the player asks. +pub const OPEN_WORLD: &[&str] = &[ + "data allow", + "data send", + "data bug", + "data benchmark", + "servers create", +]; + +/// A generated tool: its name, the CLI words it runs and the clap command behind them. +pub struct Tool { + pub name: String, + pub path: Vec, + command: Command, +} + +/// The tool name of CLI words: `mods search` gives `mods_search`. +pub fn tool_name(path: &[String]) -> String { + path.join("_").replace('-', "_") +} + +/// Every generated tool, in the CLI's order. +pub fn all() -> Vec { + let mut out = Vec::new(); + walk(&crate::cli::command(), &mut Vec::new(), &mut out); + out +} + +fn walk(cmd: &Command, path: &mut Vec, out: &mut Vec) { + for sub in cmd.get_subcommands() { + path.push(sub.get_name().to_owned()); + if sub.has_subcommands() { + walk(sub, path, out); + } else if !NOT_TOOLS.contains(&path.join(" ").as_str()) { + out.push(Tool { + name: tool_name(path), + path: path.clone(), + command: sub.clone(), + }); + } + path.pop(); + } +} + +impl Tool { + fn words(&self) -> String { + self.path.join(" ") + } + pub fn destructive(&self) -> bool { + DESTRUCTIVE.contains(&self.words().as_str()) + } + + /// The tools/list entry. + pub fn describe(&self) -> Value { + let mut props = Map::new(); + let mut required = Vec::new(); + for arg in self.command.get_arguments().filter(|a| shown(a)) { + let id = arg.get_id().as_str(); + let mut help = arg.get_help().map(ToString::to_string).unwrap_or_default(); + let defaults: Vec = arg + .get_default_values() + .iter() + .map(|d| d.to_string_lossy().into_owned()) + .collect(); + if !defaults.is_empty() { + help = format!("{help} (default {})", defaults.join(", ")) + .trim_start() + .to_owned(); + } + let choices: Vec = arg + .get_possible_values() + .iter() + .map(|v| v.get_name().to_owned()) + .collect(); + let one = if !choices.is_empty() { + json!({ "type": "string", "enum": choices }) + } else if defaults.first().is_some_and(|d| d.parse::().is_ok()) { + json!({ "type": "integer" }) + } else { + json!({ "type": "string" }) + }; + let mut schema = if matches!(arg.get_action(), ArgAction::SetTrue) { + json!({ "type": "boolean" }) + } else if many(arg) { + json!({ "type": "array", "items": one }) + } else { + one + }; + if !help.is_empty() { + schema["description"] = help.into(); + } + props.insert(id.to_owned(), schema); + if arg.is_required_set() { + required.push(id.to_owned()); + } + } + if self.destructive() { + props.insert( + "confirm".into(), + json!({ "type": "boolean", "description": "true once the player agreed: it cannot be undone" }), + ); + required.push("confirm".into()); + } + let about = self + .command + .get_about() + .map(ToString::to_string) + .unwrap_or_default(); + let mut tool = json!({ + "name": self.name, + "description": format!("{about}. CLI: horizon-launcher {}", self.words()), + "inputSchema": { "type": "object", "properties": props, "required": required }, + }); + if self.destructive() { + tool["annotations"] = json!({ "destructiveHint": true }); + } else if OPEN_WORLD.contains(&self.words().as_str()) { + tool["annotations"] = json!({ "openWorldHint": true }); + } + tool + } + + /// The CLI words for a call's arguments. + pub fn argv(&self, args: &Value) -> Result, String> { + if self.destructive() && args.get("confirm").and_then(Value::as_bool) != Some(true) { + return Err(format!( + "{} cannot be undone: ask the player, then call it with confirm: true", + self.name + )); + } + let text = |v: &Value| match v { + Value::String(s) => Ok(s.clone()), + Value::Number(n) => Ok(n.to_string()), + Value::Bool(b) => Ok(b.to_string()), + other => Err(format!("{other} is not a value")), + }; + let mut words = self.path.clone(); + let mut positional = Vec::new(); + let mut last = Vec::new(); + for arg in self.command.get_arguments().filter(|a| shown(a)) { + let id = arg.get_id().as_str(); + let Some(value) = args.get(id).filter(|v| !v.is_null()) else { + if arg.is_required_set() { + return Err(format!("{id} is required")); + } + continue; + }; + let values = match value { + Value::Array(items) => items.iter().map(text).collect::, _>>()?, + v => vec![text(v)?], + }; + if matches!(arg.get_action(), ArgAction::SetTrue) { + if value.as_bool().ok_or(format!("{id} is true or false"))? { + words.push(format!("--{}", arg.get_long().unwrap_or(id))); + } + } else if arg.is_positional() { + let into = if arg.is_last_set() { + &mut last + } else { + &mut positional + }; + into.push((arg.get_index().unwrap_or(0), values)); + } else { + let long = arg.get_long().unwrap_or(id); + for v in values { + // `=` keeps a value that starts with a dash (game arguments) a value. + words.push(format!("--{long}={v}")); + } + } + } + positional.sort_by_key(|(index, _)| *index); + words.extend(positional.into_iter().flat_map(|(_, v)| v)); + if !last.is_empty() { + words.push("--".into()); + words.extend(last.into_iter().flat_map(|(_, v)| v)); + } + Ok(words) + } + + /// Runs the command as `horizon-launcher --json ...` and returns what it printed. + pub fn call(&self, args: &Value) -> Result { + let words = self.argv(args)?; + let exe = std::env::current_exe().map_err(|e| e.to_string())?; + let out = std::process::Command::new(exe) + .arg("--json") + .args(&words) + .stdin(std::process::Stdio::null()) + .output() + .map_err(|e| format!("Could not run horizon-launcher: {e}"))?; + let stdout = String::from_utf8_lossy(&out.stdout).trim().to_owned(); + let stderr = String::from_utf8_lossy(&out.stderr).trim().to_owned(); + let text = match (stdout.is_empty(), stderr.is_empty()) { + (false, true) => stdout, + (true, false) => stderr, + (true, true) => "Done.".into(), + (false, false) => format!("{stdout}\n{stderr}"), + }; + if out.status.success() { + Ok(text) + } else { + Err(text) + } + } +} + +/// Whether an argument is part of a tool (not --help, --version or the global --json). +fn shown(arg: &clap::Arg) -> bool { + !arg.is_hide_set() && !matches!(arg.get_id().as_str(), "help" | "version" | "json") +} + +/// Whether an argument takes several values (a list). +fn many(arg: &clap::Arg) -> bool { + matches!(arg.get_action(), ArgAction::Append) + || arg.get_num_args().is_some_and(|n| n.max_values() > 1) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tool(name: &str) -> Tool { + all().into_iter().find(|t| t.name == name).unwrap() + } + + #[test] + fn every_cli_command_is_a_tool_named_after_its_words() { + let names: Vec = all().into_iter().map(|t| t.name).collect(); + for want in [ + "versions", + "install", + "remove", + "prepare", + "notes", + "update", + "update_channel", + "game_args", + "settings", + "logs", + "mods_search", + "mods_install", + "modpack_import", + "servers_create", + "servers_run", + "data_status", + "data_bug", + "account_select", + "benchmark", + ] { + assert!(names.iter().any(|n| n == want), "{want} missing: {names:?}"); + } + for not in ["mcp", "no_ai", "play", "server", "account_sign_in"] { + assert!(!names.iter().any(|n| n == not), "{not}"); + } + } + + #[test] + fn arguments_become_cli_words() { + let search = tool("mods_search"); + let schema = search.describe(); + assert_eq!(schema["inputSchema"]["properties"]["text"]["type"], "array"); + let kinds = &schema["inputSchema"]["properties"]["kind"]["enum"]; + assert!( + kinds.as_array().unwrap().contains(&json!("shader")), + "{kinds}" + ); + assert_eq!( + search + .argv(&json!({ "text": ["fresh", "animations"], "kind": "shader", "everything": true })) + .unwrap(), + ["mods", "search", "--kind=shader", "--everything", "fresh", "animations"] + ); + let run = tool("servers_run"); + assert_eq!( + run.argv(&json!({ "server": "My server", "args": ["status"] })) + .unwrap(), + ["servers", "run", "My server", "--", "status"] + ); + assert!(run + .argv(&json!({ "server": "x" })) + .unwrap_err() + .contains("args is required")); + let logs = tool("logs").describe(); + assert_eq!( + logs["inputSchema"]["properties"]["lines"]["type"], + "integer" + ); + } + + #[test] + fn destructive_tools_need_confirm() { + let remove = tool("remove"); + assert_eq!(remove.describe()["annotations"]["destructiveHint"], true); + assert!(remove + .argv(&json!({ "tag": "v1" })) + .unwrap_err() + .contains("confirm")); + assert_eq!( + remove + .argv(&json!({ "tag": "v1", "confirm": true })) + .unwrap(), + ["remove", "v1"] + ); + for words in DESTRUCTIVE.iter().chain(OPEN_WORLD) { + assert!( + all().iter().any(|t| t.words() == *words), + "{words} is not a tool" + ); + } + } +} diff --git a/launcher/src/game_tools.rs b/launcher/src/game_tools.rs index 7694d24e5..3504a531f 100644 --- a/launcher/src/game_tools.rs +++ b/launcher/src/game_tools.rs @@ -1,6 +1,6 @@ //! The running game's tools in the launcher's MCP, so an agent needs one server //! (docs/agent-control.md): the selected version's `horizon-ctl mcp` runs as a child, its tools -//! are offered as `game_`, and calls go to it unchanged. `launch_client` starts the game +//! are offered as `game_`, and calls go to it unchanged. `play` starts the game //! with the control socket that child talks to. use horizon_launcher::backend; use serde_json::{json, Value}; @@ -10,7 +10,7 @@ use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; pub const PREFIX: &str = "game_"; -/// horizon-ctl tools the launcher covers itself: `launch_client` starts the game. +/// horizon-ctl tools the launcher covers itself: `play` starts the game. const HIDDEN: &[&str] = &["launch"]; const CTL: &str = if cfg!(windows) { @@ -19,7 +19,7 @@ const CTL: &str = if cfg!(windows) { "horizon-ctl" }; -/// The control endpoint of a game started by `launch_client`: a Unix socket, or on Windows the +/// The control endpoint of a game started by `play`: a Unix socket, or on Windows the /// file naming a localhost port and its token. pub fn socket_path() -> PathBuf { backend::data_dir().join(if cfg!(unix) { @@ -151,7 +151,7 @@ fn prefixed(tools: &Value) -> Vec { let mut t = t.clone(); t["name"] = format!("{PREFIX}{}", t["name"].as_str().unwrap_or_default()).into(); t["description"] = format!( - "In the running game (start it with launch_client): {}", + "In the running game (start it with play): {}", t["description"].as_str().unwrap_or_default() ) .into(); @@ -173,7 +173,7 @@ fn explain_unreachable(mut result: Value) -> Value { }); if unreachable { result["content"] = json!([{ "type": "text", "text": json!({ - "error": "The game is not running under agent control. Start it with launch_client, then game_wait_ready.", + "error": "The game is not running under agent control. Start it with play, then game_wait_ready.", "kind": "state", }).to_string() }]); } @@ -209,7 +209,7 @@ mod tests { assert!(result["content"][0]["text"] .as_str() .unwrap() - .contains("launch_client")); + .contains("with play")); let other = json!({ "content": [{ "type": "text", "text": "{\"error\":\"no world\"}" }], "isError": true }); assert_eq!(explain_unreachable(other.clone()), other); } diff --git a/launcher/src/lib.rs b/launcher/src/lib.rs index 98228b5fc..61a9713ff 100644 --- a/launcher/src/lib.rs +++ b/launcher/src/lib.rs @@ -1,5 +1,6 @@ //! The launcher's core, shared by the GUI, the CLI and the MCP server. pub mod account; +pub mod agents; pub mod backend; pub mod browser; pub mod desktop; diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 2ffea2e98..237ac0402 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -4,6 +4,7 @@ mod art; mod blocks; mod cli; +mod cli_tools; mod collection; mod cull; mod game_tools; diff --git a/launcher/src/mcp.rs b/launcher/src/mcp.rs index 5abe45325..8aff5aa13 100644 --- a/launcher/src/mcp.rs +++ b/launcher/src/mcp.rs @@ -2,10 +2,10 @@ //! message per line), so AI agents can install, prepare and run Horizon. Every tool goes through //! `backend`. A server started here lives as long as the session. The running game's own tools //! come from its `horizon-ctl` as `game_*` (game_tools.rs). +use crate::cli_tools; use crate::game_tools::{self, GameTools}; use horizon_launcher::account::{self, Accounts, SignIn, SignInState}; use horizon_launcher::backend::{self, Job, Logged}; -use horizon_launcher::telemetry; use serde_json::{json, Value}; use std::io::{BufRead, Write}; use std::path::PathBuf; @@ -21,55 +21,38 @@ struct Session { game: Option, } -fn tools() -> Value { +/// The tools the session runs itself, under their CLI names: they keep a process (the game, a +/// server) or a sign-in going between calls. Every other CLI command is generated (cli_tools.rs). +fn session_tools() -> Value { let version = json!({ "type": "string", "description": "An installed version tag such as v2026.10.13. Default: the selected version." }); let none = json!({ "type": "object", "properties": {} }); json!([ - { "name": "list_versions", "description": "List Horizon releases on GitHub (newest first) and the versions installed here, with which is selected and which are prepared.", - "inputSchema": { "type": "object", "properties": { "installed_only": { "type": "boolean", "description": "Skip GitHub and list only installed versions." } } } }, - { "name": "install_version", "description": "Download and install a Horizon release for this platform. Takes a minute or two.", - "inputSchema": { "type": "object", "properties": { "tag": { "type": "string", "description": "A release tag such as v2026.10.13, or \"latest\"." } }, "required": ["tag"] } }, - { "name": "remove_version", "description": "Remove an installed Horizon version and its prepared resources.", - "inputSchema": { "type": "object", "properties": { "tag": { "type": "string" } }, "required": ["tag"] } }, - { "name": "prepare_resources", "description": "Prepare a version's resources from the player's own Minecraft install (needs the Minecraft release that version is built for, played once in the official launcher, and its Java; versions before horizon-prepare also need Python 3.10+). Can take several minutes; returns the end of the log.", - "inputSchema": { "type": "object", "properties": { "version": version, "minecraft_dir": { "type": "string", "description": "The game folder of the official launcher, Prism Launcher, MultiMC, the Modrinth App, ATLauncher or GDLauncher. Default: the launcher's setting, then every launcher's default folder." } } } }, - { "name": "launch_client", "description": "Start the Horizon client (a game window on the player's screen) under agent control: the game_* tools then play it. Returns once it has started; game_wait_ready waits for the world.", + { "name": "play", "description": "Start the Horizon client (a game window on the player's screen) under agent control: the game_* tools then play it. Returns once it has started; game_wait_ready waits for the world. CLI: horizon-launcher play", "inputSchema": { "type": "object", "properties": { "version": version, "world": { "type": "string", "description": "Open or create this world (a folder under saves) at once." }, "creative": { "type": "boolean", "description": "Creative mode for a new world." }, + "join": { "type": "string", "description": "Join a friend's world with its invite code. Only when the player asks." }, "offscreen": { "type": "boolean", "description": "Render without showing a window (game_screenshot still works)." }, - "args": { "type": "array", "items": { "type": "string" }, "description": "Extra game arguments, passed through as-is (for example \"--server-thread\")." } } } }, - { "name": "start_server", "description": "Start a Horizon dedicated server. It runs until stop_server or the end of this MCP session. Requires agreeing to the Minecraft EULA.", + "arg": { "type": "array", "items": { "type": "string" }, "description": "Extra game arguments, passed through as-is (for example \"--server-thread\")." } } } }, + { "name": "server", "description": "Start a Horizon dedicated server. It runs until server_stop or the end of this MCP session. Requires agreeing to the Minecraft EULA. CLI: horizon-launcher server", "inputSchema": { "type": "object", "properties": { "version": version, "dir": { "type": "string", "description": "The server's folder. Default: the launcher's server folder." }, "accept_eula": { "type": "boolean", "description": "Agree to the Minecraft EULA (https://aka.ms/MinecraftEULA) on the player's behalf. Only with their consent." } } } }, - { "name": "server_command", "description": "Send a console command to the running server (for example \"list\" or \"say hello\"), and return the lines it printed in reply.", + { "name": "server_command", "description": "Send a console command to the server started with server (for example \"list\" or \"say hello\"), and return the lines it printed in reply.", "inputSchema": { "type": "object", "properties": { "command": { "type": "string" } }, "required": ["command"] } }, { "name": "server_log", "description": "The most recent lines of the server's console.", "inputSchema": { "type": "object", "properties": { "lines": { "type": "integer", "minimum": 1, "maximum": 2000, "description": "How many lines (default 50)." } } } }, - { "name": "stop_server", "description": "Stop the running server cleanly (it saves the world), killing it if it does not stop within 30 seconds.", "inputSchema": none }, - { "name": "patch_notes", "description": "A release's patch notes as markdown.", - "inputSchema": { "type": "object", "properties": { "tag": { "type": "string", "description": "Default: the newest release." } } } }, - { "name": "links", "description": "The Horizon links: the Discord invite, the GitHub Sponsors page and the website (an empty one is not offered).", "inputSchema": none }, - { "name": "update_channel", "description": "Show or set which Horizon releases install by themselves. \"stable\" (the default) is a tested build about once a day; \"alpha\" is every release as soon as it is built, several times a day, and can break. Only when the player asks to change it.", - "inputSchema": { "type": "object", "properties": { "channel": { "type": "string", "enum": ["stable", "alpha"], "description": "Omit to show the current channel." } } } }, - { "name": "logs", "description": "Read the game's log: the last lines of logs/latest.log in the game folder, or with crash the newest crash report (what the game wrote when it last crashed). Read-only.", - "inputSchema": { "type": "object", "properties": { "lines": { "type": "integer", "minimum": 1, "maximum": 5000, "description": "How many lines of latest.log (default 100)." }, "crash": { "type": "boolean", "description": "Return the newest crash report instead." } } } }, - { "name": "accounts", "description": "The Microsoft accounts signed in to the launcher (names and UUIDs, never tokens), which one the game plays as (none = offline), and how a sign-in started with sign_in is going.", "inputSchema": none }, - { "name": "sign_in", "description": "Start signing in a Microsoft account: returns a link and a code the player enters in their browser. The sign-in finishes in the background; check it with accounts. Only when the player asks to sign in.", "inputSchema": none }, - { "name": "sign_out", "description": "Sign an account out of the launcher (its tokens leave the keychain).", - "inputSchema": { "type": "object", "properties": { "account": { "type": "string", "description": "Its name or UUID." } }, "required": ["account"] } }, - { "name": "select_account", "description": "Choose the account the game plays as, or \"offline\" to play without one.", - "inputSchema": { "type": "object", "properties": { "account": { "type": "string", "description": "A name or UUID, or \"offline\"." } }, "required": ["account"] } }, - { "name": "check_updates", "description": "Check GitHub for a Horizon release newer than every installed version, and for a newer launcher.", "inputSchema": none }, - { "name": "data_collection", "description": "The player's opt-in data collection: which kinds they allow (performance, crashes, bugs, benchmarks; all off until they answer), the install ID, how many items wait, and the data server. Read-only.", "inputSchema": none }, - { "name": "set_data_collection", "description": "Turn kinds of data collection on or off. Only when the player asks: it records their consent.", - "inputSchema": { "type": "object", "properties": { "kinds": { "type": "array", "items": { "type": "string", "enum": ["performance", "crashes", "bugs", "benchmarks", "all"] } }, "on": { "type": "boolean" } }, "required": ["kinds", "on"] } }, - { "name": "data_preview", "description": "Exactly what would be sent (the JSON), or an example of each kind when nothing waits. Sends nothing.", "inputSchema": none }, - { "name": "delete_my_data", "description": "Ask the server to delete everything sent from this install, remove what waits, and take a new install ID. Only when the player asks.", "inputSchema": none }, - { "name": "report_bug", "description": "Send a bug report in the player's words, only once they have agreed to send it (bug reports must be allowed). With include_log the end of the game's log goes too, scrubbed and without chat: show it to the player first (the logs tool). Returns exactly what was kept.", - "inputSchema": { "type": "object", "properties": { "text": { "type": "string" }, "include_log": { "type": "boolean" } }, "required": ["text"] } }, + { "name": "server_stop", "description": "Stop the server started with server cleanly (it saves the world), killing it if it does not stop within 30 seconds.", "inputSchema": none }, + { "name": "account_list", "description": "The Microsoft accounts signed in to the launcher (names and UUIDs, never tokens), which one the game plays as (none = offline), and how a sign-in started with account_sign_in is going. CLI: horizon-launcher account list", "inputSchema": none }, + { "name": "account_sign_in", "description": "Start signing in a Microsoft account: returns a link and a code the player enters in their browser. The sign-in finishes in the background; check it with account_list. Only when the player asks to sign in. CLI: horizon-launcher account sign-in", "inputSchema": none }, ]) } +/// Every launcher tool: the session's and the generated ones. +fn tools() -> Vec { + let mut list = session_tools().as_array().cloned().unwrap_or_default(); + list.extend(cli_tools::all().iter().map(cli_tools::Tool::describe)); + list +} + fn arg_str<'a>(args: &'a Value, key: &str) -> Option<&'a str> { args.get(key) .and_then(Value::as_str) @@ -78,81 +61,8 @@ fn arg_str<'a>(args: &'a Value, key: &str) -> Option<&'a str> { impl Session { fn call(&mut self, name: &str, args: &Value) -> Result { - if matches!(name, "list_versions" | "check_updates") { - backend::reuse_prepared_everywhere(); - } match name { - "list_versions" => { - let installed = backend::installed(); - let mut out = json!({ - "installed": installed.iter().map(|t| json!({ "tag": t, "prepared": backend::is_prepared(t), "sounds": backend::has_sounds(t) })).collect::>(), - "selected": backend::resolve_version(None).ok(), - }); - if !args - .get("installed_only") - .and_then(Value::as_bool) - .unwrap_or(false) - { - out["releases"] = backend::releases()? - .iter() - .map(|r| json!({ "tag": r.tag, "name": r.name, "date": r.date, "channel": backend::UpdateChannel::of(r).name(), "available_here": r.asset.is_some() })) - .collect(); - } - Ok(serde_json::to_string_pretty(&out).unwrap()) - } - "install_version" => { - let tag = backend::install_tag( - arg_str(args, "tag").ok_or("tag is required")?, - false, - |_| {}, - )?; - Ok(if backend::is_prepared(&tag) { - format!("Installed {tag}. It is now the selected version, prepared already from another installed version.") - } else { - format!("Installed {tag}. It is now the selected version; prepare it before playing.") - }) - } - "remove_version" => { - let tag = arg_str(args, "tag").ok_or("tag is required")?; - backend::remove_version(tag)?; - Ok(format!("Removed {tag}.")) - } - "prepare_resources" => { - let tag = backend::resolve_version(arg_str(args, "version"))?; - let minecraft = - backend::minecraft_dir(arg_str(args, "minecraft_dir").map(PathBuf::from))?; - let (preparer, minecraft) = backend::preparer(&tag, &minecraft, &|_| {})?; - let sound = std::cell::RefCell::new(Vec::new()); - backend::sounds(&tag, &minecraft, &|line| sound.borrow_mut().push(line)); - let (result, tail) = match preparer { - backend::Preparer::Process(cmd) => { - let run = Logged::start(Job::Prepare, cmd)?; - let result = run.wait(); - (result, run.tail(20).join("\n")) - } - backend::Preparer::InProcess(options) => { - let lines = std::cell::RefCell::new(std::collections::VecDeque::new()); - let result = backend::prepare_in_process(&options, &|line| { - let mut lines = lines.borrow_mut(); - lines.push_back(line); - if lines.len() > 20 { - lines.pop_front(); - } - }); - let tail = lines - .into_inner() - .into_iter() - .collect::>() - .join("\n"); - (result, tail) - } - }; - let tail = format!("{}\n{tail}", sound.into_inner().join("\n")); - result - .map(|_| format!("{tag} is prepared.\n{tail}")) - .map_err(|e| format!("{e}\n{tail}")) - } - "launch_client" => { + "play" => { if self.client.as_ref().is_some_and(|c| c.finished().is_none()) { return Err("The client is already running.".into()); } @@ -167,7 +77,10 @@ impl Session { cmd.arg(format!("--{flag}")); } } - if let Some(extra) = args.get("args").and_then(Value::as_array) { + if let Some(code) = arg_str(args, "join") { + backend::join_friend(&mut cmd, code)?; + } + if let Some(extra) = args.get("arg").and_then(Value::as_array) { cmd.args(extra.iter().filter_map(Value::as_str)); } let client = Logged::start(Job::Client, cmd)?; @@ -194,7 +107,7 @@ impl Session { "Started the {tag} client. The game_* tools play it; game_wait_ready waits until the world is ready." )) } - "start_server" => { + "server" => { if self.server.as_ref().is_some_and(|s| s.finished().is_none()) { return Err("A server is already running. Stop it first.".into()); } @@ -249,7 +162,7 @@ impl Session { server.tail(lines).join("\n") )) } - "stop_server" => { + "server_stop" => { let mut server = self .server .take() @@ -260,85 +173,7 @@ impl Session { server.tail(5).join("\n") )) } - "patch_notes" => { - let r = backend::release_notes(arg_str(args, "tag"))?; - Ok(format!( - "# {} ({}, {})\n\n{}", - if r.name.is_empty() { &r.tag } else { &r.name }, - r.tag, - r.date, - r.body - )) - } - "links" => Ok(serde_json::to_string_pretty(&backend::links()).unwrap()), - "logs" => { - let lines = args.get("lines").and_then(Value::as_u64).unwrap_or(100); - let crash = args.get("crash").and_then(Value::as_bool).unwrap_or(false); - let (path, text) = backend::read_logs(lines.clamp(1, 5000) as usize, crash)?; - Ok(format!("{}\n\n{text}", path.display())) - } - "update_channel" => { - let mut settings = backend::Settings::load(); - if let Some(name) = arg_str(args, "channel") { - settings.update_channel = backend::UpdateChannel::parse(name) - .ok_or("channel is \"stable\" or \"alpha\"")?; - settings.save(); - } - Ok(format!( - "Update channel: {}", - settings.update_channel.name() - )) - } - "data_collection" => Ok(serde_json::to_string_pretty(&telemetry::status_json()) - .map_err(|e| e.to_string())?), - "set_data_collection" => { - let kinds: Vec = args - .get("kinds") - .and_then(Value::as_array) - .map(|a| { - a.iter() - .filter_map(Value::as_str) - .map(str::to_owned) - .collect() - }) - .unwrap_or_default(); - let on = args - .get("on") - .and_then(Value::as_bool) - .ok_or("on is required")?; - telemetry::set(&telemetry::parse_kinds(&kinds)?, on)?; - Ok(serde_json::to_string_pretty(&telemetry::status_json()) - .map_err(|e| e.to_string())?) - } - "data_preview" => { - let (what, text) = telemetry::preview(); - Ok(format!("{what}\n{text}")) - } - "delete_my_data" => telemetry::delete_my_data(), - "report_bug" => { - let text = arg_str(args, "text").ok_or("text is required")?; - let with_log = args - .get("include_log") - .and_then(Value::as_bool) - .unwrap_or(false); - let item = telemetry::bug_report(text, with_log)?; - let done = telemetry::submit(&item)?; - Ok(format!( - "{done}\n{}", - serde_json::to_string_pretty(&item).map_err(|e| e.to_string())? - )) - } - "check_updates" => { - let u = backend::check_updates()?; - Ok(serde_json::to_string_pretty(&json!({ - "horizon_update": u.horizon.as_ref().map(|r| &r.tag), - "installed": backend::installed(), - "launcher_update": u.launcher.as_ref().and_then(|r| backend::launcher_version(&r.tag)), - "launcher_version": backend::VERSION, - })) - .unwrap()) - } - "accounts" => { + "account_list" => { let accounts = Accounts::load(); let sign_in = self.sign_in.as_ref().map(|s| match s.state() { SignInState::Starting => json!({ "state": "starting" }), @@ -355,7 +190,7 @@ impl Session { })) .unwrap()) } - "sign_in" => { + "account_sign_in" => { account::client_id().ok_or(account::NOT_CONFIGURED)?; if let Some(s) = self.sign_in.take() { s.cancel(); @@ -380,29 +215,10 @@ impl Session { _ => Err("Microsoft did not answer. Try again.".into()), } } - "sign_out" | "select_account" => { - let who = arg_str(args, "account").ok_or("account is required")?; - let mut accounts = Accounts::load(); - if name == "select_account" && who.eq_ignore_ascii_case("offline") { - accounts.selected = None; - accounts.save()?; - return Ok("The game plays offline.".into()); - } - let a = accounts - .find(who) - .cloned() - .ok_or_else(|| format!("No signed-in account {who}."))?; - if name == "sign_out" { - accounts.remove(account::store(), &a.uuid)?; - accounts.save()?; - Ok(format!("Signed out {}.", a.name)) - } else { - accounts.selected = Some(a.uuid); - accounts.save()?; - Ok(format!("The game plays as {}.", a.name)) - } - } - _ => Err(format!("Unknown tool {name}")), + _ => match cli_tools::all().into_iter().find(|t| t.name == name) { + Some(tool) => tool.call(args), + None => Err(format!("Unknown tool {name}")), + }, } } @@ -419,7 +235,7 @@ impl Session { fn running_server(&mut self) -> Result<&mut Logged, String> { match &mut self.server { Some(s) if s.finished().is_none() => Ok(s), - _ => Err("No server is running. Start one with start_server.".into()), + _ => Err("No server is running. Start one with server.".into()), } } @@ -429,11 +245,11 @@ impl Session { "protocolVersion": params.get("protocolVersion").and_then(Value::as_str).unwrap_or(PROTOCOL), "capabilities": { "tools": {} }, "serverInfo": { "name": "horizon-launcher", "version": backend::VERSION }, - "instructions": "Manage Horizon, a Rust reimplementation of Minecraft Java Edition: install versions, prepare them from the player's own Minecraft, start the client or a dedicated server. Once launch_client started the game, the game_* tools play it: game_state, game_ui (every widget of the open screen), game_click, game_goto, game_screenshot...", + "instructions": "Manage Horizon, a Rust reimplementation of Minecraft Java Edition: install versions, prepare them from the player's own Minecraft, start the client or a dedicated server. Every tool is a horizon-launcher CLI command of the same name (mods_search is horizon-launcher mods search). Once play started the game, the game_* tools play it: game_state, game_ui (every widget of the open screen), game_click, game_goto, game_screenshot...", })), "ping" => Ok(json!({})), "tools/list" => { - let mut list = tools().as_array().cloned().unwrap_or_default(); + let mut list = tools(); if let Some(game) = self.game() { list.extend(game.tools().iter().cloned()); } @@ -448,7 +264,10 @@ impl Session { .get("name") .and_then(Value::as_str) .ok_or((-32602, "name is required".to_string()))?; - if name.starts_with(game_tools::PREFIX) { + // The launcher's own tools first: game_args is one, not a game tool. + if name.starts_with(game_tools::PREFIX) + && !tools().iter().any(|t| t["name"] == name) + { let args = params.get("arguments").cloned().unwrap_or(json!({})); let game = self.game().ok_or(( -32602, @@ -459,12 +278,7 @@ impl Session { } return game.call(name, &args).map_err(|e| (-32603, e)); } - if !tools() - .as_array() - .unwrap() - .iter() - .any(|t| t["name"] == name) - { + if !tools().iter().any(|t| t["name"] == name) { return Err((-32602, format!("Unknown tool {name}"))); } let args = params.get("arguments").cloned().unwrap_or(json!({})); diff --git a/tools/launcher_mcp_e2e.py b/tools/launcher_mcp_e2e.py index fbcb1b5cc..fecf21899 100644 --- a/tools/launcher_mcp_e2e.py +++ b/tools/launcher_mcp_e2e.py @@ -3,9 +3,10 @@ A scratch launcher home gets one "installed" version made of this checkout's builds (horizon-client and horizon-ctl) and the prepared resources in .local/horizon-client. An MCP -client then talks to `horizon-launcher mcp` alone: the game tools are listed, a call before the -game runs says to launch it, launch_client starts it under control, and game_wait_ready, -game_state, game_ui and game_screenshot play it until game_quit. Then No AI is turned on with +client then talks to `horizon-launcher mcp` alone: every CLI command is listed as a tool of the same +name (versions, settings, mods_search...), a destructive one needs confirm, the game tools are +listed, a call before the game runs says to start it, play starts it under control, and +game_wait_ready, game_state, game_ui and game_screenshot play it until game_quit. Then No AI is turned on with `horizon-launcher no-ai on`: `horizon-launcher mcp` refuses to start, and a session already running refuses its next call. @@ -70,14 +71,27 @@ def scenario(m, out): 'clientInfo': {'name': 'launcher_mcp_e2e', 'version': '1'}}) assert init['serverInfo']['name'] == 'horizon-launcher', init tools = {t['name'] for t in m.rpc('tools/list', {})['tools']} - for name in ['launch_client', 'game_state', 'game_ui', 'game_click', 'game_screenshot']: + for name in ['play', 'server', 'versions', 'settings', 'mods_search', 'modpack_list', 'servers_list', + 'data_status', 'account_list', 'game_args', 'game_state', 'game_ui', 'game_click', + 'game_screenshot']: assert name in tools, f'{name} missing from {sorted(tools)}' - assert 'game_launch' not in tools, 'launch_client covers horizon-ctl launch' + for name in ['game_launch', 'mcp', 'no_ai', 'agent_config']: + assert name not in tools, f'{name} is a tool' + + # Generated from the CLI: the same command, its JSON output. + result, texts, _ = m.call('versions', installed=True) + assert json.loads(texts[-1])['installed'] == [TAG], texts + result, texts, _ = m.call('settings', key='opening-animation', value='off') + assert json.loads(texts[-1])['opening_animation'] is False, texts + result, texts, _ = m.call('game_args') + assert 'game_args' in json.loads(texts[-1]), texts + result, texts, _ = m.call('remove', tag=TAG) + assert result['isError'] and 'confirm' in texts[-1], texts result, texts, _ = m.call('game_state') - assert result['isError'] and 'launch_client' in texts[-1], texts + assert result['isError'] and 'with play' in texts[-1], texts - result, texts, _ = m.call('launch_client', world='Agent', creative=True, + result, texts, _ = m.call('play', world='Agent', creative=True, offscreen=sys.platform == 'darwin') assert not result['isError'], texts result, texts, _ = m.call('game_wait_ready', seconds=300) @@ -105,6 +119,9 @@ def no_ai_scenario(launcher, env, home): run = lambda *a: subprocess.run([str(launcher), *a], env=env, input='', capture_output=True, text=True, timeout=60) assert json.loads(run('no-ai', '--json').stdout) == {'no_ai': False} + config = json.loads(run('agent-config', '--json').stdout) + assert config['server']['args'] == ['mcp'] and len(config['clients']) == 4, config + assert 'agent-config' in run('--help').stdout m = Mcp(launcher, env) m.rpc('initialize', {'protocolVersion': '2025-06-18', 'capabilities': {}, 'clientInfo': {'name': 'launcher_mcp_e2e', 'version': '1'}}) @@ -117,9 +134,11 @@ def no_ai_scenario(launcher, env, home): except Failed as e: assert REFUSAL in str(e), e m.close() - r = run('mcp') - print(f'[launcher-mcp] mcp under No AI -> exit {r.returncode}: {r.stderr.strip()}') - assert r.returncode == 1 and r.stderr.strip() == f'error: {REFUSAL}', r + for command in ('mcp', 'agent-config'): + r = run(command) + print(f'[launcher-mcp] {command} under No AI -> exit {r.returncode}: {r.stderr.strip()}') + assert r.returncode == 1 and r.stderr.strip() == f'error: {REFUSAL}', r + assert 'agent-config' not in run('--help').stdout and ' mcp ' not in run('--help').stdout # What the launcher needs keeps working. assert run('versions', '--installed', '--json').returncode == 0 assert run('no-ai', 'off').returncode == 0