Skip to content

Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools

MCP:操作后顺带返回界面(then)、iphone_wait_for、iphone_batch,减少 agent 往返

Derrorsa01c38434564
diff --git a/Cargo.lock b/Cargo.lock
index be4059b..e9d7c72 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2006,6 +2006,7 @@ dependencies = [
"ictl-protocol",
"rmcp",
"serde_json",
+ "tokio",
]
[[package]]
diff --git a/README.md b/README.md
index 61022d2..d4cfa11 100644
--- a/README.md
+++ b/README.md
@@ -72,7 +72,7 @@ crates/
ictl-sign/ Apple ID 登录、注册设备、描述文件、签名(修复 .xctest 漏签)、签后自检
ictl-unlock/ 锁屏自动解锁(默认关闭)
ictl-daemon/ 守护进程:状态机、usbmuxd 看护、重签调度、通知、控制接口服务端
- ictl-mcp/ MCP 服务(stdio),13 个工具与 toolkit 一致
+ ictl-mcp/ MCP 服务(stdio),toolkit 的 13 个工具 + iphone_wait_for、iphone_batch
apps/
iphone-control/ 唯一的可执行程序(含隐藏的 debug 真机诊断)
vendor/ Impactor 的 plume_core / plume_store / omnisette 与打过补丁的 apple-codesign(见 THIRD_PARTY.md)
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs
index f1d4ff4..a25a944 100644
--- a/crates/ictl-daemon/src/core.rs
+++ b/crates/ictl-daemon/src/core.rs
@@ -32,6 +32,8 @@ pub const TICK: Duration = Duration::from_secs(10);
pub const STALE: Duration = Duration::from_secs(30);
/// 长按、滑动的时长上限(秒):HID 拖动按时长换算采样点,不设上限一个请求就能占住设备很久
pub const MAX_GESTURE_SECONDS: f64 = 10.0;
+/// 等界面稳定、等元素出现的上限(毫秒):持着设备锁等,不能太久
+pub const MAX_WAIT_MS: u64 = 30_000;
/// 持久化到 `state.json` 的状态(不含秘密)
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
@@ -327,6 +329,8 @@ impl Daemon {
Request::LaunchApp { app } => self.launch_app(g, &app).await,
Request::TerminateApp { app } => self.terminate_app(g, &app).await,
Request::OpenUrl { url } => self.open_url(g, &url).await,
+ Request::Settle { max_ms } => self.settle(g, Duration::from_millis(max_ms)).await,
+ Request::WaitFor { text, timeout_ms } => self.wait_for(g, &text, Duration::from_millis(timeout_ms)).await,
Request::Doctor => Ok(self.doctor(g).await),
Request::UnlockReset => {
let _ = std::fs::remove_file(self.cfg.unlock_disabled_flag());
@@ -352,6 +356,14 @@ impl Daemon {
/// 参数检查(与设备无关,不必拿锁)
fn check_request(req: &Request) -> Result<(), String> {
+ match req {
+ Request::Settle { max_ms } if *max_ms > MAX_WAIT_MS => return Err(format!("max_ms 不能超过 {MAX_WAIT_MS}")),
+ Request::WaitFor { timeout_ms, .. } if *timeout_ms > MAX_WAIT_MS => {
+ return Err(format!("timeout 不能超过 {} 秒", MAX_WAIT_MS / 1000));
+ }
+ Request::WaitFor { text, .. } if text.is_empty() => return Err("text 不能为空".into()),
+ _ => {}
+ }
let seconds = match req {
Request::LongPress { seconds, .. } | Request::Swipe { seconds, .. } => *seconds,
_ => return Ok(()),
diff --git a/crates/ictl-daemon/src/tools.rs b/crates/ictl-daemon/src/tools.rs
index c44288f..3aafd5d 100644
--- a/crates/ictl-daemon/src/tools.rs
+++ b/crates/ictl-daemon/src/tools.rs
@@ -170,6 +170,46 @@ impl Daemon {
Ok(if lines.is_empty() { "没有找到带文字的元素".into() } else { lines.join("\n") } + &more)
}
+ /// 等界面稳定:每隔一小会儿读一次元素树,连续两次一样就算稳定。读元素树时 WDA 本身也会等界面空闲。
+ /// 游戏这类元素很少的界面会马上判为稳定,看画面要截图
+ pub(crate) async fn settle(&self, g: &mut Inner, max: Duration) -> Result<String, String> {
+ let t0 = Instant::now();
+ let Some(w) = self.wda(g) else {
+ tokio::time::sleep(max.min(Duration::from_millis(500))).await;
+ return Ok("WDA 不可用,等了 0.5 秒".into());
+ };
+ let mut prev: Option<Vec<String>> = None;
+ loop {
+ let cur: Vec<String> =
+ w.elements().await.map_err(|e| e.to_string())?.iter().map(elements::Element::describe).collect();
+ if prev.as_ref() == Some(&cur) {
+ return Ok(format!("界面已稳定({:.1} 秒)", t0.elapsed().as_secs_f64()));
+ }
+ if t0.elapsed() >= max {
+ return Ok(format!("{:.1} 秒内界面一直在变(可能有动画),按最后的状态返回", max.as_secs_f64()));
+ }
+ prev = Some(cur);
+ tokio::time::sleep(Duration::from_millis(150)).await;
+ }
+ }
+
+ /// 等包含 `text` 的元素出现
+ pub(crate) async fn wait_for(&self, g: &mut Inner, text: &str, timeout: Duration) -> Result<String, String> {
+ self.ensure_unlocked(g).await?;
+ let t0 = Instant::now();
+ let w = self.require_wda(g)?;
+ loop {
+ let els = w.elements().await.map_err(|e| e.to_string())?;
+ if let Some(e) = elements::find(&els, text).first() {
+ return Ok(format!("已出现 {}({:.1} 秒)", e.describe(), t0.elapsed().as_secs_f64()));
+ }
+ if t0.elapsed() >= timeout {
+ return Err(format!("{:.0} 秒内没出现包含 \"{text}\" 的元素,截图看看屏幕", timeout.as_secs_f64()));
+ }
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ }
+ }
+
pub(crate) async fn tap(&self, g: &mut Inner, x: f64, y: f64) -> Result<String, String> {
self.ensure_unlocked(g).await?;
let pos = format!("({},{})", fmt_g(x), fmt_g(y));
diff --git a/crates/ictl-mcp/Cargo.toml b/crates/ictl-mcp/Cargo.toml
index ceda8da..fae706d 100644
--- a/crates/ictl-mcp/Cargo.toml
+++ b/crates/ictl-mcp/Cargo.toml
@@ -9,6 +9,7 @@ description = "MCP stdio 服务(13 个 iphone_* 工具)"
[dependencies]
ictl-protocol.workspace = true
+tokio.workspace = true
rmcp.workspace = true
serde_json.workspace = true
anyhow.workspace = true
diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rs
index 5613074..644949b 100644
--- a/crates/ictl-mcp/src/lib.rs
+++ b/crates/ictl-mcp/src/lib.rs
@@ -23,7 +23,9 @@ pub const INSTRUCTIONS: &str = "控制一台通过 USB 连接的真实 iPhone。
操作前先用 iphone_screenshot 或 iphone_list_elements 看清屏幕;能按名字点就优先用 iphone_tap_element。\
游戏、地图等界面没有元素树,只能看截图按坐标操作;小图标、小字看不清时用 iphone_screenshot 的区域放大。\
配置了锁屏密码时,各操作工具会先自动解锁。每次操作后再截图确认结果。\
-涉及付款、删除、发送消息、修改账号或隐私设置的操作,先向用户确认。";
+涉及付款、删除、发送消息、修改账号或隐私设置的操作,先向用户确认。\
+省时间:操作类工具可带 then=elements 或 then=screenshot,等界面稳定后顺带返回操作后的界面,不用再单独调一次;\
+几步确定的连续操作(按键、逐级点菜单、填表)用 iphone_batch 一次发完;等页面加载用 iphone_wait_for,不要反复截图。";
fn num(desc: &str) -> Value {
json!({"type": "number", "description": desc})
@@ -34,7 +36,46 @@ fn schema(props: Value, required: &[&str]) -> Map<String, Value> {
v.as_object().cloned().unwrap_or_default()
}
-/// 13 个工具的定义
+/// 操作后顺带返回界面时最多列多少个元素(每步都带太多会占满上下文)
+pub const THEN_LIMIT: usize = 80;
+/// 顺带返回界面前等界面稳定的上限
+pub const THEN_SETTLE_MS: u64 = 1500;
+/// 一次批量最多几步
+pub const BATCH_MAX_STEPS: usize = 20;
+/// 批量里能用的工具:改变界面的操作和等待;看界面用 then
+pub const BATCH_TOOLS: [&str; 11] = [
+ "iphone_tap",
+ "iphone_tap_element",
+ "iphone_long_press",
+ "iphone_swipe",
+ "iphone_type_text",
+ "iphone_press_button",
+ "iphone_launch_app",
+ "iphone_terminate_app",
+ "iphone_open_url",
+ "iphone_wait_for",
+ "wait",
+];
+
+/// 操作类工具共有的可选参数:操作后顺带返回界面
+fn then_props() -> Value {
+ json!({
+ "then": {"type": "string", "enum": ["none", "elements", "screenshot"], "default": "none",
+ "description": "操作后等界面稳定,再顺带返回界面:elements=元素列表(最多 80 个),screenshot=截图。省一次单独的调用"},
+ "then_filter": {"type": "string", "default": "", "description": "then=elements 时只列包含这段文字的元素"}
+ })
+}
+
+/// 在参数 schema 里加上 then / then_filter
+fn with_then(props: Value) -> Value {
+ let mut p = props;
+ if let (Some(o), Value::Object(extra)) = (p.as_object_mut(), then_props()) {
+ o.extend(extra);
+ }
+ p
+}
+
+/// 15 个工具的定义(toolkit 的 13 个 + iphone_wait_for、iphone_batch)
pub fn tools() -> Vec<Tool> {
let t = |name: &'static str, desc: &'static str, s: Map<String, Value>| Tool::new(name, desc, s);
vec![
@@ -55,17 +96,24 @@ pub fn tools() -> Vec<Tool> {
&[],
),
),
- t("iphone_tap", "点击屏幕坐标(点)。", schema(json!({"x": num("x(点)"), "y": num("y(点)")}), &["x", "y"])),
+ t(
+ "iphone_tap",
+ "点击屏幕坐标(点)。",
+ schema(with_then(json!({"x": num("x(点)"), "y": num("y(点)")})), &["x", "y"]),
+ ),
t(
"iphone_tap_element",
"按文字点击元素:先找标签/名字完全相同的,找不到再找包含该文字的。\n\nindex: 匹配到多个时点第几个(从 0 开始,顺序同 iphone_list_elements)。",
- schema(json!({"text": {"type": "string"}, "index": {"type": "integer", "default": 0}}), &["text"]),
+ schema(
+ with_then(json!({"text": {"type": "string"}, "index": {"type": "integer", "default": 0}})),
+ &["text"],
+ ),
),
t(
"iphone_long_press",
"长按屏幕坐标(点)。",
schema(
- json!({"x": num("x(点)"), "y": num("y(点)"), "seconds": {"type": "number", "default": 1.0}}),
+ with_then(json!({"x": num("x(点)"), "y": num("y(点)"), "seconds": {"type": "number", "default": 1.0}})),
&["x", "y"],
),
),
@@ -73,20 +121,25 @@ pub fn tools() -> Vec<Tool> {
"iphone_swipe",
"从一点滑到另一点(点坐标)。向上滑看下面的内容:from_y 大、to_y 小。",
schema(
- json!({"from_x": num(""), "from_y": num(""), "to_x": num(""), "to_y": num(""), "seconds": {"type": "number", "default": 0.3}}),
+ with_then(
+ json!({"from_x": num(""), "from_y": num(""), "to_x": num(""), "to_y": num(""), "seconds": {"type": "number", "default": 0.3}}),
+ ),
&["from_x", "from_y", "to_x", "to_y"],
),
),
t(
"iphone_type_text",
"在当前获得焦点的输入框里输入文字(支持中文)。需要先点中输入框。submit=True 时末尾按回车。",
- schema(json!({"text": {"type": "string"}, "submit": {"type": "boolean", "default": false}}), &["text"]),
+ schema(
+ with_then(json!({"text": {"type": "string"}, "submit": {"type": "boolean", "default": false}})),
+ &["text"],
+ ),
),
t(
"iphone_press_button",
"按硬件键:home(回主屏幕)、volume_up、volume_down、lock(锁屏;配置了密码时之后的操作会自动解锁)。",
schema(
- json!({"button": {"type": "string", "enum": ["home", "volume_up", "volume_down", "lock"]}}),
+ with_then(json!({"button": {"type": "string", "enum": ["home", "volume_up", "volume_down", "lock"]}})),
&["button"],
),
),
@@ -98,17 +151,40 @@ pub fn tools() -> Vec<Tool> {
t(
"iphone_launch_app",
"启动 App 并切到前台。app 可以是 Bundle ID,也可以是显示名(如「设置」「微信」)。",
- schema(json!({"app": {"type": "string"}}), &["app"]),
+ schema(with_then(json!({"app": {"type": "string"}})), &["app"]),
),
t(
"iphone_terminate_app",
"结束 App 进程。app 可以是 Bundle ID 或显示名。",
- schema(json!({"app": {"type": "string"}}), &["app"]),
+ schema(with_then(json!({"app": {"type": "string"}})), &["app"]),
),
t(
"iphone_open_url",
"用系统默认方式打开链接或 URL Scheme(网页会在 Safari 打开)。",
- schema(json!({"url": {"type": "string"}}), &["url"]),
+ schema(with_then(json!({"url": {"type": "string"}})), &["url"]),
+ ),
+ t(
+ "iphone_wait_for",
+ "等包含某段文字的界面元素出现(例如页面加载完、弹窗出现),出现就立即返回;超时报错。代替反复截图轮询。",
+ schema(
+ json!({"text": {"type": "string"}, "timeout": {"type": "number", "default": 5, "description": "最多等几秒(不超过 30)"}}),
+ &["text"],
+ ),
+ ),
+ t(
+ "iphone_batch",
+ "按顺序执行几步操作,一次调用完成(最多 20 步),某一步出错就停下并说明是第几步。\n\n\
+steps 每项是 {\"tool\": 工具名, 其余是该工具的参数},可用:iphone_tap、iphone_tap_element、iphone_long_press、\
+iphone_swipe、iphone_type_text、iphone_press_button、iphone_launch_app、iphone_terminate_app、iphone_open_url、\
+iphone_wait_for,以及 {\"tool\": \"wait\", \"seconds\": 秒数}(不超过 5)。\n\
+适合确定的连续操作;每步的结果不确定(例如点了以后不知道会跳到哪)时,还是一步步来。\n\
+then 同其他操作工具:全部做完后顺带返回界面。",
+ schema(
+ with_then(
+ json!({"steps": {"type": "array", "items": {"type": "object"}, "description": "要执行的步骤"}}),
+ ),
+ &["steps"],
+ ),
),
]
}
@@ -192,10 +268,71 @@ pub fn to_request(name: &str, args: &Map<String, Value>) -> Result<Request, Stri
"iphone_launch_app" => Request::LaunchApp { app: a.s("app")? },
"iphone_terminate_app" => Request::TerminateApp { app: a.s("app")? },
"iphone_open_url" => Request::OpenUrl { url: a.s("url")? },
+ "iphone_wait_for" => {
+ let secs = a.f_or("timeout", 5.0)?;
+ if !(0.0..=30.0).contains(&secs) {
+ return Err("timeout 要在 0 到 30 秒之间".into());
+ }
+ Request::WaitFor { text: a.s("text")?, timeout_ms: (secs * 1000.0) as u64 }
+ }
other => return Err(format!("未知工具 {other}")),
})
}
+/// 操作后顺带返回什么
+#[derive(Debug, Clone, PartialEq)]
+pub enum Then {
+ None,
+ Elements(String),
+ Screenshot,
+}
+
+pub fn parse_then(args: &Map<String, Value>) -> Result<Then, String> {
+ let a = Args(args);
+ match a.s_or("then", "none")?.as_str() {
+ "none" | "" => Ok(Then::None),
+ "elements" => Ok(Then::Elements(a.s_or("then_filter", "")?)),
+ "screenshot" => Ok(Then::Screenshot),
+ other => Err(format!("then 只能是 none / elements / screenshot,不是 {other}")),
+ }
+}
+
+/// 批量里的一步
+#[derive(Debug, Clone, PartialEq)]
+pub enum Step {
+ Request { tool: String, req: Request },
+ Wait(std::time::Duration),
+}
+
+/// 检查并转换批量步骤(一步都不执行就先把参数错误全挡掉)
+pub fn batch_steps(args: &Map<String, Value>) -> Result<Vec<Step>, String> {
+ let steps = args.get("steps").and_then(Value::as_array).ok_or("缺少 steps(数组)")?;
+ if steps.is_empty() || steps.len() > BATCH_MAX_STEPS {
+ return Err(format!("steps 要有 1 到 {BATCH_MAX_STEPS} 步"));
+ }
+ steps
+ .iter()
+ .enumerate()
+ .map(|(i, s)| {
+ let n = i + 1;
+ let obj = s.as_object().ok_or_else(|| format!("第 {n} 步不是对象"))?;
+ let tool = obj.get("tool").and_then(Value::as_str).ok_or_else(|| format!("第 {n} 步缺少 tool"))?;
+ if !BATCH_TOOLS.contains(&tool) {
+ return Err(format!("第 {n} 步:批量里不能用 {tool},可用:{}", BATCH_TOOLS.join("、")));
+ }
+ if tool == "wait" {
+ let secs = Args(obj).f("seconds").map_err(|e| format!("第 {n} 步:{e}"))?;
+ if !(0.0..=5.0).contains(&secs) {
+ return Err(format!("第 {n} 步:wait 的 seconds 要在 0 到 5 之间"));
+ }
+ return Ok(Step::Wait(std::time::Duration::from_secs_f64(secs)));
+ }
+ let req = to_request(tool, obj).map_err(|e| format!("第 {n} 步({tool}):{e}"))?;
+ Ok(Step::Request { tool: tool.to_owned(), req })
+ })
+ .collect()
+}
+
/// 守护进程响应 → MCP 结果。错误走工具错误(is_error),文字原样给客户端
pub fn to_result(r: Response) -> CallToolResult {
match r {
@@ -231,14 +368,100 @@ impl ServerHandler for McpServer {
_context: RequestContext<RoleServer>,
) -> Result<CallToolResponse, ErrorData> {
let args = request.arguments.unwrap_or_default();
- let resp = match to_request(&request.name, &args) {
- Err(e) => Response::error(e),
- // 守护进程正忙(例如在自动解锁)时会排队;最多等 150 秒,免得 agent 一直挂着
- Ok(req) => protocol::call(&self.socket, &req, Some(Duration::from_secs(150))).await.unwrap_or_else(|e| {
- Response::error(format!("连不上守护进程({}):{e};确认 iphone-control 容器在运行", self.socket.display()))
- }),
+ let then = match parse_then(&args) {
+ Ok(t) => t,
+ Err(e) => return Ok(to_result(Response::error(e)).into()),
+ };
+ if request.name == "iphone_batch" {
+ return Ok(self.batch(&args, then).await.into());
+ }
+ let req = match to_request(&request.name, &args) {
+ Ok(r) => r,
+ Err(e) => return Ok(to_result(Response::error(e)).into()),
+ };
+ // then 只对操作类工具有意义;看界面的工具本身就是返回界面
+ let then = if req.is_device_action() { then } else { Then::None };
+ let resp = self.call(&req).await;
+ Ok(match (resp, then) {
+ (Response::Text { text }, then) if then != Then::None => self.finish(text, false, then).await,
+ (resp, _) => to_result(resp),
+ }
+ .into())
+ }
+}
+
+impl McpServer {
+ async fn call(&self, req: &Request) -> Response {
+ // 守护进程正忙(例如在自动解锁)时会排队;最多等 150 秒,免得 agent 一直挂着
+ protocol::call(&self.socket, req, Some(Duration::from_secs(150))).await.unwrap_or_else(|e| {
+ Response::error(format!("连不上守护进程({}):{e};确认 iphone-control 容器在运行", self.socket.display()))
+ })
+ }
+
+ /// 操作完成后:按 then 等界面稳定,再附上元素列表或截图
+ async fn finish(&self, mut text: String, failed: bool, then: Then) -> CallToolResult {
+ let done = |blocks: Vec<ContentBlock>| {
+ if failed { CallToolResult::error(blocks) } else { CallToolResult::success(blocks) }
+ };
+ if then == Then::None {
+ return done(vec![ContentBlock::text(text)]);
+ }
+ match self.call(&Request::Settle { max_ms: THEN_SETTLE_MS }).await {
+ Response::Text { text: t } => text += &format!("\n{t}"),
+ Response::Error { message } => text += &format!("\n(等界面稳定失败:{message})"),
+ Response::Image { .. } => {}
+ }
+ match then {
+ Then::Elements(filter) => {
+ match self.call(&Request::ListElements { filter, limit: THEN_LIMIT }).await {
+ Response::Text { text: t } => text += &format!("\n--- 操作后的界面 ---\n{t}"),
+ Response::Error { message } => text += &format!("\n(读界面失败:{message})"),
+ Response::Image { .. } => {}
+ }
+ done(vec![ContentBlock::text(text)])
+ }
+ Then::Screenshot => match self.call(&Request::Screenshot { region: None }).await {
+ Response::Image { jpeg_base64, caption } => done(vec![
+ ContentBlock::text(text),
+ ContentBlock::image(jpeg_base64, "image/jpeg"),
+ ContentBlock::text(caption),
+ ]),
+ Response::Error { message } => done(vec![ContentBlock::text(format!("{text}\n(截图失败:{message})"))]),
+ Response::Text { text: t } => done(vec![ContentBlock::text(format!("{text}\n{t}"))]),
+ },
+ Then::None => unreachable!("上面已返回"),
+ }
+ }
+
+ /// 按顺序执行;某一步出错就停,说明是第几步、后面几步没执行。出错时也按 then 附上当前界面,方便看停在哪
+ async fn batch(&self, args: &Map<String, Value>, then: Then) -> CallToolResult {
+ let steps = match batch_steps(args) {
+ Ok(s) => s,
+ Err(e) => return to_result(Response::error(e)),
};
- Ok(to_result(resp).into())
+ let total = steps.len();
+ let mut lines = Vec::new();
+ for (i, step) in steps.into_iter().enumerate() {
+ let n = i + 1;
+ match step {
+ Step::Wait(d) => {
+ tokio::time::sleep(d).await;
+ lines.push(format!("{n}. wait → 等了 {} 秒", d.as_secs_f64()));
+ }
+ Step::Request { tool, req } => match self.call(&req).await {
+ Response::Text { text } => lines.push(format!("{n}. {tool} → {text}")),
+ Response::Image { caption, .. } => lines.push(format!("{n}. {tool} → {caption}")),
+ Response::Error { message } => {
+ lines.push(format!("{n}. {tool} → 出错:{message}"));
+ if n < total {
+ lines.push(format!("第 {n} 步出错,后面 {} 步没有执行", total - n));
+ }
+ return self.finish(lines.join("\n"), true, then).await;
+ }
+ },
+ }
+ }
+ self.finish(lines.join("\n"), false, then).await
}
}
@@ -258,13 +481,13 @@ mod tests {
}
#[test]
- fn thirteen_tools_with_toolkit_names() {
+ fn toolkit_tools_plus_wait_for_and_batch() {
let names: Vec<_> = tools().iter().map(|t| t.name.to_string()).collect();
- assert_eq!(names.len(), 13);
+ assert_eq!(names.len(), 15);
for n in ["iphone_status", "iphone_screenshot", "iphone_tap_element", "iphone_open_url"] {
assert!(names.contains(&n.to_owned()), "{n}");
}
- for t in tools() {
+ for t in tools().into_iter().filter(|t| t.name != "iphone_batch") {
let no_required = t.input_schema.get("required").unwrap().as_array().unwrap().is_empty();
assert_eq!(to_request(&t.name, &Map::new()).is_ok(), no_required, "{}", t.name);
}
@@ -290,6 +513,77 @@ mod tests {
);
}
+ #[test]
+ fn then_is_offered_on_actions_only() {
+ let has_then = |name: &str| {
+ let t = tools().into_iter().find(|t| t.name == name).unwrap();
+ t.input_schema["properties"].get("then").is_some()
+ };
+ for n in [
+ "iphone_tap",
+ "iphone_tap_element",
+ "iphone_swipe",
+ "iphone_type_text",
+ "iphone_launch_app",
+ "iphone_batch",
+ ] {
+ assert!(has_then(n), "{n}");
+ }
+ for n in ["iphone_status", "iphone_screenshot", "iphone_list_elements", "iphone_wait_for"] {
+ assert!(!has_then(n), "{n}");
+ }
+ assert_eq!(parse_then(&Map::new()).unwrap(), Then::None);
+ assert_eq!(
+ parse_then(&args(json!({"then": "elements", "then_filter": "设置"}))).unwrap(),
+ Then::Elements("设置".into())
+ );
+ assert_eq!(parse_then(&args(json!({"then": "screenshot"}))).unwrap(), Then::Screenshot);
+ assert!(parse_then(&args(json!({"then": "video"}))).is_err());
+ }
+
+ #[test]
+ fn batch_steps_are_checked_before_anything_runs() {
+ let steps = batch_steps(&args(json!({"steps": [
+ {"tool": "iphone_tap_element", "text": "One"},
+ {"tool": "wait", "seconds": 0.5},
+ {"tool": "iphone_tap", "x": 1, "y": 2},
+ {"tool": "iphone_wait_for", "text": "完成", "timeout": 3}
+ ]})))
+ .unwrap();
+ assert_eq!(steps.len(), 4);
+ assert_eq!(steps[1], Step::Wait(std::time::Duration::from_millis(500)));
+ assert_eq!(
+ steps[3],
+ Step::Request {
+ tool: "iphone_wait_for".into(),
+ req: Request::WaitFor { text: "完成".into(), timeout_ms: 3000 }
+ }
+ );
+ // 第 2 步参数错:一步都不执行,报出是第几步
+ let e = batch_steps(&args(
+ json!({"steps": [{"tool": "iphone_tap", "x": 1, "y": 2}, {"tool": "iphone_tap", "x": 1}]}),
+ ))
+ .unwrap_err();
+ assert!(e.contains("第 2 步"), "{e}");
+ // 看界面的工具、未知工具、批量套批量都不行
+ for bad in ["iphone_screenshot", "iphone_batch", "rm"] {
+ assert!(batch_steps(&args(json!({"steps": [{"tool": bad}]}))).is_err(), "{bad}");
+ }
+ assert!(batch_steps(&args(json!({"steps": [{"tool": "wait", "seconds": 9}]}))).is_err());
+ assert!(batch_steps(&args(json!({"steps": []}))).is_err());
+ let many: Vec<Value> = (0..21).map(|_| json!({"tool": "wait", "seconds": 0})).collect();
+ assert!(batch_steps(&args(json!({"steps": many}))).is_err());
+ }
+
+ #[test]
+ fn wait_for_timeout_is_bounded() {
+ assert_eq!(
+ to_request("iphone_wait_for", &args(json!({"text": "x"}))).unwrap(),
+ Request::WaitFor { text: "x".into(), timeout_ms: 5000 }
+ );
+ assert!(to_request("iphone_wait_for", &args(json!({"text": "x", "timeout": 60}))).is_err());
+ }
+
#[test]
fn wrong_typed_parameters_are_errors_not_defaults() {
let args = |v: Value| v.as_object().unwrap().clone();
diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rs
index ca39854..576e0f3 100644
--- a/crates/ictl-protocol/src/lib.rs
+++ b/crates/ictl-protocol/src/lib.rs
@@ -55,6 +55,15 @@ pub enum Request {
OpenUrl {
url: String,
},
+ /// 等界面稳定:连续两次读到的元素一样,最多等 `max_ms`。操作后顺带返回界面时先调它
+ Settle {
+ max_ms: u64,
+ },
+ /// 等包含 `text` 的元素出现,最多等 `timeout_ms`(代替 agent 反复截图轮询)
+ WaitFor {
+ text: String,
+ timeout_ms: u64,
+ },
/// 运维:守护进程和设备的状态快照(JSON 文本)
Daemon,
/// 运维:逐层诊断,返回多行文字
diff --git a/docs/architecture.md b/docs/architecture.md
index c252d8f..53d5b25 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -106,7 +106,7 @@
| `ictl-sign` | Apple ID 登录(含双重认证交互)、会话持久化、注册设备、App ID、描述文件、签名 `.app`/`.ipa`(**包括 `.xctest`**;bundle 逻辑改写自 plume_utils)、签后自检 | vendored 的 `plume_core`/`plume_store`(MPL-2.0/MIT;经 plume_core 用 vendored 的 `omnisette` 和打过补丁的 `apple-codesign`) |
| `ictl-unlock` | 锁屏密码键盘定位、逐位输入并核对密码栏、从第 2 位起先写停用标记 | `ictl-wda` |
| `ictl-daemon` | `core`(共享状态、请求分发、快照)、`supervise`(巡检、usbmuxd 看护、后台启动 WDA、重签、会话检查)、`tools`(13 个工具的实现、HID 后备)、`doctor`;通知(Bark/Telegram)、截图缩放/裁剪、控制接口服务端 | 以上全部、`tokio`、`reqwest`、`image` |
-| `ictl-mcp` | MCP stdio 服务,13 个 `iphone_*` 工具,经控制接口调用守护进程 | `ictl-protocol`、`rmcp`(`server`、`transport-io`) |
+| `ictl-mcp` | MCP stdio 服务,toolkit 的 13 个 `iphone_*` 工具 + `iphone_wait_for`、`iphone_batch`;操作类工具可带 `then` 顺带返回操作后的界面;经控制接口调用守护进程 | `ictl-protocol`、`rmcp`(`server`、`transport-io`) |
| `apps/iphone-control` | CLI 入口:`daemon`、`mcp`、`mcp-config`、`status`、`doctor`、`setup`、`login`、`sign`、`resign`、`passcode`、`unlock-reset`、`wda-bridge`、`notify-test`;隐藏的 `debug <ddi\|hid\|screenshot\|soak\|wda\|e2e>` 真机诊断(原第 0 步 spike,不经守护进程) | `clap` |
依赖方向:`apps` → `ictl-daemon` / `ictl-mcp`;`ictl-daemon` → `ictl-unlock` → `ictl-wda` → `ictl-device`;`ictl-daemon` 还依赖 `ictl-sign` 和 `ictl-protocol`。`ictl-mcp` 只依赖 `ictl-protocol`,不依赖守护进程和设备层。`apps` 的 `debug` 直接调用 `ictl-device`、`ictl-wda`。
diff --git a/docs/capability-matrix.md b/docs/capability-matrix.md
index 731d34c..0092bb2 100644
--- a/docs/capability-matrix.md
+++ b/docs/capability-matrix.md
@@ -23,7 +23,7 @@
| 安装 IPA | `ios install` | `installation_proxy::install`(需先 AFC 上传)或 `installcoordination_proxy` | 已有 | — |
| 列出 App(过滤 hidden 系统服务) | `ios apps --system` + 过滤 `SBAppTags` 含 `hidden` | `installation_proxy::get_apps`(取 `SBAppTags`) | 已有 + 需自写(过滤) | 必须保留 hidden 过滤,否则「设置」会匹配到 5 个后台服务 |
-## 2. 13 个 MCP 工具
+## 2. MCP 工具(toolkit 的 13 个 + 2 个扩展)
| 工具 | toolkit 现在靠 | D 方案实现 | 状态 | 风险 / 待验证 |
|---|---|---|---|---|
@@ -40,6 +40,9 @@
| `iphone_launch_app` | WDA `/wda/apps/launch` + 等前台 1 秒 | WDA `launch_app` + 轮询 activeAppInfo;退回 `core_device::app_service::launch_application` | 已有 + 需自写(等前台) | 冷启动立即点击会被吞,必须保留等待 |
| `iphone_terminate_app` | WDA `/wda/apps/terminate` | WDA `terminate_app` | 已有 | — |
| `iphone_open_url` | WDA `/url` | WDA 会话 `/url`(idevice 未封装,自己发) | 需自写 | — |
+| `iphone_wait_for`(新增) | 无 | 守护进程轮询元素树,出现即返回 | 已实现 | 只认元素树里的文字,游戏等没有元素的界面要截图 |
+| `iphone_batch`(新增) | 无 | MCP 层按顺序调用守护进程,出错即停;步骤先全部校验再执行 | 已实现 | 步骤间不看界面,只适合结果确定的连续操作 |
+| 操作类工具的 `then` 参数(新增) | 无 | 操作后 `Settle`(连续两次元素树一样,最多 1.5 秒),再附元素列表或截图 | 已实现 | 每次多 0.5~1.3 秒等稳定,换一次往返 |
## 3. 后台能力
diff --git a/docs/decisions.md b/docs/decisions.md
index 6f89258..38e5fa3 100644
--- a/docs/decisions.md
+++ b/docs/decisions.md
@@ -59,3 +59,6 @@
- **决定**:13 个 MCP 工具名、参数、返回文本格式保持与 toolkit 一致。
- **理由**:切换时 agent 侧零改动;toolkit 的回归脚本可直接用于验收。
+- **补充(2026-11-01)**:只做向后兼容的扩展,不改已有工具的名字、参数和默认返回。为减少 agent 往返(每次往返是一轮模型推理,
+ 真机观察约 8~13 秒,远大于工具本身的 0.3~1.5 秒),操作类工具加可选参数 `then`(`elements` / `screenshot`:等界面稳定后
+ 顺带返回界面),并新增 `iphone_wait_for`(等某段文字出现)和 `iphone_batch`(一次执行最多 20 步,出错即停)。
diff --git a/docs/roadmap.md b/docs/roadmap.md
index d8a354b..1382c67 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -11,7 +11,7 @@
| 0 spike | ✅ 5 项全过:TSS/挂载、HID Home 键、截图、30 分钟隧道、WDA 启动与读回 | 手机重启后补跑正式 `debug ddi` 挂载;HID 点击/drag/键盘;隧道锁屏 |
| 1 设备核心库 | usbmux 发现、sysfs 兜底、配对、开发者模式、CoreDeviceProxy 用户态隧道 + RSD、cryptexd 查询/挂载、DDI 下载缓存、截图、HID(持有媒体流)、列 App/安装;WDA 直连设备端口的 HTTP 客户端、会话自动重建、元素树解析、XCTest 启动 runner。完成标准的示例程序 `iphone-control debug e2e`(原 `ictl-spike e2e`)已在真机通过(9.8 秒;WDA 和 HID 两条路线的点击与 Home 都以前台 App 变化确认生效)。自己签的 WDA 已在真机安装,守护进程拉起后 10 秒就绪,e2e 同样通过 | 500KB 元素树经 jktcp 读回。(「Enable UI Automation」已确认:超时报 `Timed out while enabling automation mode.`,锁屏时报 `com.apple.LocalAuthentication Code=-4`;idevice 解码不了这条错误,从 runner 调试日志识别) |
| 2 守护进程 | 状态机、usbmuxd 子进程看护、WDA 就绪判定与退避、密码框 60 秒重试、控制 socket、事件日志轮转、state.json。正式容器真机已过:冷启动 10~12 秒;杀 usbmuxd 约 11 秒恢复;拔插 USB 约 40~50 秒恢复(sysfs 兜底重启 usbmuxd);手机重启 → 61 秒内进入「需要输入密码」并通知 → 输密码后 10 秒就绪 | 24 小时内存(2026-11-01 13:13 开始采样);拔插恢复可再省 10 秒(重启 usbmuxd 后当轮重新列设备);iOS 27 上开发者镜像重启后仍在,从未挂载开始的挂载流程没测到 |
-| 3 MCP | 13 个工具,参数与返回文字对齐 toolkit;区域放大;HID 后备。toolkit 的回归脚本 `tests/device/client.py` 原样跑通(13 步,截图确认生效)。Claude Code 已切到本项目 MCP:元素场景(设置 › 显示与亮度 › 自动锁定 改 5 分钟再改回)和纯坐标场景(开心消消乐 392 关,16 步通关 3 星)都完成 | 无(锁屏误判已修,见回归用例 #20、#21) |
+| 3 MCP | 13 个工具,参数与返回文字对齐 toolkit;另加 `then` 参数、`iphone_wait_for`、`iphone_batch` 减少往返(真机:计算器 12×34 往返 10→2 次、设置逐级进入 6→1、Safari 打开网页 3→1,工具耗时基本不变);区域放大;HID 后备。toolkit 的回归脚本 `tests/device/client.py` 原样跑通(13 步,截图确认生效)。Claude Code 已切到本项目 MCP:元素场景(设置 › 显示与亮度 › 自动锁定 改 5 分钟再改回)和纯坐标场景(开心消消乐 392 关,16 步通关 3 星)都完成 | 无(锁屏误判已修,见回归用例 #20、#21) |
| 4 签名与重签 | vendor plume_core/plume_store/omnisette/apple-codesign(plume_utils 未 vendor,bundle 逻辑改写进 `ictl-sign`);登录(2FA、短信)、注册设备、App ID、描述文件、深度优先签名(XCTest 无 entitlements)、签后自检、定期重签(每 6 小时检查)、每日会话验证。真机已验证:登录(2FA)→ 签名 → 安装 → WDA 启动(XCTest 不带 entitlements 可以) | 强制重签后 WDA 自动恢复;会话失效通知;修复提交 Impactor 上游未做 |
| 5 通知 | Bark、Telegram,事件去重(重签/会话失效 20 小时冷却);`iphone-control notify-test` 每类事件各发一条。Bark 实测 7 类全部收到;守护进程实际触发的「需要输入密码」「已恢复」也已在手机重启测试中走通 | Telegram 未实测(没有配置) |
| 6 自动解锁 | 规则全部实现,用假锁屏验证(键盘常驻树中、首位不生效重来、中间位被吞即停、输错一次即停用、残留输入用删除键清)。真机 6 种场景各 5 次全部成功、全程无输错:锁屏后 0 秒 15.3~16.0 秒(含有意等的 3 秒)、3/30/70 秒约 12.3 秒、键盘留 2 位残留 13.8~14.6 秒、自然自动锁屏(30 秒)11.8~12.4 秒;配置错误密码只输错一次即停用并推送,恢复密码 + unlock-reset 后正常 | 无 |