1use anyhow::Result;
6use serde_json::{Map, Value, json};
7use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
8
9use crate::{
10 client, connect,
11 reply::{Fail, envelope},
12 script,
13};
14
15const PROTOCOL_VERSION: &str = "2025-06-18";
16
17const SCRIPT_DOC: &str = "Run JavaScript that drives the phone, in one call: loops, conditions and several steps without a round trip each. \
18The 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), \
19scroll(direction, {until, max}), type(text, {clear, submit}), key(name), button(name), launch(app, {restart}), apps(). Also waitFor(selector, {timeout_ms}), \
20readField({selector, take, regex}) → text, readList({row, columns, group, stop_below, max_scrolls}) → {rows, scrolls, ended}, sleep(ms), log(…), output(key, value). \
21tap(target) waits up to 5 s for a selector to appear and hold still; tap([a, b, c]) presses a keypad without re-reading. \
22A 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. \
23After a call whose outcome is \"unknown\" the script is stopped and cannot go on. \
24For 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. \
25No 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.";
26
27const SELECTOR_DOC: &str = "Selector: a plain string is an exact label (the name part of a \"name, value\" row also counts). \
28Or combine terms: label=\"exact\", label~=\"contains\", label/regex/, role=button, id=<identifier or element id>, \
29value~=…, within=\"<selector>\", index=N. An object works too: {label, label_contains, label_regex, value, \
30value_contains, role, id, id_contains, id_regex, within, index}. More than one match is an error that lists the candidates.";
31
32fn tool(name: &str, description: &str, properties: Value, required: &[&str]) -> Value {
33 json!({
34 "name": name,
35 "description": description,
36 "inputSchema": {
37 "type": "object",
38 "properties": properties,
39 "required": required,
40 "additionalProperties": false,
41 },
42 })
43}
44
45fn tools() -> Vec<Value> {
46 let selector = json!({ "description": SELECTOR_DOC, "type": ["string", "object"] });
47 vec![
48 tool(
49 "iph_connect",
50 "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.",
51 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." } }),
52 &["ip"],
53 ),
54 tool(
55 "iph_read",
56 "Read the iPhone's current screen as a list of elements (id, role, label, value, frame in points, traits, enabled). \
57 Read before acting; coordinates and labels come from here. Only on-screen elements unless all=true.",
58 json!({
59 "app": { "type": "boolean", "description": "Only the foreground app's elements." },
60 "all": { "type": "boolean", "description": "Include elements outside the screen." },
61 "full": { "type": "boolean", "description": "Wait ~0.6 s more for accessibility identifiers." },
62 "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)." },
63 }),
64 &[],
65 ),
66 tool(
67 "iph_find",
68 "Find elements on screen that match a selector.",
69 json!({ "selector": selector, "all": { "type": "boolean" } }),
70 &["selector"],
71 ),
72 tool(
73 "iph_tap",
74 "Tap an element (selector) or a point (\"x,y\" in points). Waits for the screen to change and hold still, \
75 then returns it (`elements`, as iph_read does) and whether it changed. \
76 Never retry a tap whose outcome is \"unknown\".",
77 json!({
78 "target": { "description": format!("A selector, or \"x,y\". {SELECTOR_DOC}"), "type": ["string", "object"] },
79 "long_ms": { "type": "integer", "description": "Hold this long instead of a short tap." },
80 "double": { "type": "boolean" },
81 "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." },
82 }),
83 &["target"],
84 ),
85 tool(
86 "iph_swipe",
87 "Swipe the finger up, down, left or right across the middle of the screen, or between two points.",
88 json!({
89 "direction": { "type": "string", "enum": ["up", "down", "left", "right"] },
90 "from": { "type": "array", "items": { "type": "number" }, "minItems": 2, "maxItems": 2 },
91 "to": { "type": "array", "items": { "type": "number" }, "minItems": 2, "maxItems": 2 },
92 "duration_ms": { "type": "integer" },
93 "drag": { "type": "boolean", "description": "Slow to a stop before lifting (a drag) instead of flicking." },
94 }),
95 &[],
96 ),
97 tool(
98 "iph_scroll",
99 "Scroll the content. \"down\" shows what is further down. With `until`, keeps scrolling until that element is on screen.",
100 json!({
101 "direction": { "type": "string", "enum": ["up", "down"] },
102 "until": selector,
103 "max": { "type": "integer", "description": "Most scrolls to try (default 10)." },
104 }),
105 &["direction"],
106 ),
107 tool(
108 "iph_type",
109 "Type text into the field that has the keyboard (tap the field first). Pasted through the clipboard, so Korean and emoji work; \
110 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. \
111 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. \
112 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.",
113 json!({
114 "text": { "type": "string" },
115 "clear": { "type": "boolean", "description": "Replace what the field holds." },
116 "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." },
117 }),
118 &["text"],
119 ),
120 tool(
121 "iph_key",
122 "Press a key: return, esc, tab, space, backspace, delete, arrows, or a combination like cmd+a.",
123 json!({ "key": { "type": "string" } }),
124 &["key"],
125 ),
126 tool(
127 "iph_button",
128 "Press a hardware button.",
129 json!({ "button": { "type": "string", "enum": ["home", "lock", "volume_up", "volume_down"] } }),
130 &["button"],
131 ),
132 tool(
133 "iph_launch",
134 "Bring an app to the front by bundle id (com.apple.Preferences) or by its name.",
135 json!({
136 "app": { "type": "string" },
137 "restart": { "type": "boolean", "description": "Quit the app first so it starts from its first screen." },
138 }),
139 &["app"],
140 ),
141 tool("iph_apps", "List installed apps with their bundle ids.", json!({}), &[]),
142 tool(
143 "iph_dnd",
144 "Do Not Disturb on the phone, so a notification banner cannot take a tap. \"on\" before the work, \"off\" when it is done \
145 (puts back the Focus that was on).",
146 json!({ "action": { "type": "string", "enum": ["on", "off", "status"] } }),
147 &["action"],
148 ),
149 tool(
150 "iph_screenshot",
151 "Save a PNG screenshot to a file on this computer. Use iph_read for content; this is for looks.",
152 json!({ "path": { "type": "string", "description": "Absolute path of the PNG to write." } }),
153 &["path"],
154 ),
155 tool(
156 "iph_batch",
157 "Run several steps in one call, stopping at the first failure. Each step is a one-key object: \
158 {\"launch\": \"…\"}, {\"wait_for\": selector}, {\"tap\": selector}, {\"type\": {\"text\": \"…\"}}, {\"swipe\": \"up\"}, \
159 {\"scroll_until\": selector}, {\"read_field\": {\"name\", \"selector\", \"take\"}}, {\"read_list\": {\"name\", \"row\", \"columns\"}}, \
160 {\"assert\": selector}, {\"button\": \"home\"}, {\"key\": \"return\"}, {\"sleep\": ms}.",
161 json!({ "steps": { "type": "array", "items": { "type": "object" } } }),
162 &["steps"],
163 ),
164 tool(
165 "iph_script",
166 SCRIPT_DOC,
167 json!({
168 "code": { "type": "string", "description": "JavaScript. The body of a function: `return` ends it and its value becomes `outputs`." },
169 "args": { "type": "object", "description": "What the script reads as `args`." },
170 }),
171 &["code"],
172 ),
173 tool(
174 "iph_run",
175 "Run a saved script by name (see iph_scripts) in one call and get its outputs. Same result as iph_script.",
176 json!({
177 "name": { "type": "string" },
178 "args": { "type": "object", "description": "What the script reads as `args`." },
179 }),
180 &["name"],
181 ),
182 tool("iph_scripts", "List saved scripts: name, what each does, and where it lives.", json!({}), &[]),
183 tool(
184 "iph_doctor",
185 "Check that the phone is ready. Each check says what the user must do when it fails.",
186 json!({
187 "no_touch_test": { "type": "boolean", "description": "Skip the check that scrolls Settings down and back." },
188 "fix_wifi": { "type": "boolean", "description": "Enable disabled Wi-Fi connection/debugging flags over USB and briefly check Network discovery." },
189 }),
190 &[],
191 ),
192 ]
193}
194
195async fn call(udid: &str, name: &str, args: Value) -> Value {
196 let started = std::time::Instant::now();
197 let args = if args.is_null() { json!({}) } else { args };
198 match name {
199 "iph_connect" => match serde_json::from_value::<connect::Args>(args) {
200 Ok(args) => envelope(connect::run(udid, args).await, started),
201 Err(e) => envelope(Err(Fail::invalid(e.to_string())), started),
202 },
203 "iph_scripts" => envelope(script::cmd_scripts(), started),
204 "iph_script" | "iph_run" => match script_request(name, &args) {
205 Ok(request) => client::request(udid, "script", request).await,
206 Err(f) => envelope(Err(f), started),
207 },
208 "iph_read" | "iph_find" | "iph_tap" | "iph_swipe" | "iph_scroll" | "iph_type" | "iph_key"
209 | "iph_button" | "iph_launch" | "iph_apps" | "iph_screenshot" | "iph_batch" | "iph_doctor"
210 | "iph_dnd" => {
211 let cmd = name.trim_start_matches("iph_");
212 let args = if cmd == "apps" { Value::Null } else { args };
213 client::request(udid, cmd, args).await
214 }
215 other => envelope(Err(Fail::invalid(format!("unknown tool `{other}`"))), started),
216 }
217}
218
219fn script_request(tool: &str, args: &Value) -> Result<Value, Fail> {
222 let empty = Map::new();
223 let given = match args.get("args") {
224 None | Some(Value::Null) => &empty,
225 Some(Value::Object(map)) => map,
226 Some(_) => return Err(Fail::invalid("`args` takes an object")),
227 };
228 let text = |key: &str| {
229 args.get(key)
230 .and_then(|v| v.as_str())
231 .ok_or_else(|| Fail::invalid(format!("{tool} needs `{key}`")))
232 };
233 if tool == "iph_script" {
234 let code = match args.get("script").and_then(|v| v.as_str()) {
237 Some(code) if args.get("code").is_none() => code,
238 _ => text("code")?,
239 };
240 return Ok(script::request(code, given, None));
241 }
242 let name = text("name")?;
243 let (code, source) = script::load(name)?;
244 Ok(script::request(&code, given, Some((name, &source))))
245}
246
247fn response(id: &Value, result: Value) -> Value {
248 json!({ "jsonrpc": "2.0", "id": id, "result": result })
249}
250
251fn error(id: &Value, code: i64, message: &str) -> Value {
252 json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } })
253}
254
255fn offered(only: &[String]) -> Vec<Value> {
257 tools()
258 .into_iter()
259 .filter(|t| {
260 let name = t["name"].as_str().unwrap_or("");
261 only.is_empty() || only.iter().any(|o| o == name || format!("iph_{o}") == name)
262 })
263 .collect()
264}
265
266async fn handle(udid: &str, only: &[String], msg: &Value) -> Option<Value> {
267 let method = msg.get("method").and_then(|m| m.as_str())?;
268 let id = msg.get("id")?;
270 let empty = Map::new();
271 let params = msg.get("params").and_then(|p| p.as_object()).unwrap_or(&empty);
272 Some(match method {
273 "initialize" => {
274 let version = params
275 .get("protocolVersion")
276 .and_then(|v| v.as_str())
277 .unwrap_or(PROTOCOL_VERSION);
278 response(
279 id,
280 json!({
281 "protocolVersion": version,
282 "capabilities": { "tools": {} },
283 "serverInfo": { "name": "iph", "version": env!("CARGO_PKG_VERSION") },
284 "instructions": "Operate a real iPhone through its accessibility tree. Read the screen with iph_read, act with iph_tap / iph_type / iph_scroll, \
285 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. \
286 Outcome \"unknown\" means input may have gone out: read the screen, never resend.",
287 }),
288 )
289 }
290 "ping" => response(id, json!({})),
291 "tools/list" => response(id, json!({ "tools": offered(only) })),
292 "tools/call" => {
293 let Some(name) = params.get("name").and_then(|n| n.as_str()) else {
294 return Some(error(id, -32602, "tools/call needs a tool name"));
295 };
296 if !offered(only).iter().any(|t| t["name"] == name) {
297 return Some(error(id, -32602, "this server does not offer that tool"));
298 }
299 let args = params.get("arguments").cloned().unwrap_or(Value::Null);
300 let result = call(udid, name, args).await;
301 let is_error = result["ok"] != true;
302 response(
303 id,
304 json!({
305 "content": [{ "type": "text", "text": result.to_string() }],
306 "isError": is_error,
307 }),
308 )
309 }
310 "resources/list" => response(id, json!({ "resources": [] })),
311 "prompts/list" => response(id, json!({ "prompts": [] })),
312 _ => error(id, -32601, "method not found"),
313 })
314}
315
316pub async fn serve(udid: String, only: Vec<String>) -> Result<()> {
318 let mut lines = BufReader::new(tokio::io::stdin()).lines();
319 let mut stdout = tokio::io::stdout();
320 while let Some(line) = lines.next_line().await? {
321 let line = line.trim();
322 if line.is_empty() {
323 continue;
324 }
325 let reply = match serde_json::from_str::<Value>(line) {
326 Ok(msg) => handle(&udid, &only, &msg).await,
327 Err(_) => Some(error(&Value::Null, -32700, "parse error")),
328 };
329 if let Some(reply) = reply {
330 stdout.write_all(format!("{reply}\n").as_bytes()).await?;
331 stdout.flush().await?;
332 }
333 }
334 Ok(())
335}
336
337#[cfg(test)]
338mod tests {
339 use super::*;
340
341 #[test]
342 fn tool_list_covers_the_spec() {
343 let names: Vec<String> = tools()
344 .iter()
345 .map(|t| t["name"].as_str().unwrap().to_string())
346 .collect();
347 for expected in [
348 "iph_read", "iph_find", "iph_tap", "iph_swipe", "iph_scroll", "iph_type", "iph_button",
349 "iph_launch", "iph_batch", "iph_script", "iph_run", "iph_scripts", "iph_doctor", "iph_connect",
350 ] {
351 assert!(names.contains(&expected.to_string()), "missing {expected}");
352 }
353 for t in tools() {
354 assert_eq!(t["inputSchema"]["type"], "object");
355 assert!(!t["description"].as_str().unwrap().is_empty());
356 }
357 }
358
359 #[test]
360 fn a_script_request_takes_code_or_a_saved_name() {
361 let req = script_request("iph_script", &json!({"code": "return 1", "args": {"n": 2}})).unwrap();
362 assert_eq!(req, json!({"code": "return 1", "args": {"n": 2}}));
363 let req = script_request("iph_script", &json!({"script": "return 2"})).unwrap();
365 assert_eq!(req["code"], "return 2");
366 let req = script_request("iph_run", &json!({"name": "settings-version"})).unwrap();
367 assert_eq!(req["script"], "settings-version");
368 assert_eq!(req["source"], "builtin:settings-version");
369 assert!(req["code"].as_str().unwrap().contains("launch("));
370 for bad in [json!({}), json!({"code": 1}), json!({"code": "x", "args": [1]})] {
371 assert_eq!(script_request("iph_script", &bad).unwrap_err().code, "invalid_argument", "{bad}");
372 }
373 assert_eq!(script_request("iph_run", &json!({"name": "nope"})).unwrap_err().code, "script_not_found");
374 }
375
376 #[tokio::test]
377 async fn connect_rejects_missing_invalid_and_extra_arguments_before_contacting_a_phone() {
378 for args in [json!({}), json!({"ip": "not-an-ip"}),
379 json!({"ip": "192.0.2.1", "submit": true})] {
380 let result = call("NO-PHONE", "iph_connect", args).await;
381 assert_eq!(result["ok"], false);
382 assert_eq!(result["outcome"], "not_sent");
383 assert_eq!(result["error"]["code"], "invalid_argument");
384 }
385 }
386
387 #[tokio::test]
388 async fn initialize_and_notifications() {
389 let init = json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{}}});
390 let r = handle("X", &[], &init).await.unwrap();
391 assert_eq!(r["result"]["protocolVersion"], "2024-11-05");
392 assert_eq!(r["result"]["serverInfo"]["name"], "iph");
393 let note = json!({"jsonrpc":"2.0","method":"notifications/initialized"});
394 assert!(handle("X", &[], ¬e).await.is_none());
395 let unknown = json!({"jsonrpc":"2.0","id":2,"method":"nope"});
396 assert_eq!(handle("X", &[], &unknown).await.unwrap()["error"]["code"], -32601);
397 }
398
399 #[tokio::test]
400 async fn tools_can_be_limited() {
401 let only = vec!["read".to_string(), "iph_find".to_string()];
402 let list = json!({"jsonrpc":"2.0","id":1,"method":"tools/list"});
403 let r = handle("X", &only, &list).await.unwrap();
404 let names: Vec<&str> = r["result"]["tools"]
405 .as_array()
406 .unwrap()
407 .iter()
408 .map(|t| t["name"].as_str().unwrap())
409 .collect();
410 assert_eq!(names, ["iph_read", "iph_find"]);
411 let call = json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"iph_tap","arguments":{"target":"x"}}});
413 assert_eq!(handle("X", &only, &call).await.unwrap()["error"]["code"], -32602);
414 }
415}