Skip to main content

iphone_cli/
mcp.rs

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