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

feat(mcp): opt-in developer tools for logs, crash reports and installs (#35)

TheSalaty6c85fd4f6aa2
diff --git a/.env.example b/.env.example
index 3ed157f..7192fd9 100644
--- a/.env.example
+++ b/.env.example
@@ -13,6 +13,10 @@ DATA_DIR=./data
# 容器部署时也管 docker exec 起的 MCP 和命令行。
IPHONE_CONTROL_LANG=
+# 开发者工具:设为 1 时 MCP 服务多出日志、崩溃报告、安装和卸载 App 四个工具(默认关闭,免得 agent 多读工具说明)
+# Developer tools: 1 adds four MCP tools for logs, crash reports, installing and removing apps (off by default).
+IPHONE_CONTROL_DEV_TOOLS=
+
# 固定控制哪台设备,设了就不能切换。留空为自动选:正在控制的那台一直用到它断开;
# 运行中可以用 `iphone-control select` 或 iphone_select_device 工具切换
IPHONE_UDID=
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b244a27..3fe5cb3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@ All notable changes to this project are documented here. The format is based on
- The MCP server and the CLI send their language with each request and the daemon answers in it; requests from older clients carry none and get Chinese as before, so mixed versions during an upgrade keep working. `mcp-config` includes the setting when English is on.
- Text responses carry an optional `outcome` (`tapped_nothing`, `alert_reported`), so the MCP server no longer reads result text to stop a batch after a missed tap or to skip the extra alert check. Responses without it (older daemons) are still recognised by their Chinese prefixes.
- `iphone-control viewer [--port]`: watch and control the phone live in a browser (opt-in, 127.0.0.1:8200 by default). Taps, swipes, long presses, typing and buttons go through the daemon, so they queue with the agent's calls and unlock the phone first. It binds the loopback address only, checks `Host`, and also checks `Origin` on actions; other local users can reach the port, so stop it when done.
+- Developer tools, opt-in with `IPHONE_CONTROL_DEV_TOOLS=1`: `iphone_app_logs` (the phone's unified log, filtered by app or process, text and time), `iphone_crash_reports`, `iphone_install_app` and `iphone_uninstall_app` (both marked destructive; uninstalling the WebDriverAgent runner is refused). Without the switch the tool list is unchanged.
### Fixed
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index 82d6268..2c328fd 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -12,6 +12,7 @@
- MCP 和命令行在每个请求里带上自己的语言,守护进程按它回答;旧版本客户端的请求不带语言,照旧用中文,升级过程中新旧版本混用也不受影响。开着英文时 `mcp-config` 会把这个设置带上。
- 文字响应带可选的 `outcome`(`tapped_nothing`、`alert_reported`),MCP 端据此在没点到时停下批量、跳过多余的弹窗检查,不再从结果文字里认;没有这个字段的响应(旧版本守护进程)照旧按中文开头认。
- `iphone-control viewer [--port]`:在浏览器里看实时画面并操作手机(默认 127.0.0.1:8200,显式开启)。点击、滑动、长按、输入和按键都经守护进程,和 agent 的调用排队,并先自动解锁。只绑本机回环地址,检查 `Host`,操作还检查 `Origin`;本机其他用户能连上这个端口,用完就停。
+- 开发者工具,设 `IPHONE_CONTROL_DEV_TOOLS=1` 开启:`iphone_app_logs`(手机的系统日志,可按 App 或进程、文字、时间筛选)、`iphone_crash_reports`、`iphone_install_app` 和 `iphone_uninstall_app`(后两个标为破坏性操作;拒绝卸载 WebDriverAgent)。不设就和原来一样,工具列表不变。
### 修复
diff --git a/Cargo.lock b/Cargo.lock
index ff3d699..8785186 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2151,6 +2151,7 @@ dependencies = [
"async-stream",
"async_zip",
"base64 0.22.1",
+ "bytes",
"chrono",
"flate2",
"futures",
diff --git a/Cargo.toml b/Cargo.toml
index 256183c..17fe561 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -44,6 +44,9 @@ idevice = { version = "=0.1.68", default-features = false, features = [
"installation_proxy",
"misagent",
"xctest",
+ # developer tools (IPHONE_CONTROL_DEV_TOOLS): os_trace logs, crash reports
+ "syslog_relay",
+ "crashreportcopymobile",
] }
rmcp = { version = "=3.8.0", features = ["server", "transport-io"] }
tokio = { version = "=1.54.1", features = ["full"] }
diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md
index b9c717c..f02d429 100644
--- a/THIRD_PARTY.md
+++ b/THIRD_PARTY.md
@@ -13,6 +13,7 @@
| Impactor `omnisette` | 同上 | MPL-2.0 | `vendor/omnisette` | `src/lib.rs` 加了 `anisette_url_v3()`/`set_anisette_url_v3()`(原来 v3 地址没有 setter,自建 anisette 服务配不进去;改动处有注释,文件仍是 MPL-2.0);Cargo.toml 展开 workspace 继承;reqwest 用 `rustls-no-provider`;本地 anisette(StoreServicesCore,要苹果 Android 版的 `libstoreservicescore.so` 和没有许可证声明的 git 依赖 `android-loader`)改成可选 feature `local-anisette`,默认 feature 里保留与上游一致,本项目不启用(只用远程 anisette v3) |
| Impactor `plume_utils` | 同上 | MIT | 未 vendor;`crates/ictl-sign/src/bundle.rs` 改写自其 `bundle.rs` | 增加 `BundleType::XCTest`,修复 `.xctest` 漏签 |
| idevice tools | v0.1.68 | MIT | `crates/ictl-device/src/media.rs`、`hid.rs` 的按键/键码表改写自 `tools/src/coredevice_stream.rs`、`hid.rs` | 去掉日志、改错误类型 |
+| idevice os_trace_relay | 上游 master `89702099` | MIT | `crates/ictl-device/src/oslog.rs` 的日志条目格式取自 `idevice/src/services/os_trace_relay.rs` | 请求里去掉 Debug 位,解析加越界检查 |
| [WebDriverAgent](https://github.com/appium/WebDriverAgent) | v16.15.3(Appium 官方构建,sha256 2176793538d9…) | BSD-3-Clause | 镜像构建时下载校验,打成未签名 IPA;计划改为本项目 macOS CI 编译 | 不嵌入苹果框架 |
| [usbmuxd](https://github.com/libimobiledevice/usbmuxd) | Debian 包 | GPL-3.0 | 独立进程,不链接 | 无 |
diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rs
index 6eed17a..b0538e2 100644
--- a/apps/iphone-control/src/main.rs
+++ b/apps/iphone-control/src/main.rs
@@ -217,14 +217,19 @@ fn mcp_config(container: Option<String>, socket: &Path) -> anyhow::Result<String
// 英文时把语言写进注册命令:直接调用时 MCP 客户端不带用户 shell 的环境;容器里一般由 .env 继承,
// 但只给这一次 docker exec 设了语言(.env 里没有)时,不写进去 MCP 就还是中文
let lang = |flag: &str| if ictl_l10n::is_en() { format!("{flag} {}=en ", ictl_l10n::ENV) } else { String::new() };
+ let dev = || if ictl_mcp::dev_tools_enabled() { "-e IPHONE_CONTROL_DEV_TOOLS=1 " } else { "" };
Ok(match container {
- Some(c) => format!("claude mcp add iphone -s user -- docker exec -i {}{c} iphone-control mcp", lang("-e")),
+ // 开发者工具开关同理:只给这次 docker exec 设了、.env 里没有时也要写进去
+ Some(c) => {
+ format!("claude mcp add iphone -s user -- docker exec -i {}{}{c} iphone-control mcp", lang("-e"), dev())
+ }
None => {
let exe = std::env::current_exe()
.context(ictl_l10n::tr!("找不到本程序的路径", "can't find the path of this program"))?;
let lang = lang("-e");
+ let dev = dev();
format!(
- "claude mcp add iphone -s user {lang}-- {} --socket {} mcp",
+ "claude mcp add iphone -s user {lang}{dev}-- {} --socket {} mcp",
shell_quote(&exe.to_string_lossy()),
shell_quote(&socket.to_string_lossy())
)
diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs
index 3b2c41e..bd9dd56 100644
--- a/crates/ictl-daemon/src/core.rs
+++ b/crates/ictl-daemon/src/core.rs
@@ -242,6 +242,8 @@ pub(crate) struct Inner {
pub next_resign: Instant,
pub next_session_check: Instant,
pub apps: HashMap<bool, Vec<AppInfo>>,
+ /// Log capture for `AppLogs` (developer tools), started by the first request
+ pub log_capture: Option<crate::devtools::Capture>,
}
pub struct Daemon {
@@ -347,6 +349,7 @@ impl Daemon {
next_resign: now + Duration::from_secs(60),
next_session_check: now + Duration::from_secs(90),
apps: HashMap::new(),
+ log_capture: None,
};
let first = Snapshot {
state: DeviceState::Absent,
@@ -537,6 +540,10 @@ impl Daemon {
Request::Resign { force } => {
return self.resign_now(force).await.map(Response::text).unwrap_or_else(Response::error);
}
+ // an install can take minutes; it doesn't hold the lock meanwhile
+ Request::InstallApp { path } => {
+ return self.install_app(&path).await.map(Response::text).unwrap_or_else(Response::error);
+ }
_ => {}
}
if let Err(e) = check_request(&req) {
@@ -622,7 +629,12 @@ impl Daemon {
}
Request::ListDevices => Ok(self.list_devices_text(g)),
Request::SelectDevice { device } => self.select_device(g, &device).await,
- Request::Daemon | Request::Resign { .. } => unreachable!("上面已处理"),
+ Request::AppLogs { process, grep, since_secs, limit, errors_only } => {
+ self.app_logs(g, &process, &grep, Duration::from_secs(since_secs), limit, errors_only).await
+ }
+ Request::CrashReports { filter, name } => self.crash_reports(g, &filter, &name).await,
+ Request::UninstallApp { app } => self.uninstall_app(g, &app).await,
+ Request::Daemon | Request::Resign { .. } | Request::InstallApp { .. } => unreachable!("上面已处理"),
};
if invalidates {
g.elements_cache = None;
@@ -658,6 +670,13 @@ fn check_request(req: &Request) -> Result<(), String> {
Request::WaitFor { text, .. } if text.is_empty() => {
return Err(ictl_l10n::tr!("text 不能为空", "text can't be empty").into());
}
+ Request::AppLogs { since_secs, limit, .. } if *since_secs > 3600 || *limit == 0 || *limit > 1000 => {
+ return Err(ictl_l10n::tr!(
+ "since 最多 3600 秒,limit 要在 1 到 1000 之间",
+ "since can be at most 3600 seconds, and limit must be between 1 and 1000"
+ )
+ .into());
+ }
_ => {}
}
let seconds = match req {
diff --git a/crates/ictl-daemon/src/devtools.rs b/crates/ictl-daemon/src/devtools.rs
new file mode 100644
index 0000000..ec3b484
--- /dev/null
+++ b/crates/ictl-daemon/src/devtools.rs
@@ -0,0 +1,417 @@
+//! Developer tools (`IPHONE_CONTROL_DEV_TOOLS`): the phone's logs, crash reports, installing and removing apps.
+//!
+//! The MCP server only lists these tools when the switch is on; the daemon always understands the requests.
+//!
+//! Logs come from os_trace_relay. It only streams what happens from now on, so the first `AppLogs` request
+//! starts a capture into a ring buffer (at most [`MAX_LINES`]); later requests read from it, which is what makes
+//! `since` work. The capture follows the controlled device: it stops when the daemon switches to another device or
+//! the device goes offline, and by itself after [`IDLE`] without a request, so a session that used the tool once
+//! doesn't keep a log stream running.
+//!
+//! The stream leaves out debug and info messages (see `ictl_device::Device::log_stream`: asking for them slows the
+//! phone). It is still every process, tens of lines a second, so the buffer is bounded by size as well as by count
+//! ([`MAX_BYTES`]): messages are cut to
+//! [`MAX_LINE_CHARS`] and processes kept by name only when they arrive. How far back it reaches depends on how busy
+//! the phone is, so every answer says so.
+
+use std::collections::VecDeque;
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use ictl_device::{LogEntry, LogLevel};
+use tokio::task::JoinHandle;
+
+use crate::core::{Daemon, Inner};
+
+const MAX_LINES: usize = 20_000;
+/// Text kept in the buffer (messages, process names, subsystems); the oldest lines go first
+const MAX_BYTES: usize = 8 * 1024 * 1024;
+const IDLE: Duration = Duration::from_secs(15 * 60);
+/// Longest crash report text returned; the start holds the exception, the crashed thread and the app version
+const MAX_REPORT_CHARS: usize = 40_000;
+const MAX_LINE_CHARS: usize = 600;
+
+pub(crate) struct Capture {
+ udid: String,
+ started: Instant,
+ buf: Arc<Mutex<Buffer>>,
+ last_query: Arc<Mutex<Instant>>,
+ task: JoinHandle<()>,
+}
+
+impl Drop for Capture {
+ fn drop(&mut self) {
+ self.task.abort();
+ }
+}
+
+impl Daemon {
+ pub(crate) async fn app_logs(
+ &self,
+ g: &mut Inner,
+ process: &str,
+ grep: &str,
+ since: Duration,
+ limit: usize,
+ errors_only: bool,
+ ) -> Result<String, String> {
+ let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;
+ let running = g.log_capture.as_ref().is_some_and(|c| c.udid == device.udid && !c.task.is_finished());
+ if !running {
+ let mut stream = device.log_stream().await.map_err(|e| e.to_string())?;
+ let buf = Arc::new(Mutex::new(Buffer::default()));
+ let last_query = Arc::new(Mutex::new(Instant::now()));
+ let (b, q) = (buf.clone(), last_query.clone());
+ let task = tokio::spawn(async move {
+ let mut check = tokio::time::interval(Duration::from_secs(30));
+ loop {
+ tokio::select! {
+ e = stream.next() => {
+ let Ok(e) = e else { return };
+ b.lock().unwrap_or_else(|p| p.into_inner()).push(Instant::now(), compact(e));
+ }
+ _ = check.tick() => {
+ if q.lock().unwrap_or_else(|p| p.into_inner()).elapsed() > IDLE {
+ return;
+ }
+ }
+ }
+ }
+ });
+ g.log_capture = Some(Capture { udid: device.udid.clone(), started: Instant::now(), buf, last_query, task });
+ }
+ let c = g.log_capture.as_ref().expect("set above");
+ *c.last_query.lock().unwrap_or_else(|p| p.into_inner()) = Instant::now();
+
+ // an app's name or bundle ID → the process it runs as; anything else is taken as a process name
+ let wanted = if process.is_empty() { None } else { Some(self.process_name(g, process).await) };
+ let c = g.log_capture.as_ref().expect("set above");
+ let filter = LogFilter { process: wanted.as_deref(), grep, errors_only };
+ let from = Instant::now().checked_sub(since);
+ let (lines, oldest) = {
+ let b = c.buf.lock().unwrap_or_else(|p| p.into_inner());
+ let mut hits: Vec<String> = b
+ .lines
+ .iter()
+ .rev()
+ .filter(|(t, _)| from.is_none_or(|f| *t >= f))
+ .filter(|(_, e)| filter.matches(e))
+ .take(limit)
+ .map(|(t, e)| format_line(t.elapsed(), e))
+ .collect();
+ hits.reverse();
+ (hits, b.lines.front().map(|(t, _)| t.elapsed().as_secs()))
+ };
+ let mut out = if running {
+ ictl_l10n::trf!(
+ "最近 {} 秒内 {} 行匹配(日志从 {} 秒前开始记录):",
+ "In the last {} s, {} lines match (capture running for {} s):",
+ since.as_secs(),
+ lines.len(),
+ c.started.elapsed().as_secs()
+ )
+ } else {
+ ictl_l10n::tr!(
+ "刚开始记录日志,这次调用之前的日志拿不到。复现问题后再调一次。",
+ "Log capture started just now; lines from before this call aren't available. Reproduce the problem, then call again."
+ )
+ .to_owned()
+ };
+ if running && lines.is_empty() {
+ out += ictl_l10n::tr!(" 没有。", " none.");
+ }
+ // the buffer may reach back less far than `since`: say how far, so a missing line isn't taken as "didn't happen"
+ if running && let Some(o) = oldest.filter(|o| *o < since.as_secs()) {
+ out += &ictl_l10n::trf!(
+ "\n(缓冲里最早一行是 {o} 秒前,更早的已经挤出去了)",
+ "\n(the oldest line in the buffer is from {o} s ago; earlier lines have been dropped)"
+ );
+ }
+ for l in lines {
+ out.push('\n');
+ out += &l;
+ }
+ Ok(out)
+ }
+
+ /// The executable name of an installed app given by name or bundle ID, or `process` itself
+ async fn process_name(&self, g: &mut Inner, process: &str) -> String {
+ for system in [false, true] {
+ if let Ok(apps) = self.list_apps(g, system).await
+ && let Some(a) = apps.iter().find(|a| a.bundle_id == process || a.name == process)
+ && !a.executable.is_empty()
+ {
+ return a.executable.clone();
+ }
+ }
+ process.to_owned()
+ }
+
+ pub(crate) async fn crash_reports(&self, g: &mut Inner, filter: &str, name: &str) -> Result<String, String> {
+ let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;
+ if !name.is_empty() {
+ if name.contains('/') || name.contains("..") {
+ return Err(ictl_l10n::tr!(
+ "name 要是 iphone_crash_reports 列出的文件名",
+ "name must be a file name listed by iphone_crash_reports"
+ )
+ .into());
+ }
+ let data = device.crash_report(name).await.map_err(|e| e.to_string())?;
+ let text = String::from_utf8_lossy(&data);
+ let n = text.chars().count();
+ if n <= MAX_REPORT_CHARS {
+ return Ok(text.into_owned());
+ }
+ let head: String = text.chars().take(MAX_REPORT_CHARS).collect();
+ return Ok(head
+ + &ictl_l10n::trf!(
+ "\n…(共 {n} 个字符,只返回前 {MAX_REPORT_CHARS} 个)",
+ "\n… ({n} characters in total, only the first {MAX_REPORT_CHARS} returned)"
+ ));
+ }
+ let names = device.crash_reports().await.map_err(|e| e.to_string())?;
+ let list = crash_list(names, filter);
+ if list.is_empty() {
+ return Ok(if filter.is_empty() {
+ ictl_l10n::tr!("没有崩溃报告", "No crash reports").into()
+ } else {
+ ictl_l10n::trf!("没有包含「{filter}」的崩溃报告", "No crash reports containing “{filter}”")
+ });
+ }
+ Ok(ictl_l10n::tr!(
+ "崩溃报告(新的在前;用 name 取其中一份的内容):\n",
+ "Crash reports (newest first; pass one as name to read it):\n"
+ )
+ .to_owned()
+ + &list.join("\n"))
+ }
+
+ /// Runs without holding the daemon lock (an install can take minutes), like re-signing
+ pub(crate) async fn install_app(&self, path: &str) -> Result<String, String> {
+ let device =
+ self.inner.lock().await.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;
+ let p = std::path::Path::new(path);
+ if !p.exists() {
+ return Err(ictl_l10n::trf!(
+ "找不到 {path}(路径要在运行守护进程的机器上,容器部署时是容器里的路径)",
+ "{path} not found (the path is on the machine that runs the daemon; inside the container for a container deployment)"
+ ));
+ }
+ device.install(p).await.map_err(|e| e.to_string())?;
+ self.inner.lock().await.apps.clear();
+ Ok(ictl_l10n::trf!("已安装 {path}", "Installed {path}"))
+ }
+
+ pub(crate) async fn uninstall_app(&self, g: &mut Inner, app: &str) -> Result<String, String> {
+ let bid = self.resolve_app(g, app).await?;
+ if is_wda_runner(&bid, g.persisted.wda_bundle.as_deref()) {
+ return Err(ictl_l10n::trf!(
+ "{bid} 是 WebDriverAgent,iphone-control 靠它控制手机,不能卸载",
+ "{bid} is WebDriverAgent, which iphone-control needs to control the phone; it can't be uninstalled"
+ ));
+ }
+ let device = g.device.clone().ok_or(ictl_l10n::tr!("手机未连接", "Phone not connected"))?;
+ device.uninstall(&bid).await.map_err(|e| e.to_string())?;
+ g.apps.clear();
+ Ok(ictl_l10n::trf!("已卸载 {bid}", "Uninstalled {bid}"))
+ }
+}
+
+/// The captured lines, bounded by [`MAX_LINES`] and [`MAX_BYTES`]
+#[derive(Default)]
+pub(crate) struct Buffer {
+ lines: VecDeque<(Instant, LogEntry)>,
+ bytes: usize,
+}
+
+impl Buffer {
+ fn push(&mut self, at: Instant, e: LogEntry) {
+ self.bytes += size(&e);
+ self.lines.push_back((at, e));
+ while self.lines.len() > MAX_LINES || self.bytes > MAX_BYTES {
+ let Some((_, old)) = self.lines.pop_front() else { break };
+ self.bytes -= size(&old);
+ }
+ }
+}
+
+fn size(e: &LogEntry) -> usize {
+ e.process.len() + e.message.len() + e.subsystem.as_ref().map_or(0, String::len)
+}
+
+/// What the buffer keeps of an entry: the process by name (the filter and the output only use the name) and the
+/// message cut to [`MAX_LINE_CHARS`] (marked with `…`)
+fn compact(mut e: LogEntry) -> LogEntry {
+ if let Some(name) = e.process.rsplit('/').next()
+ && name.len() < e.process.len()
+ {
+ e.process = name.to_owned();
+ }
+ if let Some((i, _)) = e.message.char_indices().nth(MAX_LINE_CHARS) {
+ e.message.truncate(i);
+ e.message.push('…');
+ }
+ e.message.shrink_to_fit();
+ e
+}
+
+/// The WDA runner this daemon signed, or any other WebDriverAgent build
+fn is_wda_runner(bid: &str, signed: Option<&str>) -> bool {
+ signed.is_some_and(|s| s.eq_ignore_ascii_case(bid)) || bid.to_ascii_lowercase().contains("webdriveragentrunner")
+}
+
+struct LogFilter<'a> {
+ /// executable name, matched against the last path component, ignoring case
+ process: Option<&'a str>,
+ grep: &'a str,
+ errors_only: bool,
+}
+
+impl LogFilter<'_> {
+ fn matches(&self, e: &LogEntry) -> bool {
+ if self.errors_only && !matches!(e.level, LogLevel::Error | LogLevel::Fault) {
+ return false;
+ }
+ if let Some(p) = self.process {
+ let name = e.process.rsplit('/').next().unwrap_or_default();
+ if !name.eq_ignore_ascii_case(p) {
+ return false;
+ }
+ }
+ if !self.grep.is_empty() {
+ let g = self.grep.to_lowercase();
+ let sub = e.subsystem.as_deref().unwrap_or_default();
+ if !e.message.to_lowercase().contains(&g) && !sub.to_lowercase().contains(&g) {
+ return false;
+ }
+ }
+ true
+ }
+}
+
+/// `-12.3s Process[pid] <Error> subsystem:category message`, the message cut to [`MAX_LINE_CHARS`]
+fn format_line(age: Duration, e: &LogEntry) -> String {
+ let name = e.process.rsplit('/').next().unwrap_or_default();
+ let level = match e.level {
+ LogLevel::Debug => "<Debug> ",
+ LogLevel::Info => "<Info> ",
+ LogLevel::Notice => "",
+ LogLevel::Error => "<Error> ",
+ LogLevel::Fault => "<Fault> ",
+ };
+ let sub = e.subsystem.as_deref().map(|s| format!("{s} ")).unwrap_or_default();
+ // already cut when stored (`compact`); cut again for entries that didn't go through it
+ let mut msg: String = e.message.chars().take(MAX_LINE_CHARS).collect();
+ if msg.len() < e.message.len() {
+ msg.push('…');
+ }
+ format!("-{:.1}s {name}[{}] {level}{sub}{}", age.as_secs_f64(), e.pid, msg.replace('\n', " ⏎ "))
+}
+
+/// Report files (not directories such as `Retired`), filtered, newest first, at most 50
+fn crash_list(names: Vec<String>, filter: &str) -> Vec<String> {
+ let f = filter.to_lowercase();
+ let mut v: Vec<String> = names
+ .into_iter()
+ .filter(|n| n.contains('.') && !n.starts_with('.'))
+ .filter(|n| f.is_empty() || n.to_lowercase().contains(&f))
+ .collect();
+ v.sort_by(|a, b| report_date(b).cmp(report_date(a)).then_with(|| a.cmp(b)));
+ v.truncate(50);
+ v
+}
+
+/// `MyApp-2026-11-08-120000.ips` → `2026-11-08-120000`, for sorting by date across apps
+fn report_date(name: &str) -> &str {
+ let stem = name.split('.').next().unwrap_or(name);
+ let b = stem.as_bytes();
+ (0..b.len().saturating_sub(16))
+ .rev()
+ .find(|&i| {
+ b[i..].len() >= 17
+ && b[i..i + 4].iter().all(u8::is_ascii_digit)
+ && b[i + 4] == b'-'
+ && b[i + 7] == b'-'
+ && b[i + 10] == b'-'
+ })
+ .map_or("", |i| &stem[i..])
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn entry(process: &str, level: LogLevel, msg: &str) -> LogEntry {
+ LogEntry {
+ pid: 42,
+ process: process.into(),
+ level,
+ subsystem: Some("com.example:net".into()),
+ message: msg.into(),
+ }
+ }
+
+ #[test]
+ fn wda_runner_cannot_be_uninstalled() {
+ let signed = Some("com.facebook.WebDriverAgentRunner.xctrunner.ABC123");
+ assert!(is_wda_runner("com.facebook.WebDriverAgentRunner.xctrunner.ABC123", signed));
+ // another build of the runner, or ours before a re-sign changed the suffix
+ assert!(is_wda_runner("com.example.WebDriverAgentRunner.xctrunner", None));
+ assert!(!is_wda_runner("com.example.myapp", signed));
+ }
+
+ #[test]
+ fn log_filter() {
+ let app = "/private/var/containers/Bundle/Application/X/My App.app/MyApp";
+ let e = entry(app, LogLevel::Error, "Request failed: timeout");
+ let f = |process, grep, errors_only| LogFilter { process, grep, errors_only };
+ assert!(f(Some("myapp"), "", false).matches(&e));
+ assert!(!f(Some("App"), "", false).matches(&e));
+ assert!(f(None, "TIMEOUT", true).matches(&e));
+ assert!(f(None, "example:net", false).matches(&e));
+ assert!(!f(None, "", true).matches(&entry(app, LogLevel::Notice, "ok")));
+ }
+
+ #[test]
+ fn log_line_format() {
+ let e = entry("/usr/libexec/backboardd", LogLevel::Fault, "a\nb");
+ assert_eq!(format_line(Duration::from_millis(1500), &e), "-1.5s backboardd[42] <Fault> com.example:net a ⏎ b");
+ let long = entry("/x/P", LogLevel::Notice, &"é".repeat(700));
+ assert!(format_line(Duration::ZERO, &long).ends_with("é…"));
+ }
+
+ /// Lines are kept short and the buffer stays within its byte budget, dropping the oldest lines first
+ #[test]
+ fn buffer_is_bounded_by_size() {
+ let e = compact(entry("/private/var/containers/X.app/MyApp", LogLevel::Debug, &"x".repeat(5000)));
+ assert_eq!(e.process, "MyApp");
+ assert_eq!(e.message.chars().count(), MAX_LINE_CHARS + 1);
+ let mut b = Buffer::default();
+ let t = Instant::now();
+ let per = size(&e);
+ for i in 0..(MAX_BYTES / per + 100) {
+ b.push(t + Duration::from_micros(i as u64), e.clone());
+ }
+ assert!(b.bytes <= MAX_BYTES && b.lines.len() <= MAX_LINES, "{} bytes, {} lines", b.bytes, b.lines.len());
+ assert_eq!(b.bytes, b.lines.iter().map(|(_, e)| size(e)).sum::<usize>());
+ assert!(b.lines.front().unwrap().0 > t, "the oldest lines went first");
+ }
+
+ #[test]
+ fn crash_reports_newest_first() {
+ let names = vec![
+ "Retired".into(),
+ "MyApp-2026-11-07-090000.ips".into(),
+ "Other-2026-11-08-120000.ips".into(),
+ "MyApp-2026-11-08-101500.ips".into(),
+ ];
+ assert_eq!(
+ crash_list(names.clone(), ""),
+ ["Other-2026-11-08-120000.ips", "MyApp-2026-11-08-101500.ips", "MyApp-2026-11-07-090000.ips"]
+ );
+ assert_eq!(crash_list(names, "myapp").len(), 2);
+ assert_eq!(report_date("JetsamEvent-2026-11-08-101500.ips"), "2026-11-08-101500");
+ assert_eq!(report_date("weird.ips"), "");
+ }
+}
diff --git a/crates/ictl-daemon/src/lib.rs b/crates/ictl-daemon/src/lib.rs
index 4086be0..4b9853c 100644
--- a/crates/ictl-daemon/src/lib.rs
+++ b/crates/ictl-daemon/src/lib.rs
@@ -8,6 +8,7 @@
pub mod config;
pub mod core;
pub mod devices;
+mod devtools;
mod doctor;
pub mod eventlog;
pub mod imaging;
diff --git a/crates/ictl-daemon/src/supervise.rs b/crates/ictl-daemon/src/supervise.rs
index a871383..12d903d 100644
--- a/crates/ictl-daemon/src/supervise.rs
+++ b/crates/ictl-daemon/src/supervise.rs
@@ -205,6 +205,8 @@ impl Daemon {
self.drop_session(g).await;
g.offline_since = Some(now);
g.apps.clear();
+ // 日志采集属于那台设备:不再控制它就停掉,不让旧设备的日志流再跑到闲置超时
+ g.log_capture = None;
}
self.set_state(g, DeviceState::Absent);
let since = *g.offline_since.get_or_insert(now);
@@ -237,6 +239,8 @@ impl Daemon {
g.device_profile = DeviceProfile::NotChecked;
// App 列表是上一台的(同一台重新接入也重读,便宜)
g.apps.clear();
+ // 日志采集属于那台设备:不再控制它就停掉,不让旧设备的日志流再跑到闲置超时
+ g.log_capture = None;
g.wda_rotation = None;
let d = Device::from_usb(seen);
g.info = d.info().await.ok();
diff --git a/crates/ictl-daemon/src/tools.rs b/crates/ictl-daemon/src/tools.rs
index b78b4a7..724a23d 100644
--- a/crates/ictl-daemon/src/tools.rs
+++ b/crates/ictl-daemon/src/tools.rs
@@ -726,7 +726,7 @@ impl Daemon {
Ok(a)
}
- async fn resolve_app(&self, g: &mut Inner, app: &str) -> Result<String, String> {
+ pub(crate) async fn resolve_app(&self, g: &mut Inner, app: &str) -> Result<String, String> {
if apps::looks_like_bundle_id(app) {
return Ok(app.to_owned());
}
diff --git a/crates/ictl-device/src/apps.rs b/crates/ictl-device/src/apps.rs
index c26bd51..0bbb748 100644
--- a/crates/ictl-device/src/apps.rs
+++ b/crates/ictl-device/src/apps.rs
@@ -6,6 +6,8 @@ use std::collections::HashMap;
pub struct AppInfo {
pub name: String,
pub bundle_id: String,
+ /// CFBundleExecutable: the process name the app runs as (for filtering its logs)
+ pub executable: String,
}
/// 解析 installation_proxy `Lookup` 的结果,按名字排序。
@@ -29,7 +31,8 @@ pub fn parse_apps(lookup: HashMap<String, plist::Value>) -> Vec<AppInfo> {
.unwrap_or_default()
.to_owned();
let bundle_id = d.get("CFBundleIdentifier").and_then(|v| v.as_string()).unwrap_or(&bid).to_owned();
- Some(AppInfo { name, bundle_id })
+ let executable = d.get("CFBundleExecutable").and_then(|v| v.as_string()).unwrap_or_default().to_owned();
+ Some(AppInfo { name, bundle_id, executable })
})
.collect();
out.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.bundle_id.cmp(&b.bundle_id)));
@@ -92,7 +95,11 @@ mod tests {
#[test]
fn hidden_system_services_are_skipped() {
let s = system();
- assert!(s.contains(&AppInfo { name: "设置".into(), bundle_id: "com.apple.Preferences".into() }));
+ assert!(s.contains(&AppInfo {
+ name: "设置".into(),
+ bundle_id: "com.apple.Preferences".into(),
+ executable: String::new()
+ }));
assert!(s.iter().all(|a| a.bundle_id != "com.apple.NewDeviceSetupUIService"));
assert_eq!(s.iter().filter(|a| a.name == "设置").count(), 1);
}
diff --git a/crates/ictl-device/src/lib.rs b/crates/ictl-device/src/lib.rs
index 2a34dfc..703a08a 100644
--- a/crates/ictl-device/src/lib.rs
+++ b/crates/ictl-device/src/lib.rs
@@ -14,6 +14,7 @@ pub mod apps;
pub mod ddi;
pub mod hid;
mod media;
+pub mod oslog;
use std::future::Future;
use std::path::Path;
@@ -25,6 +26,7 @@ use idevice::{
amfi::AmfiClient,
core_device::{ImageFormat, ScreenCaptureServiceClient},
core_device_proxy::CoreDeviceProxy,
+ crashreportcopymobile::CrashReportCopyMobileClient,
cryptexd::{Cryptex1Assets, install_ddi, installed_ddi},
installation_proxy::InstallationProxyClient,
lockdown::LockdownClient,
@@ -38,6 +40,49 @@ use idevice::{
pub use apps::AppInfo;
pub use hid::{Button, HidSession};
+/// A running log stream from the phone; see [`Device::log_stream`]
+pub struct LogStream(oslog::OsLogStream);
+
+/// One line of the phone's unified log
+#[derive(Debug, Clone)]
+pub struct LogEntry {
+ pub pid: u32,
+ /// Path of the process' executable
+ pub process: String,
+ pub level: LogLevel,
+ pub subsystem: Option<String>,
+ pub message: String,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum LogLevel {
+ Debug,
+ Info,
+ Notice,
+ Error,
+ Fault,
+}
+
+impl LogStream {
+ /// The next entry; an error means the stream is gone (phone unplugged, service stopped)
+ pub async fn next(&mut self) -> Result<LogEntry> {
+ let e = self.0.next().await?;
+ Ok(LogEntry {
+ pid: e.pid,
+ process: e.filename,
+ level: match e.level {
+ 1 => LogLevel::Info,
+ 2 => LogLevel::Debug,
+ 0x10 => LogLevel::Error,
+ 0x11 => LogLevel::Fault,
+ _ => LogLevel::Notice,
+ },
+ subsystem: e.subsystem.map(|(s, c)| format!("{s}:{c}")),
+ message: e.message,
+ })
+ }
+}
+
/// 连接标签,出现在设备日志里
pub const LABEL: &str = "iphone-control";
@@ -412,6 +457,48 @@ impl Device {
})
.await
}
+
+ /// Removes an app by bundle ID (installation_proxy)
+ pub async fn uninstall(&self, bundle_id: &str) -> Result<()> {
+ limit(ictl_l10n::tr!("卸载", "uninstall"), Duration::from_secs(120), async {
+ let mut proxy = InstallationProxyClient::connect(&*self.provider).await?;
+ proxy.uninstall(bundle_id, None).await?;
+ Ok(())
+ })
+ .await
+ }
+
+ /// Names of the crash reports in the top directory, after asking the phone to move new ones there
+ pub async fn crash_reports(&self) -> Result<Vec<String>> {
+ limit(ictl_l10n::tr!("列出崩溃报告", "list crash reports"), Duration::from_secs(30), async {
+ // without the flush, reports from the last minutes may not be visible yet; it is only a hint
+ let _ = idevice::crashreportcopymobile::flush_reports(&*self.provider).await;
+ let mut c = CrashReportCopyMobileClient::connect(&*self.provider).await?;
+ Ok(c.ls(None).await?)
+ })
+ .await
+ }
+
+ /// One crash report's content
+ pub async fn crash_report(&self, name: &str) -> Result<Vec<u8>> {
+ limit(ictl_l10n::tr!("读取崩溃报告", "read crash report"), Duration::from_secs(30), async {
+ let mut c = CrashReportCopyMobileClient::connect(&*self.provider).await?;
+ Ok(c.pull(name).await?)
+ })
+ .await
+ }
+
+ /// Starts the phone's unified log stream (os_trace_relay), every process, without debug messages.
+ /// Asking for debug messages (what idevice's `start_trace` does) makes every process on the phone produce them:
+ /// about 650 lines a second instead of about 80 on an idle iPhone 15 Pro Max (iOS 27.0.1), and gestures got
+ /// slower and some failed while the stream ran. Info messages come along with debug, so they are left out too
+ pub async fn log_stream(&self) -> Result<LogStream> {
+ let flags = oslog::flags::IDEVICE_DEFAULT & !oslog::flags::DEBUG;
+ let inner =
+ limit(ictl_l10n::tr!("打开日志流", "open the log stream"), QUERY, oslog::start(&*self.provider, flags))
+ .await?;
+ Ok(LogStream(inner))
+ }
}
/// 一条活着的隧道。HID、截图、cryptexd 都经它访问 RSD 服务;丢掉它隧道就断了。
diff --git a/crates/ictl-device/src/oslog.rs b/crates/ictl-device/src/oslog.rs
new file mode 100644
index 0000000..cd32dea
--- /dev/null
+++ b/crates/ictl-device/src/oslog.rs
@@ -0,0 +1,172 @@
+//! The phone's unified log over `com.apple.os_trace_relay`, with our own `StartActivity` request.
+//!
+//! idevice's `OsTraceRelayClient::start_trace` always asks for `StreamFlags: 60`, which includes debug messages.
+//! Streaming debug messages makes every process on the phone produce them (hundreds of lines a second) and visibly
+//! slows the phone: gestures get slower and some fail. So we send the request ourselves with the flags we want and
+//! read the entries with a bounds-checked parser.
+//!
+//! Packet layout follows idevice's `OsTraceRelayReceiver::next` (MIT, Copyright Jackson Coxson), itself based on
+//! pymobiledevice3's `os_trace.py`.
+
+use idevice::{Idevice, IdeviceService, os_trace_relay::OsTraceRelayClient, provider::IdeviceProvider};
+
+use crate::{DeviceError, Result};
+
+/// `StreamFlags` bits of the activity stream (Apple's private `os_activity_stream_flag_t`)
+pub mod flags {
+ pub const PAYLOAD: u64 = 0x04;
+ pub const HISTORICAL: u64 = 0x08;
+ pub const CALLSTACK: u64 = 0x10;
+ pub const DEBUG: u64 = 0x20;
+ /// What idevice and pymobiledevice3 send
+ pub const IDEVICE_DEFAULT: u64 = PAYLOAD | HISTORICAL | CALLSTACK | DEBUG;
+}
+
+/// Fixed part of an entry before the strings
+const HEADER: usize = 129;
+
+/// One raw entry
+#[derive(Debug, Clone)]
+pub struct RawEntry {
+ pub pid: u32,
+ /// 0 notice, 1 info, 2 debug, 0x10 error, 0x11 fault
+ pub level: u8,
+ pub filename: String,
+ pub subsystem: Option<(String, String)>,
+ pub message: String,
+}
+
+pub struct OsLogStream(Idevice);
+
+/// Opens the relay and starts streaming every process with `stream_flags`
+pub async fn start(provider: &dyn IdeviceProvider, stream_flags: u64) -> Result<OsLogStream> {
+ let mut idevice = OsTraceRelayClient::connect(provider).await?.idevice;
+ let mut req = plist::Dictionary::new();
+ req.insert("Request".into(), "StartActivity".into());
+ req.insert("Pid".into(), plist::Value::Integer((-1i64).into()));
+ req.insert("MessageFilter".into(), plist::Value::Integer(65_535u64.into()));
+ req.insert("StreamFlags".into(), plist::Value::Integer(stream_flags.into()));
+ let mut body = Vec::new();
+ plist::Value::Dictionary(req).to_writer_binary(&mut body).map_err(|e| DeviceError::Idevice(e.to_string()))?;
+ let mut msg = (body.len() as u32).to_be_bytes().to_vec();
+ msg.extend_from_slice(&body);
+ idevice.send_raw(&msg).await?;
+ // one byte, then a length-prefixed plist with the status
+ idevice.read_raw(1).await?;
+ let len = u32::from_be_bytes(be4(&idevice.read_raw(4).await?)?) as usize;
+ let res: plist::Value =
+ plist::from_bytes(&idevice.read_raw(len).await?).map_err(|e| DeviceError::Idevice(e.to_string()))?;
+ let status = res.as_dictionary().and_then(|d| d.get("Status")).and_then(|s| s.as_string());
+ if status != Some("RequestSuccessful") {
+ return Err(DeviceError::Idevice(format!("os_trace_relay StartActivity: {res:?}")));
+ }
+ Ok(OsLogStream(idevice))
+}
+
+impl OsLogStream {
+ /// The next entry; an error means the stream is gone or out of step. An entry that doesn't parse is
+ /// skipped (its length is known, so the stream stays in step)
+ pub async fn next(&mut self) -> Result<RawEntry> {
+ loop {
+ if self.0.read_raw(1).await?[0] != 0x02 {
+ return Err(DeviceError::Idevice("os_trace_relay: unexpected packet start".into()));
+ }
+ let len = u32::from_le_bytes(be4(&self.0.read_raw(4).await?)?) as usize;
+ let packet = self.0.read_raw(len).await?;
+ match parse(&packet) {
+ Some(e) => return Ok(e),
+ None => tracing::debug!("os_trace_relay: skipped an unreadable entry ({len} bytes)"),
+ }
+ }
+ }
+}
+
+fn be4(b: &[u8]) -> Result<[u8; 4]> {
+ b.get(..4).and_then(|s| s.try_into().ok()).ok_or_else(|| DeviceError::Idevice("short read".into()))
+}
+
+/// Parses one entry; `None` if it is shorter than its own sizes say
+pub fn parse(p: &[u8]) -> Option<RawEntry> {
+ let u16le = |at: usize| p.get(at..at + 2).map(|b| u16::from_le_bytes([b[0], b[1]]) as usize);
+ let u32le = |at: usize| p.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
+ if p.len() < HEADER {
+ return None;
+ }
+ let pid = u32le(9)?;
+ let level = *p.get(68)?;
+ let image_name_size = u16le(107)?;
+ let message_size = u16le(109)?;
+ let subsystem_size = u32le(117)? as usize;
+ let category_size = u32le(121)? as usize;
+ let rest = &p[HEADER..];
+ let nul = rest.iter().position(|&b| b == 0)?;
+ let filename = String::from_utf8_lossy(&rest[..nul]).into_owned();
+ let mut at = nul + 1 + image_name_size;
+ let message = take(rest, &mut at, message_size)?;
+ // the sizes can be set while the strings are left out (idevice does the same check)
+ let subsystem = if subsystem_size > 0 && category_size > 0 && at < rest.len() {
+ let sub = take(rest, &mut at, subsystem_size)?;
+ Some((sub, take(rest, &mut at, category_size)?))
+ } else {
+ None
+ };
+ Some(RawEntry { pid, level, filename, subsystem, message })
+}
+
+/// The `n`-byte string at `*at` (NUL-terminated, the size includes the NUL), moving `at` past it
+fn take(rest: &[u8], at: &mut usize, n: usize) -> Option<String> {
+ let s = rest.get(*at..at.checked_add(n)?)?;
+ *at += n;
+ Some(String::from_utf8_lossy(s.strip_suffix(&[0]).unwrap_or(s)).into_owned())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn entry(level: u8, file: &str, msg: &str, label: Option<(&str, &str)>) -> Vec<u8> {
+ let mut p = vec![0u8; HEADER];
+ p[9..13].copy_from_slice(&42u32.to_le_bytes());
+ p[68] = level;
+ let image = b"img\0";
+ p[107..109].copy_from_slice(&(image.len() as u16).to_le_bytes());
+ p[109..111].copy_from_slice(&((msg.len() + 1) as u16).to_le_bytes());
+ if let Some((s, c)) = label {
+ p[117..121].copy_from_slice(&((s.len() + 1) as u32).to_le_bytes());
+ p[121..125].copy_from_slice(&((c.len() + 1) as u32).to_le_bytes());
+ }
+ p.extend_from_slice(file.as_bytes());
+ p.push(0);
+ p.extend_from_slice(image);
+ p.extend_from_slice(msg.as_bytes());
+ p.push(0);
+ if let Some((s, c)) = label {
+ p.extend_from_slice(s.as_bytes());
+ p.push(0);
+ p.extend_from_slice(c.as_bytes());
+ p.push(0);
+ }
+ p
+ }
+
+ #[test]
+ fn parses_entries_and_rejects_short_ones() {
+ let e = parse(&entry(0x10, "/usr/libexec/x", "boom", Some(("com.example", "net")))).unwrap();
+ assert_eq!((e.pid, e.level, e.filename.as_str(), e.message.as_str()), (42, 0x10, "/usr/libexec/x", "boom"));
+ assert_eq!(e.subsystem, Some(("com.example".into(), "net".into())));
+ let e = parse(&entry(0, "/x", "hi", None)).unwrap();
+ assert_eq!((e.message.as_str(), e.subsystem), ("hi", None));
+ // cut anywhere: no panic, just None
+ let full = entry(2, "/usr/bin/y", "message", Some(("s", "c")));
+ for n in 0..full.len() {
+ let _ = parse(&full[..n]);
+ }
+ assert!(parse(&full[..HEADER - 1]).is_none());
+ // label sizes set but the strings left out
+ let mut no_label = entry(0, "/x", "hi", None);
+ no_label[117..121].copy_from_slice(&5u32.to_le_bytes());
+ no_label[121..125].copy_from_slice(&5u32.to_le_bytes());
+ assert_eq!(parse(&no_label).unwrap().subsystem, None);
+ assert!(parse(&full[..full.len() - 3]).is_none());
+ }
+}
diff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rs
index 3661789..b14d469 100644
--- a/crates/ictl-mcp/src/lib.rs
+++ b/crates/ictl-mcp/src/lib.rs
@@ -118,9 +118,102 @@ fn acting(title: &str, destructive: bool, idempotent: bool) -> ToolAnnotations {
ToolAnnotations::with_title(title).read_only(false).destructive(destructive).idempotent(idempotent).open_world(true)
}
+/// Names of the developer tools, listed only with [`dev_tools_enabled`]
+pub const DEV_TOOLS: [&str; 4] =
+ ["iphone_app_logs", "iphone_crash_reports", "iphone_install_app", "iphone_uninstall_app"];
+
+/// `IPHONE_CONTROL_DEV_TOOLS=1` (or true/yes/on) adds the developer tools; off by default, so agents that don't
+/// need them don't pay for their descriptions
+pub fn dev_tools_enabled() -> bool {
+ std::env::var("IPHONE_CONTROL_DEV_TOOLS")
+ .is_ok_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
+}
+
+/// The tools this server lists: the 17 standard ones, plus the developer tools when switched on
+pub fn tools() -> Vec<Tool> {
+ tools_with(dev_tools_enabled())
+}
+
+pub fn tools_with(dev: bool) -> Vec<Tool> {
+ let mut v = standard_tools();
+ if dev {
+ v.extend(dev_tools());
+ }
+ v
+}
+
+fn dev_tools() -> Vec<Tool> {
+ let t = |name: &'static str, desc: &str, s: Map<String, Value>, a: ToolAnnotations| {
+ Tool::new(name, desc.to_owned(), s).with_annotations(a)
+ };
+ vec![
+ t(
+ "iphone_app_logs",
+ ictl_l10n::tr!(
+ "读手机的系统日志(os_log,默认、Error、Fault 级别;Debug、Info 不记录,记录它们会拖慢手机),可按 App 或进程、关键词、时间筛选,每行:多少秒前、进程[pid]、级别、子系统、内容。\n\n\
+何时用:App 崩溃、报错、请求失败、界面没反应时,不靠截图找原因。第一次调用才开始记录(之前的拿不到):先调一次,复现问题,再调一次。\
+记录在 15 分钟没有调用后自动停止。只读。",
+ "Read the phone's system log (os_log, default, Error and Fault levels; Debug and Info aren't recorded, since streaming them slows the phone down), filtered by app or process, keyword and time; one line per entry: seconds ago, process[pid], level, subsystem, message.\n\nWhen to use: when an app crashes, shows an error, a request fails or the UI doesn't respond, to find the cause without screenshots. Recording starts with the first call (earlier lines aren't available): call it once, reproduce the problem, then call it again. Recording stops by itself after 15 minutes without a call. Read-only."
+ ),
+ schema(
+ json!({
+ "process": {"type": "string", "default": "", "description": ictl_l10n::tr!("App 的显示名或 Bundle ID,或进程名(如 SpringBoard);空为全部", "app display name or bundle ID, or a process name (e.g. SpringBoard); empty for all")},
+ "grep": {"type": "string", "default": "", "description": ictl_l10n::tr!("只要内容或子系统包含这段文字的行(不分大小写)", "only lines whose message or subsystem contains this text (case-insensitive)")},
+ "since": {"type": "number", "default": 60, "description": ictl_l10n::tr!("只看最近多少秒,最多 3600", "only the last this many seconds, at most 3600")},
+ "limit": {"type": "integer", "default": 100, "description": ictl_l10n::tr!("最多返回多少行(最新的),1 到 1000", "at most this many lines (the newest), 1 to 1000")},
+ "errors_only": {"type": "boolean", "default": false, "description": ictl_l10n::tr!("只看 Error 和 Fault 级别", "only Error and Fault levels")}
+ }),
+ &[],
+ ),
+ looking(ictl_l10n::tr!("读日志", "Read logs")),
+ ),
+ t(
+ "iphone_crash_reports",
+ ictl_l10n::tr!(
+ "列出手机上的崩溃报告(新的在前,最多 50 个),或用 name 读取其中一份(.ips,开头是异常类型、崩溃的线程和 App 版本)。\n\n\
+何时用:App 闪退后找原因。只读。",
+ "List the crash reports on the phone (newest first, at most 50), or read one with name (.ips; the start has the exception type, the crashed thread and the app version).\n\nWhen to use: to find out why an app quit unexpectedly. Read-only."
+ ),
+ schema(
+ json!({
+ "filter": {"type": "string", "default": "", "description": ictl_l10n::tr!("只列文件名包含这段文字的(如进程名)", "only list file names containing this text (e.g. the process name)")},
+ "name": {"type": "string", "default": "", "description": ictl_l10n::tr!("要读取的报告文件名(来自列表);给了就返回内容", "file name of the report to read (from the list); if given, returns its content")}
+ }),
+ &[],
+ ),
+ looking(ictl_l10n::tr!("崩溃报告", "Crash reports")),
+ ),
+ t(
+ "iphone_install_app",
+ ictl_l10n::tr!(
+ "安装签好名的 .ipa 或 .app(覆盖已装的同一 App)。path 是运行守护进程的机器上的路径,容器部署时是容器里的路径。\
+大的包要一两分钟。",
+ "Install a signed .ipa or .app (replacing the same app if installed). path is on the machine that runs the daemon; inside the container for a container deployment. Large packages take a minute or two."
+ ),
+ schema(
+ json!({"path": {"type": "string", "description": ictl_l10n::tr!(".ipa 文件或 .app 目录的路径", "path of the .ipa file or .app directory")}}),
+ &["path"],
+ ),
+ acting(ictl_l10n::tr!("安装 App", "Install app"), true, true),
+ ),
+ t(
+ "iphone_uninstall_app",
+ ictl_l10n::tr!(
+ "卸载 App,连同它的数据。不会卸载 WebDriverAgent(iphone-control 靠它控制手机)。卸载前先问用户。",
+ "Uninstall an app, together with its data. Refuses to remove WebDriverAgent, which iphone-control needs to control the phone. Ask the user before uninstalling."
+ ),
+ schema(
+ json!({"app": {"type": "string", "description": ictl_l10n::tr!("Bundle ID 或显示名", "bundle ID or display name")}}),
+ &["app"],
+ ),
+ acting(ictl_l10n::tr!("卸载 App", "Uninstall app"), true, true),
+ ),
+ ]
+}
+
/// 17 个工具的定义(toolkit 的 13 个 + iphone_wait_for、iphone_batch、iphone_list_devices、iphone_select_device)。
/// 描述可以改写,但工具名、参数、默认返回不改(docs/decisions.md D10)
-pub fn tools() -> Vec<Tool> {
+fn standard_tools() -> Vec<Tool> {
let t = |name: &'static str, desc: String, s: Map<String, Value>, a: ToolAnnotations| {
Tool::new(name, desc, s).with_annotations(a)
};
@@ -502,6 +595,16 @@ pub fn to_request(name: &str, args: &Map<String, Value>) -> Result<Request, Stri
"iphone_open_url" => Request::OpenUrl { url: a.s("url")? },
"iphone_list_devices" => Request::ListDevices,
"iphone_select_device" => Request::SelectDevice { device: a.s("device")? },
+ "iphone_app_logs" => Request::AppLogs {
+ process: a.s_or("process", "")?,
+ grep: a.s_or("grep", "")?,
+ since_secs: a.u_or("since", 60)? as u64,
+ limit: a.u_or("limit", 100)?,
+ errors_only: a.b_or("errors_only", false)?,
+ },
+ "iphone_crash_reports" => Request::CrashReports { filter: a.s_or("filter", "")?, name: a.s_or("name", "")? },
+ "iphone_install_app" => Request::InstallApp { path: a.s("path")? },
+ "iphone_uninstall_app" => Request::UninstallApp { app: a.s("app")? },
"iphone_wait_for" => {
let secs = a.f_or("timeout", 5.0)?;
if !(0.0..=30.0).contains(&secs) {
@@ -639,7 +742,14 @@ pub fn tap_missed(text: &str, outcome: Option<protocol::Outcome>) -> bool {
pub fn wants_alert_check(req: &Request) -> bool {
// 切换设备后新设备的 WDA 还没起来,查不了弹窗
req.is_device_action()
- && !matches!(req, Request::PressButton { .. } | Request::TerminateApp { .. } | Request::SelectDevice { .. })
+ && !matches!(
+ req,
+ Request::PressButton { .. }
+ | Request::TerminateApp { .. }
+ | Request::SelectDevice { .. }
+ | Request::InstallApp { .. }
+ | Request::UninstallApp { .. }
+ )
}
/// 守护进程响应 → MCP 结果。错误走工具错误(is_error),文字原样给客户端
@@ -695,6 +805,14 @@ impl McpServer {
if request.name == "iphone_batch" {
return Ok(self.batch(&args, then).await.into());
}
+ if DEV_TOOLS.contains(&&*request.name) && !dev_tools_enabled() {
+ let name = &request.name;
+ return Ok(to_result(Response::error(ictl_l10n::trf!(
+ "{name} 是开发者工具,要先设 IPHONE_CONTROL_DEV_TOOLS=1",
+ "{name} is a developer tool; set IPHONE_CONTROL_DEV_TOOLS=1 first"
+ )))
+ .into());
+ }
let req = match to_request(&request.name, &args) {
Ok(r) => r,
Err(e) => return Ok(to_result(Response::error(e)).into()),
@@ -718,8 +836,10 @@ impl McpServer {
/// `expect_udid`:守护进程正在控制的不是这台就不执行(见 [`protocol::EXPECT_UDID`])
async fn call_on(&self, req: &Request, expect_udid: Option<&str>) -> Response {
- // 守护进程正忙(例如在自动解锁)时会排队;最多等 150 秒,免得 agent 一直挂着
- protocol::call_expecting(&self.socket, req, Some(Duration::from_secs(150)), expect_udid).await.unwrap_or_else(
+ // 守护进程正忙(例如在自动解锁)时会排队;最多等 150 秒,免得 agent 一直挂着。An install uploads the package and
+ // can take several minutes on its own
+ let wait = if matches!(req, Request::InstallApp { .. }) { 660 } else { 150 };
+ protocol::call_expecting(&self.socket, req, Some(Duration::from_secs(wait)), expect_udid).await.unwrap_or_else(
|e| {
Response::error(ictl_l10n::trf!("连不上守护进程({}):{e};确认守护进程在运行(容器部署看 iphone-control 容器)", "Can't reach the daemon ({}): {e}; make sure the daemon is running (for a container deployment, check the iphone-control container)",
self.socket.display()
@@ -871,7 +991,7 @@ mod tests {
use ictl_l10n::{Lang, with_lang};
with_lang(Lang::En, || {
assert!(!has_cjk(instructions()), "{}", instructions());
- for t in tools() {
+ for t in tools_with(true) {
let json = serde_json::to_string(&t).unwrap();
assert!(!has_cjk(&json), "{}: {json}", t.name);
}
@@ -892,6 +1012,10 @@ mod tests {
fn toolkit_tools_plus_wait_for_batch_and_devices() {
let names: Vec<_> = tools().iter().map(|t| t.name.to_string()).collect();
assert_eq!(names.len(), 17);
+ // the developer tools only with IPHONE_CONTROL_DEV_TOOLS
+ let dev: Vec<_> = tools_with(true).iter().skip(17).map(|t| t.name.to_string()).collect();
+ assert_eq!(dev, DEV_TOOLS);
+ assert_eq!(tools_with(false).len(), 17);
for n in [
"iphone_status",
"iphone_screenshot",
@@ -902,7 +1026,7 @@ mod tests {
] {
assert!(names.contains(&n.to_owned()), "{n}");
}
- for t in tools().into_iter().filter(|t| t.name != "iphone_batch") {
+ for t in tools_with(true).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);
}
@@ -911,7 +1035,7 @@ mod tests {
/// 注解与工具实际行为一致:看界面的只读,改界面的不是;每个参数都有说明
#[test]
fn annotations_and_param_docs() {
- for t in tools() {
+ for t in tools_with(true) {
let a = t.annotations.as_ref().unwrap_or_else(|| panic!("{} 没有注解", t.name));
assert!(a.title.is_some(), "{}", t.name);
let probe = || {
diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rs
index 0b5ab9e..64841f7 100644
--- a/crates/ictl-protocol/src/lib.rs
+++ b/crates/ictl-protocol/src/lib.rs
@@ -123,6 +123,33 @@ pub enum Request {
SelectDevice {
device: String,
},
+ /// Developer tools: the phone's unified log. `process` is an app (name or bundle ID) or a process name, empty for
+ /// all; `grep` matches message or subsystem; only lines from the last `since_secs` seconds
+ AppLogs {
+ #[serde(default)]
+ process: String,
+ #[serde(default)]
+ grep: String,
+ since_secs: u64,
+ limit: usize,
+ #[serde(default)]
+ errors_only: bool,
+ },
+ /// Developer tools: list crash reports (filtered by `filter`), or return the one called `name`
+ CrashReports {
+ #[serde(default)]
+ filter: String,
+ #[serde(default)]
+ name: String,
+ },
+ /// Developer tools: install a signed .ipa or .app from a path on the daemon's machine
+ InstallApp {
+ path: String,
+ },
+ /// Developer tools: remove an app (never the WebDriverAgent runner)
+ UninstallApp {
+ app: String,
+ },
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -184,6 +211,8 @@ impl Request {
| Self::TerminateApp { .. }
| Self::OpenUrl { .. }
| Self::SelectDevice { .. }
+ | Self::InstallApp { .. }
+ | Self::UninstallApp { .. }
)
}
}
diff --git a/docs/licensing.md b/docs/licensing.md
index ed069e8..eb37b08 100644
--- a/docs/licensing.md
+++ b/docs/licensing.md
@@ -10,7 +10,7 @@
| 依赖 | 用途 | 许可证 | 使用方式 | 义务 |
|---|---|---|---|---|
-| idevice(上游 master `89702099`) | 设备通讯 | MIT | git 依赖(`[patch.crates-io]`,0.1.68 之后未发版的修复);`ictl-device/src/media.rs` 与 HID 键码表改写自它的 tools(MIT) | 保留版权声明 |
+| idevice(上游 master `89702099`) | 设备通讯 | MIT | git 依赖(`[patch.crates-io]`,0.1.68 之后未发版的修复);`ictl-device/src/media.rs` 与 HID 键码表改写自它的 tools、`oslog.rs` 的日志条目格式取自它的 os_trace_relay(MIT) | 保留版权声明 |
| jktcp 0.1.8 | 用户态 TCP(idevice 间接依赖) | MIT | 间接依赖 | 同上 |
| plume_core(Impactor) | Apple ID、开发者 API、描述文件、证书 | **MPL-2.0**(目录内 LICENSE) | vendor 到 `vendor/plume_core`,源码未改,只改了 Cargo.toml(workspace 继承、reqwest 不带 aws-lc-rs、omnisette 只开远程 anisette) | 以 MPL-2.0 随仓库提供源码;文件头保留 |
| plume_store(Impactor) | 账号会话存储 | MIT(Impactor 根 LICENSE) | vendor 到 `vendor/plume_store`,源码未改 | 保留版权声明(`vendor/plume_store/LICENSE-MIT-Impactor`) |
diff --git a/docs/tools.md b/docs/tools.md
index b193ac8..3df8d7e 100644
--- a/docs/tools.md
+++ b/docs/tools.md
@@ -1,6 +1,6 @@
# MCP tools
-The MCP server (`iphone-control mcp`) exposes 17 tools. The tool descriptions the agent sees, and every result text, are in Simplified Chinese by default, or in English with `IPHONE_CONTROL_LANG=en` (see [configuration](https://derrors.github.io/iphone-control/en/guide/configuration)); this page is the English reference. The definitions live in [`crates/ictl-mcp/src/lib.rs`](../crates/ictl-mcp/src/lib.rs).
+The MCP server (`iphone-control mcp`) exposes 17 tools (21 with the [developer tools](#developer-tools-opt-in)). The tool descriptions the agent sees, and every result text, are in Simplified Chinese by default, or in English with `IPHONE_CONTROL_LANG=en` (see [configuration](https://derrors.github.io/iphone-control/en/guide/configuration)); this page is the English reference. The definitions live in [`crates/ictl-mcp/src/lib.rs`](../crates/ictl-mcp/src/lib.rs).
Coordinates are in **points**, the same unit as the pixels of a full-screen `iphone_screenshot` (for example 430×932 on an iPhone 15 Pro Max), so an agent can read a position off a screenshot and tap it directly. Coordinates follow the current screen orientation: after a rotation the same spot has different coordinates, so take a new screenshot. Screen sizes differ per device (an iPad mini 5 is 768×1024 in portrait); don't assume 430×932.
@@ -37,6 +37,17 @@ Only one device is controlled at a time; every other tool acts on it. With one d
| `iphone_list_devices` | — | Every iPhone/iPad on USB: name, model, iOS version, UDID; marks the one being controlled and whether it has an auto-unlock passcode |
| `iphone_select_device` | `device`: UDID, device name, or `auto` | Switches to that device and keeps controlling it, also after a restart. A unique substring of the name works too. `auto` goes back to automatic choice: the controlled device is kept until it disconnects. WDA has to start on the new device (10–60 s). Refused when `IPHONE_UDID` is set |
+## Developer tools (opt-in)
+
+With `IPHONE_CONTROL_DEV_TOOLS=1` in the MCP server's environment, four more tools are listed. They are off by default, so agents that don't need them don't pay for their descriptions.
+
+| Tool | Parameters | Notes |
+|---|---|---|
+| `iphone_app_logs` | `process`, `grep`, `since` (60 s), `limit` (100), `errors_only` | The phone's unified log (os_log) at the default, Error and Fault levels, one line per entry (Debug and Info are left out: streaming them makes every process on the phone produce them and slows it down): seconds ago, `process[pid]`, level, subsystem, message. `process` is an app (name or bundle ID) or a process name. The first call starts recording, so earlier lines aren't available: call it once, reproduce the problem, call it again. Recording keeps the last 20,000 lines and stops after 15 minutes without a call. Read-only |
+| `iphone_crash_reports` | `filter`, `name` | Lists crash reports, newest first (at most 50); with `name`, returns that report (`.ips`, cut at 40,000 characters). Read-only |
+| `iphone_install_app` | `path` | Installs a signed `.ipa` or `.app` from a path on the machine that runs the daemon (inside the container for a container deployment). Destructive: it replaces an installed copy of the same app |
+| `iphone_uninstall_app` | `app` | Removes an app and its data. Refuses to remove the WebDriverAgent runner. Destructive |
+
## Auto-unlock and "read-only" tools
When auto-unlock is configured for the controlled device, a locked phone is unlocked first by the action tools and by `iphone_screenshot`, `iphone_list_elements` and `iphone_wait_for`. `iphone_status`, `iphone_list_apps`, `iphone_list_devices`, `iphone_select_device` and `iphone_press_button` with `lock` never unlock it. While WDA is unavailable nothing is unlocked.
diff --git a/website/en/guide/configuration.md b/website/en/guide/configuration.md
index 422f495..61f1e74 100644
--- a/website/en/guide/configuration.md
+++ b/website/en/guide/configuration.md
@@ -13,6 +13,7 @@ Everything is configured with environment variables, and all of them are optiona
|---|---|---|
| `HTTP_PROXY` / `HTTPS_PROXY` | direct | Proxy for Apple, anisette, Developer Disk Image and notification traffic |
| `IPHONE_CONTROL_LANG` | `zh` | Language: `zh` or `en`. Applies to tool descriptions and results, CLI output, logs and notifications. The MCP server and the CLI each send their own setting and the daemon answers in it; logs and notifications follow the daemon's own setting. So for a source install also set it in the MCP client config (`iphone-control mcp-config` includes it) |
+| `IPHONE_CONTROL_DEV_TOOLS` | off | `1` adds the [developer tools](./tools#developer-tools-opt-in) to the MCP server: logs, crash reports, installing and removing apps. For a source install set it in the MCP client config (`iphone-control mcp-config` includes it when set) |
| `IPHONE_UDID` | automatic | Pin the device to control. Unset: the controlled device is kept until it disconnects, and you can switch with the `select` command or the `iphone_select_device` tool. When set, switching is refused |
| `RESIGN_MIN_DAYS` | `2` | Re-sign when fewer days than this remain |
| `RESIGN_CHECK_HOURS` | `6` | How often to check; it is also checked within a minute after the phone reconnects or you switch devices |
diff --git a/website/en/guide/tools.md b/website/en/guide/tools.md
index 31f6d29..381a15c 100644
--- a/website/en/guide/tools.md
+++ b/website/en/guide/tools.md
@@ -39,6 +39,17 @@ Only one device is controlled at a time; every other tool acts on it. With one d
Details: [Several devices](./multi-device).
+## Developer tools (opt-in)
+
+Set `IPHONE_CONTROL_DEV_TOOLS=1` for the MCP server to get four more tools. They are off by default, so agents that don't need them don't pay for their descriptions.
+
+| Tool | What it does |
+|---|---|
+| `iphone_app_logs` | Read the phone's log (default, Error and Fault levels; Debug and Info would slow the phone down), filtered by app or process, text and time. Recording starts with the first call: call it, reproduce the problem, call it again |
+| `iphone_crash_reports` | List crash reports, or read one |
+| `iphone_install_app` | Install a signed `.ipa` or `.app` (a path on the machine that runs the daemon) |
+| `iphone_uninstall_app` | Remove an app and its data; never the WebDriverAgent runner |
+
## See the screen after an action: `then`
The tools under *Acting* accept `then`: it waits for the screen to settle and returns it, saving a round trip.
diff --git a/website/guide/configuration.md b/website/guide/configuration.md
index db1882c..0c92121 100644
--- a/website/guide/configuration.md
+++ b/website/guide/configuration.md
@@ -13,6 +13,7 @@
|---|---|---|
| `HTTP_PROXY` / `HTTPS_PROXY` | 直连 | 访问苹果、anisette、开发者镜像、推送通知用的代理 |
| `IPHONE_CONTROL_LANG` | `zh` | 界面语言:`zh` 或 `en`。工具说明和结果、命令行输出、日志、通知都按它。MCP 和命令行各自按自己的设置请求,守护进程按请求的语言回答;日志和通知按守护进程自己的设置。从源码运行时要在 MCP 配置里也设上(`iphone-control mcp-config` 会带上) |
+| `IPHONE_CONTROL_DEV_TOOLS` | 关 | 设为 `1` 时 MCP 服务多出[开发者工具](./tools):日志、崩溃报告、安装和卸载 App。从源码运行时要写进 MCP 客户端的配置(设了时 `iphone-control mcp-config` 会带上) |
| `IPHONE_UDID` | 自动选 | 固定控制哪台设备。不设时自动选:正在控制的那台一直用到它断开;运行中可以用 `select` 命令或 `iphone_select_device` 工具切换。设了就不能切换 |
| `RESIGN_MIN_DAYS` | `2` | 描述文件剩余不到几天时重签 |
| `RESIGN_CHECK_HOURS` | `6` | 每隔几小时检查一次;手机重新连上或切换设备后 1 分钟内也查一次 |
diff --git a/website/guide/tools.md b/website/guide/tools.md
index dbd1a83..b0091a4 100644
--- a/website/guide/tools.md
+++ b/website/guide/tools.md
@@ -39,6 +39,17 @@ MCP 服务提供 17 个工具。坐标单位是**点**,和整屏截图的像
详见[多台设备](./multi-device)。
+## 开发者工具(显式开启)
+
+给 MCP 服务设 `IPHONE_CONTROL_DEV_TOOLS=1` 后多出四个工具。默认关闭,用不到的 agent 不必多读这些工具说明。
+
+| 工具 | 作用 |
+|---|---|
+| `iphone_app_logs` | 读手机的系统日志(默认、Error、Fault 级别;Debug、Info 会拖慢手机,不记录),可按 App 或进程、文字、时间筛选。第一次调用才开始记录:先调一次,复现问题,再调一次 |
+| `iphone_crash_reports` | 列出崩溃报告,或读取其中一份 |
+| `iphone_install_app` | 安装签好名的 `.ipa` 或 `.app`(路径在运行守护进程的机器上) |
+| `iphone_uninstall_app` | 卸载 App 及其数据;不会卸载 WebDriverAgent |
+
## 操作后顺带看界面:`then`
上面「操作」一节的工具都可以带 `then`,等界面稳定后顺带返回操作后的样子,省一次往返: