Launcher MCP: play the running game through game_* tools

An agent now needs one MCP server. horizon-launcher mcp runs the selected
version's horizon-ctl mcp as a child and offers its tools as game_<name>
(all but launch, which launch_client covers), passing calls and image
results through. launch_client starts the game with a control socket in
the launcher's data folder, takes world, creative and offscreen, and
returns once the socket answers. A game tool called while no game listens
says to call launch_client.

tools/launcher_mcp_e2e.py checks it end to end against this checkout's
builds in a scratch launcher home.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-15 14:23:57 +02:00
parent c6eb50f10b
commit b0abb62883
5 changed files with 431 additions and 11 deletions
+8
View File
@@ -104,6 +104,14 @@ finishes in the background), `sign_out` and `select_account`.
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
version is offered as `game_<name>`: `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`.
The window, the command line and the MCP server all call the same core, `src/backend.rs`.
## Microsoft accounts
+216
View File
@@ -0,0 +1,216 @@
//! 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_<name>`, and calls go to it unchanged. `launch_client` starts the game
//! with the control socket that child talks to.
use horizon_launcher::backend;
use serde_json::{json, Value};
use std::io::{BufRead, BufReader, Write};
use std::path::PathBuf;
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.
const HIDDEN: &[&str] = &["launch"];
const CTL: &str = if cfg!(windows) {
"horizon-ctl.exe"
} else {
"horizon-ctl"
};
/// The control endpoint of a game started by `launch_client`: 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) {
"game-control.sock"
} else {
"game-control.json"
})
}
/// The game arguments that put it under the agent's control.
pub fn control_args() -> Vec<String> {
vec![
"--control-socket".into(),
socket_path().display().to_string(),
]
}
/// Whether a game answers on the control endpoint (a crashed game's socket refuses).
pub fn listening() -> bool {
let path = socket_path();
#[cfg(unix)]
return std::os::unix::net::UnixStream::connect(path).is_ok();
#[cfg(not(unix))]
return path.exists();
}
pub struct GameTools {
child: Child,
stdin: ChildStdin,
stdout: BufReader<ChildStdout>,
next_id: u64,
tools: Vec<Value>,
}
impl GameTools {
/// Start `horizon-ctl mcp` of an installed version and read its tools.
pub fn start(tag: &str) -> Result<Self, String> {
let ctl = backend::version_dir(tag).join(CTL);
if !ctl.exists() {
return Err(format!("{tag} has no {CTL}"));
}
let mut child = Command::new(&ctl)
.arg("--socket")
.arg(socket_path())
.arg("mcp")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.map_err(|e| format!("Could not start {}: {e}", ctl.display()))?;
let stdin = child.stdin.take().ok_or("no stdin")?;
let stdout = BufReader::new(child.stdout.take().ok_or("no stdout")?);
let mut tools = Self {
child,
stdin,
stdout,
next_id: 0,
tools: Vec::new(),
};
tools.rpc(
"initialize",
json!({ "protocolVersion": crate::mcp::PROTOCOL, "capabilities": {},
"clientInfo": { "name": "horizon-launcher", "version": backend::VERSION } }),
)?;
tools.send(&json!({ "jsonrpc": "2.0", "method": "notifications/initialized" }))?;
let listed = tools.rpc("tools/list", json!({}))?;
tools.tools = prefixed(&listed["tools"]);
Ok(tools)
}
/// The game's tools, named `game_<name>`.
pub fn tools(&self) -> &[Value] {
&self.tools
}
/// Call a `game_` tool; the result is horizon-ctl's (text and image content).
pub fn call(&mut self, name: &str, args: &Value) -> Result<Value, String> {
let inner = name.strip_prefix(PREFIX).ok_or("not a game tool")?;
let result = self.rpc("tools/call", json!({ "name": inner, "arguments": args }))?;
Ok(explain_unreachable(result))
}
fn send(&mut self, message: &Value) -> Result<(), String> {
writeln!(self.stdin, "{message}")
.and_then(|_| self.stdin.flush())
.map_err(|e| format!("horizon-ctl stopped: {e}"))
}
fn rpc(&mut self, method: &str, params: Value) -> Result<Value, String> {
self.next_id += 1;
let id = self.next_id;
self.send(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }))?;
let mut line = String::new();
loop {
line.clear();
match self.stdout.read_line(&mut line) {
Ok(0) | Err(_) => return Err("horizon-ctl stopped".into()),
Ok(_) => {}
}
let Ok(reply) = serde_json::from_str::<Value>(&line) else {
continue;
};
if reply["id"] != id {
continue;
}
if let Some(error) = reply.get("error") {
return Err(error["message"].as_str().unwrap_or("error").to_owned());
}
return Ok(reply["result"].clone());
}
}
}
impl Drop for GameTools {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
/// horizon-ctl's tools as the launcher offers them.
fn prefixed(tools: &Value) -> Vec<Value> {
tools
.as_array()
.into_iter()
.flatten()
.filter(|t| !HIDDEN.contains(&t["name"].as_str().unwrap_or_default()))
.map(|t| {
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): {}",
t["description"].as_str().unwrap_or_default()
)
.into();
t
})
.collect()
}
/// A game tool called while no game listens says how to start one from here.
fn explain_unreachable(mut result: Value) -> Value {
let unreachable = result["isError"] == true
&& result["content"].as_array().is_some_and(|c| {
c.iter().any(|block| {
block["text"]
.as_str()
.and_then(|t| serde_json::from_str::<Value>(t).ok())
.is_some_and(|v| v["kind"] == "connection")
})
});
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.",
"kind": "state",
}).to_string() }]);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn offers_the_game_tools_prefixed_without_launch() {
let listed = json!([
{ "name": "launch", "description": "start", "inputSchema": {} },
{ "name": "click_slot", "description": "Click a slot", "inputSchema": { "type": "object" } },
]);
let tools = prefixed(&listed);
assert_eq!(tools.len(), 1);
assert_eq!(tools[0]["name"], "game_click_slot");
assert!(tools[0]["description"]
.as_str()
.unwrap()
.ends_with("Click a slot"));
assert_eq!(tools[0]["inputSchema"], json!({ "type": "object" }));
}
#[test]
fn a_connection_error_says_to_launch_the_client() {
let text = json!({ "error": "cannot connect", "kind": "connection" }).to_string();
let result = explain_unreachable(
json!({ "content": [{ "type": "text", "text": text }], "isError": true }),
);
assert!(result["content"][0]["text"]
.as_str()
.unwrap()
.contains("launch_client"));
let other = json!({ "content": [{ "type": "text", "text": "{\"error\":\"no world\"}" }], "isError": true });
assert_eq!(explain_unreachable(other.clone()), other);
}
}
+1
View File
@@ -2,6 +2,7 @@
//! and starts the client or a dedicated server.
mod cli;
mod game_tools;
mod markdown;
mod mcp;
mod perf;
+72 -11
View File
@@ -1,6 +1,8 @@
//! `horizon-launcher mcp`: the Model Context Protocol over stdin and stdout (JSON-RPC 2.0, one
//! 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.
//! `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::game_tools::{self, GameTools};
use horizon_launcher::account::{self, Accounts, SignIn, SignInState};
use horizon_launcher::backend::{self, Job, Logged};
use serde_json::{json, Value};
@@ -8,12 +10,14 @@ use std::io::{BufRead, Write};
use std::path::PathBuf;
use std::time::Duration;
const PROTOCOL: &str = "2025-06-18";
pub const PROTOCOL: &str = "2025-06-18";
struct Session {
server: Option<Logged>,
client: Option<Logged>,
sign_in: Option<SignIn>,
/// The selected version's `horizon-ctl mcp`, once a version is installed.
game: Option<GameTools>,
}
fn tools() -> Value {
@@ -28,8 +32,11 @@ fn tools() -> Value {
"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 Minecraft 26.3 played once in the official launcher and Java 25; 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 official launcher's game folder. Default: the launcher's setting, else the platform default." } } } },
{ "name": "launch_client", "description": "Start the Horizon client (a game window on the player's screen). Returns once it has started.",
"inputSchema": { "type": "object", "properties": { "version": version } } },
{ "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.",
"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." },
"offscreen": { "type": "boolean", "description": "Render without showing a window (game_screenshot still works)." } } } },
{ "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.",
"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.",
@@ -141,13 +148,39 @@ impl Session {
return Err("The client is already running.".into());
}
let tag = backend::resolve_version(arg_str(args, "version"))?;
let client = Logged::start(Job::Client, backend::client(&tag)?)?;
std::thread::sleep(Duration::from_secs(2));
if let Some(Err(e)) = client.finished() {
return Err(format!("{e}\n{}", client.tail(20).join("\n")));
let mut cmd = backend::client(&tag)?;
cmd.args(game_tools::control_args());
if let Some(world) = arg_str(args, "world") {
cmd.arg("--world").arg(world);
}
for flag in ["creative", "offscreen"] {
if args.get(flag).and_then(Value::as_bool).unwrap_or(false) {
cmd.arg(format!("--{flag}"));
}
}
let client = Logged::start(Job::Client, cmd)?;
// Started once its control socket answers, as horizon-ctl launch waits.
let deadline = std::time::Instant::now() + Duration::from_secs(120);
while !game_tools::listening() {
if let Some(result) = client.finished() {
return Err(format!(
"The client stopped: {}\n{}",
result.err().unwrap_or_default(),
client.tail(20).join("\n")
));
}
if std::time::Instant::now() > deadline {
return Err(format!(
"The client did not open its control socket within 2 minutes.\n{}",
client.tail(20).join("\n")
));
}
std::thread::sleep(Duration::from_millis(100));
}
self.client = Some(client);
Ok(format!("Started the {tag} client."))
Ok(format!(
"Started the {tag} client. The game_* tools play it; game_wait_ready waits until the world is ready."
))
}
"start_server" => {
if self.server.as_ref().is_some_and(|s| s.finished().is_none()) {
@@ -318,6 +351,16 @@ impl Session {
}
}
/// The game's tools, starting the selected version's horizon-ctl the first time.
fn game(&mut self) -> Option<&mut GameTools> {
if self.game.is_none() {
self.game = backend::resolve_version(None)
.and_then(|tag| GameTools::start(&tag))
.ok();
}
self.game.as_mut()
}
fn running_server(&mut self) -> Result<&mut Logged, String> {
match &mut self.server {
Some(s) if s.finished().is_none() => Ok(s),
@@ -331,15 +374,32 @@ 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.",
"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...",
})),
"ping" => Ok(json!({})),
"tools/list" => Ok(json!({ "tools": tools() })),
"tools/list" => {
let mut list = tools().as_array().cloned().unwrap_or_default();
if let Some(game) = self.game() {
list.extend(game.tools().iter().cloned());
}
Ok(json!({ "tools": list }))
}
"tools/call" => {
let name = params
.get("name")
.and_then(Value::as_str)
.ok_or((-32602, "name is required".to_string()))?;
if name.starts_with(game_tools::PREFIX) {
let args = params.get("arguments").cloned().unwrap_or(json!({}));
let game = self.game().ok_or((
-32602,
"No installed version with horizon-ctl: install one first".to_string(),
))?;
if !game.tools().iter().any(|t| t["name"] == name) {
return Err((-32602, format!("Unknown tool {name}")));
}
return game.call(name, &args).map_err(|e| (-32603, e));
}
if !tools()
.as_array()
.unwrap()
@@ -365,6 +425,7 @@ pub fn serve() -> Result<(), String> {
server: None,
client: None,
sign_in: None,
game: None,
};
let stdin = std::io::stdin();
let mut stdout = std::io::stdout();
+134
View File
@@ -0,0 +1,134 @@
#!/usr/bin/env python3
"""End-to-end check of the launcher's MCP playing the game through its game_* tools.
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.
python3 tools/launcher_mcp_e2e.py --bin-dir target/fast --launcher launcher/target/debug/horizon-launcher
On macOS the game renders offscreen (it runs in a locked session or over SSH); on Linux it needs
a display (vscreen on the desktop). Games started here have no audio.
"""
import argparse
import base64
import json
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
TAG = 'v2099.1.1'
class Failed(Exception):
pass
class Mcp:
def __init__(self, launcher, env):
self.proc = subprocess.Popen([str(launcher), 'mcp'], env=env, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, text=True)
self.next_id = 0
def rpc(self, method, params):
self.next_id += 1
self.proc.stdin.write(json.dumps({'jsonrpc': '2.0', 'id': self.next_id, 'method': method,
'params': params}) + '\n')
self.proc.stdin.flush()
reply = json.loads(self.proc.stdout.readline())
if 'error' in reply:
raise Failed(f'{method}: {reply["error"]}')
return reply['result']
def call(self, tool, **args):
result = self.rpc('tools/call', {'name': tool, 'arguments': args})
texts = [c['text'] for c in result['content'] if c['type'] == 'text']
images = [c for c in result['content'] if c['type'] == 'image']
print(f'[launcher-mcp] {tool} {args} -> {(texts[-1] if texts else "")[:300]}')
return result, texts, images
def close(self):
self.proc.stdin.close()
self.proc.wait(timeout=60)
def scenario(m, out):
init = m.rpc('initialize', {'protocolVersion': '2025-06-18', 'capabilities': {},
'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']:
assert name in tools, f'{name} missing from {sorted(tools)}'
assert 'game_launch' not in tools, 'launch_client covers horizon-ctl launch'
result, texts, _ = m.call('game_state')
assert result['isError'] and 'launch_client' in texts[-1], texts
result, texts, _ = m.call('launch_client', world='Agent', creative=True,
offscreen=sys.platform == 'darwin')
assert not result['isError'], texts
result, texts, _ = m.call('game_wait_ready', seconds=300)
assert not result['isError'], texts
result, texts, _ = m.call('game_state')
state = json.loads(texts[-1])
assert state['screen'] == 'playing' and state['gamemode'] == 'creative', state
m.call('game_pause')
result, texts, _ = m.call('game_ui')
ids = {w['id'] for w in json.loads(texts[-1])['widgets']}
assert 'back-to-game' in ids, ids
result, texts, _ = m.call('game_click', id='back-to-game')
assert json.loads(texts[-1])['screen'] == 'playing', texts
result, _, images = m.call('game_screenshot')
assert images, 'no image'
(out / 'launcher-mcp.png').write_bytes(base64.b64decode(images[0]['data']))
m.call('game_quit')
return {'tools': len(tools)}
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--bin-dir', required=True, help='horizon-client and horizon-ctl built from this checkout')
parser.add_argument('--launcher', required=True, help='a horizon-launcher binary')
parser.add_argument('--out', default=str(ROOT / '.local/launcher-mcp-e2e'), help='the screenshot goes here')
args = parser.parse_args()
bins = Path(args.bin_dir).resolve()
resources = (ROOT / '.local/horizon-client/26.3').resolve()
if not (resources / 'horizon-resources.json').exists():
sys.exit(f'no prepared resources in {resources}')
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
work = Path(tempfile.mkdtemp(prefix='hzlm-'))
version = work / 'launcher/versions' / TAG
(version / '.local/horizon-client').mkdir(parents=True)
for name in ['horizon-client', 'horizon-ctl']:
os.symlink(bins / name, version / name)
os.symlink(resources, version / '.local/horizon-client/26.3')
(version / '.installed').write_text('')
env = dict(os.environ, HORIZON_LAUNCHER_HOME=str(work / 'launcher'), HORIZON_HOME=str(work / 'home'),
HORIZON_NO_AUDIO='1')
m = Mcp(Path(args.launcher).resolve(), env)
try:
summary = scenario(m, out)
print(f'[launcher-mcp] PASS: {summary}')
ok = True
except (Failed, AssertionError, KeyError, json.JSONDecodeError) as e:
print(f'[launcher-mcp] FAIL: {e!r}')
ok = False
try:
m.call('game_quit')
except Exception:
pass
finally:
m.close()
shutil.rmtree(work, ignore_errors=True)
sys.exit(0 if ok else 1)
if __name__ == '__main__':
main()