use anyhow::Result;
use serde_json::{Map, Value, json};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use crate::{
client, connect,
reply::{Fail, envelope},
script,
};
const PROTOCOL_VERSION: &str = "2025-06-18";
const SCRIPT_DOC: &str = "Run JavaScript that drives the phone, in one call: loops, conditions and several steps without a round trip each. \
The commands are functions that return what the tool of the same name returns: read(opts), find(selector), tap(target, opts), swipe(direction | {from, to}, opts), \
pinch(direction | {scale, rotate, at}, opts), scroll(direction, {until, max}), type(text, {clear, submit}), key(name), button(name), launch(app, {restart, arguments, environment}), apps(). Also waitFor(selector, {timeout_ms}), \
readField({selector, take, regex}) → text, readList({row, columns, group, stop_below, max_scrolls}) → {rows, scrolls, ended}, sleep(ms), log(…), output(key, value). \
tap(target) waits up to 5 s for a selector to appear and hold still; tap([a, b, c]) presses a keypad without re-reading. \
A call that fails throws an Error with .code, .outcome, .hint and .result (the full result object); uncaught, it ends the script and the result says which call and line. \
After a call whose outcome is \"unknown\" the script is stopped and cannot go on. \
For type(), verified means read back, not text matched; inspect value_changed and warning, never automatically retype. submit withholds Return with unknown / type_not_verified when the effect is uncertain. \
No files, network or timers; Date, JSON, RegExp, Map and the rest of the language are there. The result has outputs (the returned object, plus output() calls), logs, calls and inputs_sent.";
const SELECTOR_DOC: &str = "Selector: a plain string is an exact label (the name part of a \"name, value\" row also counts). \
Or combine terms: label=\"exact\", label~=\"contains\", label/regex/, role=button, id=<identifier or element id>, \
value~=…, within=\"<selector>\", index=N. An object works too: {label, label_contains, label_regex, value, \
value_contains, role, id, id_contains, id_regex, within, index}. More than one match is an error that lists the candidates.";
fn tool(name: &str, description: &str, properties: Value, required: &[&str]) -> Value {
json!({
"name": name,
"description": description,
"inputSchema": {
"type": "object",
"properties": properties,
"required": required,
"additionalProperties": false,
},
})
}
fn tools() -> Vec<Value> {
let selector = json!({ "description": SELECTOR_DOC, "type": ["string", "object"] });
vec![
tool(
"iph_connect",
"Verify and save the selected paired iPhone's IP address when automatic discovery fails. Requires prior USB trust on this computer. Checks a paired session and reported UDID before saving. Subsequent tools and scripts use the address; this does not establish developer-service readiness or repair Apple's discovery list.",
json!({ "ip": { "type": "string", "description": "The iPhone's IPv4 or IPv6 address. Link-local IPv6 needs the computer's numeric interface index, e.g. fe80::1234%12." } }),
&["ip"],
),
tool(
"iph_read",
"Read the iPhone's current screen as a list of elements (id, role, label, value, frame in points, traits, enabled). \
Read before acting; coordinates and labels come from here. Only on-screen elements unless all=true.",
json!({
"app": { "type": "boolean", "description": "Only the foreground app's elements." },
"all": { "type": "boolean", "description": "Include elements outside the screen." },
"full": { "type": "boolean", "description": "Wait ~0.6 s more for accessibility identifiers." },
"max_age_ms": { "type": "integer", "description": "Accept a cached reading this recent instead of asking the phone (a fresh read takes about 1.2 s)." },
}),
&[],
),
tool(
"iph_find",
"Find elements on screen that match a selector.",
json!({ "selector": selector, "all": { "type": "boolean" } }),
&["selector"],
),
tool(
"iph_tap",
"Tap an element (selector) or a point (\"x,y\" in points). Waits for the screen to change and hold still, \
then returns it (`elements`, as iph_read does) and whether it changed. \
Never retry a tap whose outcome is \"unknown\".",
json!({
"target": { "description": format!("A selector, or \"x,y\". {SELECTOR_DOC}"), "type": ["string", "object"] },
"long_ms": { "type": "integer", "description": "Hold this long instead of a short tap." },
"double": { "type": "boolean" },
"no_wait": { "type": "boolean", "description": "Read the screen once right after the tap instead of waiting for it to settle; the result then has no elements." },
}),
&["target"],
),
tool(
"iph_swipe",
"Swipe the finger up, down, left or right across the middle of the screen, or between two points.",
json!({
"direction": { "type": "string", "enum": ["up", "down", "left", "right"] },
"from": { "type": "array", "items": { "type": "number" }, "minItems": 2, "maxItems": 2 },
"to": { "type": "array", "items": { "type": "number" }, "minItems": 2, "maxItems": 2 },
"duration_ms": { "type": "integer" },
"drag": { "type": "boolean", "description": "Slow to a stop before lifting (a drag) instead of flicking." },
}),
&[],
),
tool(
"iph_pinch",
"Two fingers on the screen: pinch in or out to zoom, turn to rotate (a map, an image, a web page). Give a direction, or a scale and/or a rotation. \
The fingers meet in the middle of the screen, or at `at`. `screen_changed: false` is a fair answer on a screen that does not zoom. \
Never retry one whose outcome is \"unknown\".",
json!({
"direction": { "type": "string", "enum": ["in", "out"], "description": "in = scale 0.5, out = scale 2. Not together with scale." },
"scale": { "type": "number", "minimum": 0.25, "maximum": 4, "description": "End distance between the fingers over the start distance: above 1 spreads them (zoom in), below 1 pinches (zoom out)." },
"rotate": { "type": "number", "minimum": -180, "maximum": 180, "description": "Degrees, positive clockwise." },
"at": { "description": format!("Where the fingers meet: a selector, or \"x,y\" in points. Default: the middle of the screen. {SELECTOR_DOC}"), "type": ["string", "object"] },
"duration_ms": { "type": "integer", "description": "How long the fingers move (default 500, 100..10000)." },
}),
&[],
),
tool(
"iph_scroll",
"Scroll the content. \"down\" shows what is further down. With `until`, keeps scrolling until that element is on screen.",
json!({
"direction": { "type": "string", "enum": ["up", "down"] },
"until": selector,
"max": { "type": "integer", "description": "Most scrolls to try (default 10)." },
}),
&["direction"],
),
tool(
"iph_type",
"Type text into the field that has the keyboard (tap the field first). Pasted through the clipboard, so Korean and emoji work; \
the user's clipboard is put back (not content copied in an app: see clipboard_note). verified means the value was read, not that it matches the intended text. \
Inspect value_before, value, value_changed (true/false/null) and warning. An unchanged value can mean blocked paste, masking or identical replacement; never automatically retype. \
screen_changed compares accessibility readings after keyboard restoration (null if unavailable). submit withholds Return with outcome unknown / type_not_verified when the input effect is uncertain.",
json!({
"text": { "type": "string" },
"clear": { "type": "boolean", "description": "Replace what the field holds." },
"submit": { "type": "boolean", "description": "Press Return only after observing a changed, nonempty value (or an empty value for clear-only). Otherwise withhold Return and return unknown; inspect before taking another action." },
}),
&["text"],
),
tool(
"iph_key",
"Press a key: return, esc, tab, space, backspace, delete, arrows, or a combination like cmd+a.",
json!({ "key": { "type": "string" } }),
&["key"],
),
tool(
"iph_button",
"Press a hardware button.",
json!({ "button": { "type": "string", "enum": ["home", "lock", "volume_up", "volume_down"] } }),
&["button"],
),
tool(
"iph_launch",
"Bring an app to the front by bundle id (com.apple.Preferences) or by its name.",
json!({
"app": { "type": "string" },
"restart": { "type": "boolean", "description": "Quit the app first so it starts from its first screen." },
"arguments": {
"type": "array", "items": { "type": "string" },
"description": "Launch arguments for the app, e.g. [\"-AppleLanguages\", \"(ko)\"]. The app is restarted, since a running process takes none.",
},
"environment": {
"type": "object", "additionalProperties": { "type": "string" },
"description": "Environment variables for the app's process, e.g. {\"TZ\": \"UTC\"}. The app is restarted.",
},
}),
&["app"],
),
tool("iph_apps", "List installed apps with their bundle ids.", json!({}), &[]),
tool(
"iph_dnd",
"Do Not Disturb on the phone, so a notification banner cannot take a tap. \"on\" before the work, \"off\" when it is done \
(puts back the Focus that was on).",
json!({ "action": { "type": "string", "enum": ["on", "off", "status"] } }),
&["action"],
),
tool(
"iph_screenshot",
"Save a PNG screenshot to a file on this computer. Use iph_read for content; this is for looks.",
json!({ "path": { "type": "string", "description": "Absolute path of the PNG to write." } }),
&["path"],
),
tool(
"iph_batch",
"Run several steps in one call, stopping at the first failure. Each step is a one-key object: \
{\"launch\": \"…\"}, {\"wait_for\": selector}, {\"tap\": selector}, {\"type\": {\"text\": \"…\"}}, {\"swipe\": \"up\"}, {\"pinch\": \"out\"}, \
{\"scroll_until\": selector}, {\"read_field\": {\"name\", \"selector\", \"take\"}}, {\"read_list\": {\"name\", \"row\", \"columns\"}}, \
{\"assert\": selector}, {\"button\": \"home\"}, {\"key\": \"return\"}, {\"sleep\": ms}.",
json!({ "steps": { "type": "array", "items": { "type": "object" } } }),
&["steps"],
),
tool(
"iph_script",
SCRIPT_DOC,
json!({
"code": { "type": "string", "description": "JavaScript. The body of a function: `return` ends it and its value becomes `outputs`." },
"args": { "type": "object", "description": "What the script reads as `args`." },
}),
&["code"],
),
tool(
"iph_run",
"Run a saved script by name (see iph_scripts) in one call and get its outputs. Same result as iph_script.",
json!({
"name": { "type": "string" },
"args": { "type": "object", "description": "What the script reads as `args`." },
}),
&["name"],
),
tool("iph_scripts", "List saved scripts: name, what each does, and where it lives.", json!({}), &[]),
tool(
"iph_doctor",
"Check that the phone is ready. Each check says what the user must do when it fails.",
json!({
"no_touch_test": { "type": "boolean", "description": "Skip the check that scrolls Settings down and back." },
"fix_wifi": { "type": "boolean", "description": "Enable disabled Wi-Fi connection/debugging flags over USB and briefly check Network discovery." },
}),
&[],
),
]
}
async fn call(udid: &str, name: &str, args: Value) -> Value {
let started = std::time::Instant::now();
let args = if args.is_null() { json!({}) } else { args };
match name {
"iph_connect" => match serde_json::from_value::<connect::Args>(args) {
Ok(args) => envelope(connect::run(udid, args).await, started),
Err(e) => envelope(Err(Fail::invalid(e.to_string())), started),
},
"iph_scripts" => envelope(script::cmd_scripts(), started),
"iph_script" | "iph_run" => match script_request(name, &args) {
Ok(request) => client::request(udid, "script", request).await,
Err(f) => envelope(Err(f), started),
},
"iph_read" | "iph_find" | "iph_tap" | "iph_swipe" | "iph_pinch" | "iph_scroll" | "iph_type" | "iph_key"
| "iph_button" | "iph_launch" | "iph_apps" | "iph_screenshot" | "iph_batch" | "iph_doctor"
| "iph_dnd" => {
let cmd = name.trim_start_matches("iph_");
let args = if cmd == "apps" { Value::Null } else { args };
client::request(udid, cmd, args).await
}
other => envelope(Err(Fail::invalid(format!("unknown tool `{other}`"))), started),
}
}
fn script_request(tool: &str, args: &Value) -> Result<Value, Fail> {
let empty = Map::new();
let given = match args.get("args") {
None | Some(Value::Null) => &empty,
Some(Value::Object(map)) => map,
Some(_) => return Err(Fail::invalid("`args` takes an object")),
};
let text = |key: &str| {
args.get(key)
.and_then(|v| v.as_str())
.ok_or_else(|| Fail::invalid(format!("{tool} needs `{key}`")))
};
if tool == "iph_script" {
let code = match args.get("script").and_then(|v| v.as_str()) {
Some(code) if args.get("code").is_none() => code,
_ => text("code")?,
};
return Ok(script::request(code, given, None));
}
let name = text("name")?;
let (code, source) = script::load(name)?;
Ok(script::request(&code, given, Some((name, &source))))
}
fn response(id: &Value, result: Value) -> Value {
json!({ "jsonrpc": "2.0", "id": id, "result": result })
}
fn error(id: &Value, code: i64, message: &str) -> Value {
json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } })
}
fn offered(only: &[String]) -> Vec<Value> {
tools()
.into_iter()
.filter(|t| {
let name = t["name"].as_str().unwrap_or("");
only.is_empty() || only.iter().any(|o| o == name || format!("iph_{o}") == name)
})
.collect()
}
async fn handle(udid: &str, only: &[String], msg: &Value) -> Option<Value> {
let method = msg.get("method").and_then(|m| m.as_str())?;
let id = msg.get("id")?;
let empty = Map::new();
let params = msg.get("params").and_then(|p| p.as_object()).unwrap_or(&empty);
Some(match method {
"initialize" => {
let version = params
.get("protocolVersion")
.and_then(|v| v.as_str())
.unwrap_or(PROTOCOL_VERSION);
response(
id,
json!({
"protocolVersion": version,
"capabilities": { "tools": {} },
"serverInfo": { "name": "iph", "version": env!("CARGO_PKG_VERSION") },
"instructions": "Operate a real iPhone through its accessibility tree. Read the screen with iph_read, act with iph_tap / iph_type / iph_scroll, \
and check `screen_changed` in each result. For typing also check value_changed and warning: verified only means read back. Never automatically retype on a warning. For a known sequence prefer one iph_script (or a saved one with iph_run): one call instead of one per step. \
Outcome \"unknown\" means input may have gone out: read the screen, never resend.",
}),
)
}
"ping" => response(id, json!({})),
"tools/list" => response(id, json!({ "tools": offered(only) })),
"tools/call" => {
let Some(name) = params.get("name").and_then(|n| n.as_str()) else {
return Some(error(id, -32602, "tools/call needs a tool name"));
};
if !offered(only).iter().any(|t| t["name"] == name) {
return Some(error(id, -32602, "this server does not offer that tool"));
}
let args = params.get("arguments").cloned().unwrap_or(Value::Null);
let result = call(udid, name, args).await;
let is_error = result["ok"] != true;
response(
id,
json!({
"content": [{ "type": "text", "text": result.to_string() }],
"isError": is_error,
}),
)
}
"resources/list" => response(id, json!({ "resources": [] })),
"prompts/list" => response(id, json!({ "prompts": [] })),
_ => error(id, -32601, "method not found"),
})
}
pub async fn serve(udid: String, only: Vec<String>) -> Result<()> {
let mut lines = BufReader::new(tokio::io::stdin()).lines();
let mut stdout = tokio::io::stdout();
while let Some(line) = lines.next_line().await? {
let line = line.trim();
if line.is_empty() {
continue;
}
let reply = match serde_json::from_str::<Value>(line) {
Ok(msg) => handle(&udid, &only, &msg).await,
Err(_) => Some(error(&Value::Null, -32700, "parse error")),
};
if let Some(reply) = reply {
stdout.write_all(format!("{reply}\n").as_bytes()).await?;
stdout.flush().await?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn launch_offers_arguments_and_environment() {
let launch = tools().into_iter().find(|t| t["name"] == "iph_launch").unwrap();
let props = &launch["inputSchema"]["properties"];
assert_eq!(props["arguments"]["items"]["type"], "string");
assert_eq!(props["environment"]["additionalProperties"]["type"], "string");
}
#[test]
fn tool_list_covers_the_spec() {
let names: Vec<String> = tools()
.iter()
.map(|t| t["name"].as_str().unwrap().to_string())
.collect();
for expected in [
"iph_read", "iph_find", "iph_tap", "iph_swipe", "iph_pinch", "iph_scroll", "iph_type", "iph_button",
"iph_launch", "iph_batch", "iph_script", "iph_run", "iph_scripts", "iph_doctor", "iph_connect",
] {
assert!(names.contains(&expected.to_string()), "missing {expected}");
}
for t in tools() {
assert_eq!(t["inputSchema"]["type"], "object");
assert!(!t["description"].as_str().unwrap().is_empty());
}
}
#[test]
fn the_pinch_tool_offers_what_the_command_accepts() {
let tool = tools().into_iter().find(|t| t["name"] == "iph_pinch").unwrap();
let props = tool["inputSchema"]["properties"].as_object().unwrap();
let mut keys: Vec<&str> = props.keys().map(String::as_str).collect();
keys.sort();
assert_eq!(keys, ["at", "direction", "duration_ms", "rotate", "scale"]);
assert_eq!(props["direction"]["enum"], json!(["in", "out"]));
assert!(tool["inputSchema"].get("required").is_none_or(|r| r.as_array().is_some_and(|r| r.is_empty())));
for args in [
json!({"direction": "out", "rotate": 30, "at": "Map", "duration_ms": 300}),
json!({"scale": 0.5, "at": {"x": 100, "y": 200}}),
] {
assert!(serde_json::from_value::<crate::actions::PinchArgs>(args).is_ok());
}
assert!(serde_json::from_value::<crate::actions::PinchArgs>(json!({"direction": "out", "zoom": 2})).is_err());
}
#[test]
fn a_script_request_takes_code_or_a_saved_name() {
let req = script_request("iph_script", &json!({"code": "return 1", "args": {"n": 2}})).unwrap();
assert_eq!(req, json!({"code": "return 1", "args": {"n": 2}}));
let req = script_request("iph_script", &json!({"script": "return 2"})).unwrap();
assert_eq!(req["code"], "return 2");
let req = script_request("iph_run", &json!({"name": "settings-version"})).unwrap();
assert_eq!(req["script"], "settings-version");
assert_eq!(req["source"], "builtin:settings-version");
assert!(req["code"].as_str().unwrap().contains("launch("));
for bad in [json!({}), json!({"code": 1}), json!({"code": "x", "args": [1]})] {
assert_eq!(script_request("iph_script", &bad).unwrap_err().code, "invalid_argument", "{bad}");
}
assert_eq!(script_request("iph_run", &json!({"name": "nope"})).unwrap_err().code, "script_not_found");
}
#[tokio::test]
async fn connect_rejects_missing_invalid_and_extra_arguments_before_contacting_a_phone() {
for args in [json!({}), json!({"ip": "not-an-ip"}),
json!({"ip": "192.0.2.1", "submit": true})] {
let result = call("NO-PHONE", "iph_connect", args).await;
assert_eq!(result["ok"], false);
assert_eq!(result["outcome"], "not_sent");
assert_eq!(result["error"]["code"], "invalid_argument");
}
}
#[tokio::test]
async fn initialize_and_notifications() {
let init = json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{}}});
let r = handle("X", &[], &init).await.unwrap();
assert_eq!(r["result"]["protocolVersion"], "2024-11-05");
assert_eq!(r["result"]["serverInfo"]["name"], "iph");
let note = json!({"jsonrpc":"2.0","method":"notifications/initialized"});
assert!(handle("X", &[], ¬e).await.is_none());
let unknown = json!({"jsonrpc":"2.0","id":2,"method":"nope"});
assert_eq!(handle("X", &[], &unknown).await.unwrap()["error"]["code"], -32601);
}
#[tokio::test]
async fn tools_can_be_limited() {
let only = vec!["read".to_string(), "iph_find".to_string()];
let list = json!({"jsonrpc":"2.0","id":1,"method":"tools/list"});
let r = handle("X", &only, &list).await.unwrap();
let names: Vec<&str> = r["result"]["tools"]
.as_array()
.unwrap()
.iter()
.map(|t| t["name"].as_str().unwrap())
.collect();
assert_eq!(names, ["iph_read", "iph_find"]);
let call = json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"iph_tap","arguments":{"target":"x"}}});
assert_eq!(handle("X", &only, &call).await.unwrap()["error"]["code"], -32602);
}
}