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(cli): mcp --url bridges stdio to another viewer; task … --url everywhere (#82)

Qinghe Lic4a45c2c5406
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 97608d9..eb2b5b9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,8 @@ All notable changes to this project are documented here. The format is based on
### Added
+- `iphone-control mcp --url https://<that machine>:8200` bridges stdio to another machine's viewer `/mcp`, so an MCP client that only starts a command can control the phone connected there. With a task's token only that is sent, otherwise the login from `IPHONE_CONTROL_VIEWER_TOKEN`; a command under `task run --url` has `IPHONE_CONTROL_URL` set, so a plain `iphone-control mcp` in it bridges by itself.
+- Every `task` subcommand takes `--url` (or `IPHONE_CONTROL_URL`): `list`, `events`, `pause`, `resume`, `takeover`, `handback`, `stop`, `approve` and `reject` work through another machine's viewer, with the login token in `IPHONE_CONTROL_VIEWER_TOKEN`.
- Named login tokens, read-only ones among them: `iphone-control viewer token add <name> [--read-only]`, `list`, `show <name> [--new]`, `remove <name>`. A read-only token can watch the picture, the device's state and tasks; every action (taps, typing, starting, pausing or confirming tasks, switching devices, `/mcp`) is refused, and the page hides them. The task log records which token controlled it (`viewer:<name>`). Tokens moved to `viewer-tokens.json` and the earlier one became `owner`, so nobody logs in again after upgrading; adding, replacing and removing tokens takes effect at once, without restarting the viewer.
- Tasks opened from another machine: `iphone-control task run --url https://<that machine>:8200 -- <command>` (the login token in `IPHONE_CONTROL_VIEWER_TOKEN`), or `POST /api/agent/tasks/open` directly, whose event stream is the lease. The agent on the other machine gets only the task's token: `/mcp` takes the token of an active task (header `Iphone-Control-Task-Token`), so it can act on the phone for that task but can't reach pausing or confirming, and can't approve itself.
- The viewer and its `/mcp` need a login, from this machine too (the viewer can't tell a local browser from a visit forwarded by frp, cloudflared or another reverse proxy). The token is made on the first start and kept in `viewer-token` in the data directory (0600); `iphone-control viewer token` shows it with links that log in here and on the local network and the command to connect to the HTTP MCP, and `--new` replaces it. A browser stays logged in for 30 days; programs and MCP clients send `Authorization: Bearer <token>`. After too many wrong tokens (20 in a minute) tokens aren't checked for a minute. The CLI, `iphone-control mcp` (stdio) and `task run` use the local Unix socket and are unaffected.
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index 1634326..38c571a 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -8,6 +8,8 @@
### 新增
+- `iphone-control mcp --url https://<那台机器>:8200`:把 stdio 转到另一台机器控制台的 `/mcp`,只能填命令的 MCP 客户端也能操作接在那台机器上的手机。有任务口令就只带它,否则用 `IPHONE_CONTROL_VIEWER_TOKEN` 登录;`task run --url` 启动的命令已经设好 `IPHONE_CONTROL_URL`,里面照常配置的 `iphone-control mcp` 自动转接。
+- `task` 的所有子命令都能加 `--url`(或设 `IPHONE_CONTROL_URL`):`list`、`events`、`pause`、`resume`、`takeover`、`handback`、`stop`、`approve`、`reject` 经另一台机器的控制台操作,登录令牌放在 `IPHONE_CONTROL_VIEWER_TOKEN`。
- 有名字的登录令牌,可以是只读的:`iphone-control viewer token add <名字> [--read-only]`、`list`、`show <名字> [--new]`、`remove <名字>`。只读令牌能看画面、设备状态和任务,所有操作(点按、输入、开任务、暂停、确认、切换设备、`/mcp`)都被拒绝,页面上也不显示操作入口。任务记录里写下是哪个令牌做的控制(`viewer:<名字>`)。令牌改存在 `viewer-tokens.json`,原来的令牌成了 `owner`,升级后不用重新登录;增删、换令牌马上生效,不用重启控制台。
- 从另一台机器开任务:`iphone-control task run --url https://<那台机器>:8200 -- <命令>`(登录令牌放在 `IPHONE_CONTROL_VIEWER_TOKEN`),或者直接调 `POST /api/agent/tasks/open`,返回的事件流就是租约。另一台机器上的 agent 只拿任务口令:`/mcp` 认进行中任务的口令(请求头 `Iphone-Control-Task-Token`),它能为这个任务操作手机,但碰不到暂停、确认这些控制接口,不能批准自己。
- 控制台和它的 `/mcp` 要登录了,本机也一样(控制台分不清本机的浏览器和经 frp、cloudflared 等反向代理转发进来的访问)。令牌第一次启动时生成,存在数据目录的 `viewer-token`(0600);`iphone-control viewer token` 显示令牌、本机和局域网的登录链接以及接入 HTTP MCP 的命令,`--new` 换一个新令牌。浏览器登录一次后记住 30 天;程序和 MCP 客户端用 `Authorization: Bearer <令牌>`。输错太多次(一分钟 20 次)会暂停校验一分钟。命令行、`iphone-control mcp`(stdio)和 `task run` 走本机的 Unix socket,不受影响。
diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rs
index 030b41e..1432630 100644
--- a/apps/iphone-control/src/main.rs
+++ b/apps/iphone-control/src/main.rs
@@ -19,6 +19,8 @@ mod completions;
mod debug;
mod envfile;
mod guide;
+mod mcp_bridge;
+mod remote;
mod schedule;
mod service;
mod task;
@@ -57,8 +59,13 @@ enum Command {
},
#[command(about = ictl_l10n::tr!("常驻守护进程(安装时装成用户服务:macOS 是 launchd,Linux 是 systemd;也可以手动启动)", "The long-running daemon (installed as a user service: launchd on macOS, systemd on Linux; can also be started by hand)"))]
Daemon,
- #[command(about = ictl_l10n::tr!("MCP stdio 服务(由 agent 拉起)", "MCP stdio server (started by the agent)"))]
- Mcp,
+ #[command(about = ictl_l10n::tr!("MCP stdio 服务(由 agent 拉起)。--url(或 IPHONE_CONTROL_URL)时转接另一台机器的控制台 /mcp:给只能填命令的 MCP 客户端用", "MCP stdio server (started by the agent). With --url (or IPHONE_CONTROL_URL), a bridge to another machine's viewer /mcp, for MCP clients that only start a command"))]
+ Mcp {
+ #[arg(long, value_name = "URL", env = "IPHONE_CONTROL_URL", help = ictl_l10n::tr!("手机接在另一台机器上:那台机器的控制台地址。有任务口令(IPHONE_CONTROL_TASK_TOKEN)就只带它,否则用 IPHONE_CONTROL_VIEWER_TOKEN 登录;task run --url 启动的命令会自动设好", "The phone is on another machine: that machine's viewer. With a task's token (IPHONE_CONTROL_TASK_TOKEN) only that is sent, otherwise the login from IPHONE_CONTROL_VIEWER_TOKEN; a command under task run --url has it set already"))]
+ url: Option<String>,
+ #[arg(long, value_name = "PEM", env = "IPHONE_CONTROL_CA", help = ictl_l10n::tr!("--url 是本机生成的自签证书时,信任这张证书", "With --url and a self-signed certificate: trust it"))]
+ ca: Option<PathBuf>,
+ },
#[command(about = ictl_l10n::tr!("打印把 MCP 注册到 Claude Code 的命令", "Print the command that registers the MCP server with Claude Code"))]
McpConfig,
#[command(about = ictl_l10n::tr!("守护进程和设备状态、最近的日志", "Daemon and device state, recent log"))]
@@ -129,6 +136,10 @@ enum Command {
},
#[command(about = ictl_l10n::tr!("AI 任务:在任务里运行外部 agent(task run),查看、暂停、接管、停止、确认任务", "AI tasks: run an external agent in a task (task run); list, pause, take over, stop and confirm tasks"))]
Task {
+ #[arg(long, global = true, value_name = "URL", env = "IPHONE_CONTROL_URL", help = ictl_l10n::tr!("手机接在另一台机器上:那台机器的控制台地址,比如 https://192.168.1.5:8200;登录令牌放在 IPHONE_CONTROL_VIEWER_TOKEN 里(task finish 用任务口令)", "The phone is on another machine: that machine's viewer, such as https://192.168.1.5:8200; the login token goes in IPHONE_CONTROL_VIEWER_TOKEN (task finish uses the task's token)"))]
+ url: Option<String>,
+ #[arg(long, global = true, value_name = "PEM", env = "IPHONE_CONTROL_CA", help = ictl_l10n::tr!("--url 是本机生成的自签证书时,信任这张证书(那台机器上的 viewer-tls/cert.pem)", "With --url and a self-signed certificate made there: trust it (viewer-tls/cert.pem on that machine)"))]
+ ca: Option<PathBuf>,
#[command(subcommand)]
action: task::TaskAction,
},
@@ -272,7 +283,7 @@ fn prints_and_exits(command: Option<&Command>) -> bool {
| Command::NotifyTest { .. }
| Command::Update { action: Some(UpdateAction::Check { .. }), .. }
)
- ) || matches!(command, Some(Command::Task { action }) if task::prints_and_exits(action))
+ ) || matches!(command, Some(Command::Task { action, .. }) if task::prints_and_exits(action))
}
/// Rust starts every program with SIGPIPE ignored, so once the reader of stdout has gone (`iphone-control status |
@@ -295,7 +306,7 @@ async fn run() -> anyhow::Result<()> {
if prints_and_exits(cli.command.as_ref()) {
restore_sigpipe();
}
- let quiet = matches!(cli.command, Some(Command::Mcp));
+ let quiet = matches!(cli.command, Some(Command::Mcp { .. }));
// ICTL_LOG 留空(配置文件里常见的 `ICTL_LOG=`)当作没设;原来空值会生成一个什么都不放行的过滤器
let filter =
env_nonempty("ICTL_LOG").and_then(|v| tracing_subscriber::EnvFilter::try_new(v).ok()).unwrap_or_else(|| {
@@ -329,7 +340,8 @@ async fn run() -> anyhow::Result<()> {
cfg.socket = cli.socket;
ictl_daemon::run(cfg).await
}
- Command::Mcp => ictl_mcp::serve_stdio(cli.socket).await,
+ Command::Mcp { url: Some(url), ca } => mcp_bridge::run(&url, ca.as_deref()).await,
+ Command::Mcp { url: None, .. } => ictl_mcp::serve_stdio(cli.socket).await,
Command::McpConfig => {
println!("{}", mcp_config(&cli.socket)?);
Ok(())
@@ -356,7 +368,7 @@ async fn run() -> anyhow::Result<()> {
None => viewer::run(&cli.socket, &cli.data_dir, port, lan, &lan_hosts, &tls, mcp).await,
}
}
- Command::Task { action } => task::run(&cli.socket, action).await,
+ Command::Task { url, ca, action } => task::run(&cli.socket, url, ca, action).await,
#[cfg(feature = "debug-cmds")]
Command::Debug(args) => debug::run(env_nonempty("IPHONE_UDID").as_deref(), args).await,
Command::NotifyTest { event } => notify_test(&cli.data_dir, event.as_deref()).await,
@@ -1399,6 +1411,32 @@ mod tests {
/// The viewer's settings come from the settings file as environment variables (also for the viewer service):
/// `IPHONE_CONTROL_VIEWER_LAN=1` turns `--lan` on. A plain flag only took true/false, so the service didn't start
+ /// `--url` anywhere in `task …`, or from IPHONE_CONTROL_URL (which `task run --url` gives its command), and for
+ /// `mcp`
+ #[test]
+ fn the_remote_viewer_from_a_flag_or_the_environment() {
+ use clap::Parser;
+ let task = |args: &[&str]| match super::Cli::try_parse_from(args).unwrap().command {
+ Some(super::Command::Task { url, .. }) => url,
+ _ => panic!("not task"),
+ };
+ let mcp = |args: &[&str]| match super::Cli::try_parse_from(args).unwrap().command {
+ Some(super::Command::Mcp { url, .. }) => url,
+ _ => panic!("not mcp"),
+ };
+ // SAFETY: only this test sets this variable
+ unsafe { std::env::remove_var("IPHONE_CONTROL_URL") };
+ assert_eq!(task(&["i", "task", "pause", "abc"]), None);
+ assert_eq!(mcp(&["i", "mcp"]), None, "the local stdio server, as before");
+ assert_eq!(task(&["i", "task", "--url", "https://a:1", "pause", "abc"]).as_deref(), Some("https://a:1"));
+ assert_eq!(task(&["i", "task", "approve", "abc", "--url", "https://a:1"]).as_deref(), Some("https://a:1"));
+ assert_eq!(mcp(&["i", "mcp", "--url", "https://a:1"]).as_deref(), Some("https://a:1"));
+ unsafe { std::env::set_var("IPHONE_CONTROL_URL", "https://b:2") };
+ assert_eq!(task(&["i", "task", "finish", "done"]).as_deref(), Some("https://b:2"));
+ assert_eq!(mcp(&["i", "mcp"]).as_deref(), Some("https://b:2"));
+ unsafe { std::env::remove_var("IPHONE_CONTROL_URL") };
+ }
+
#[test]
fn token_names_line_up_in_columns() {
assert_eq!(super::pad("owner", 8), "owner ");
diff --git a/apps/iphone-control/src/mcp_bridge.rs b/apps/iphone-control/src/mcp_bridge.rs
new file mode 100644
index 0000000..16d51e0
--- /dev/null
+++ b/apps/iphone-control/src/mcp_bridge.rs
@@ -0,0 +1,200 @@
+//! `iphone-control mcp --url`: the MCP server of another machine's viewer, for clients that only start a command
+//! (docs/task-control.md 7.7).
+//!
+//! Stdio on this side, the viewer's `/mcp` (Streamable HTTP) on the other: each JSON-RPC message read from stdin is
+//! posted there, and what comes back (a JSON body, or server-sent events) is written to stdout, one message a line.
+//! Requests go out at once and side by side (a tool call may wait for the user a long time); notifications and the
+//! answers to the server's own requests go in order, so `notifications/initialized` reaches the server before the
+//! next request. The session id and protocol version from `initialize` go along with every message after it, and
+//! the session is ended when stdin closes.
+//!
+//! The address comes from `--url` or `IPHONE_CONTROL_URL`, which `task run --url` gives its command: an agent set
+//! up with plain `iphone-control mcp` then works for its task on the other machine without changing anything. With
+//! a task's token (`IPHONE_CONTROL_TASK_TOKEN`) only that goes along, so the agent can't control its task;
+//! otherwise the login from `IPHONE_CONTROL_VIEWER_TOKEN`.
+
+use std::path::Path;
+use std::sync::{Arc, Mutex};
+
+use ictl_daemon::protocol;
+use serde_json::{Value, json};
+use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncWrite, AsyncWriteExt};
+use tokio::sync::mpsc::UnboundedSender;
+
+use crate::remote::{self, Remote};
+
+/// `iphone-control mcp --url <viewer>` on stdin and stdout
+pub async fn run(url: &str, ca: Option<&Path>) -> anyhow::Result<()> {
+ let task = std::env::var(protocol::TASK_TOKEN_ENV).ok().filter(|t| !t.trim().is_empty());
+ // working for a task: only its token, never the login (which could control the task)
+ let login = match task {
+ Some(_) => None,
+ None => Some(Remote::login_from_env()?),
+ };
+ let remote = Remote::new(url, ca, login)?;
+ bridge(remote, task, tokio::io::BufReader::new(tokio::io::stdin()), tokio::io::stdout()).await
+}
+
+/// What `initialize` set up, for the messages after it
+#[derive(Default)]
+struct Session {
+ id: Option<String>,
+ version: Option<String>,
+}
+
+/// One MCP client's messages from `input` to the viewer, and its answers to `output`, until `input` ends
+pub async fn bridge<R, W>(remote: Remote, task: Option<String>, input: R, output: W) -> anyhow::Result<()>
+where
+ R: AsyncBufRead + Unpin,
+ W: AsyncWrite + Unpin + Send + 'static,
+{
+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<String>();
+ // one writer: lines from requests answered side by side never mix
+ let writer = tokio::spawn(async move {
+ let mut out = output;
+ while let Some(line) = rx.recv().await {
+ out.write_all(line.as_bytes()).await?;
+ out.write_all(b"\n").await?;
+ out.flush().await?;
+ }
+ anyhow::Ok(())
+ });
+ let link = Arc::new(Link { remote, task, session: Mutex::default(), tx });
+ let mut requests = tokio::task::JoinSet::new();
+ let mut lines = input.lines();
+ while let Some(line) = lines.next_line().await? {
+ if line.trim().is_empty() {
+ continue;
+ }
+ let msg: Value = match serde_json::from_str(&line) {
+ Ok(v) => v,
+ Err(e) => {
+ let _ = link.tx.send(rpc_error(Value::Null, -32700, &format!("parse error: {e}")));
+ continue;
+ }
+ };
+ let request = msg.get("method").is_some() && msg.get("id").is_some_and(|i| !i.is_null());
+ // `initialize` first and alone: what follows needs its session
+ if request && msg["method"] != "initialize" {
+ let link = link.clone();
+ requests.spawn(async move { link.forward(msg).await });
+ } else {
+ link.forward(msg).await;
+ }
+ while requests.try_join_next().is_some() {}
+ }
+ // the client is done: what it still waited for goes with it
+ requests.abort_all();
+ link.end().await;
+ drop(link);
+ writer.await??;
+ Ok(())
+}
+
+struct Link {
+ remote: Remote,
+ task: Option<String>,
+ session: Mutex<Session>,
+ tx: UnboundedSender<String>,
+}
+
+impl Link {
+ fn session(&self) -> std::sync::MutexGuard<'_, Session> {
+ self.session.lock().unwrap_or_else(|p| p.into_inner())
+ }
+
+ fn with_headers(&self, mut r: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
+ if let Some(t) = &self.task {
+ r = r.header(protocol::TASK_TOKEN_HEADER, t);
+ }
+ let s = self.session();
+ if let Some(id) = &s.id {
+ r = r.header("mcp-session-id", id);
+ }
+ if let Some(v) = &s.version {
+ r = r.header("mcp-protocol-version", v);
+ }
+ r
+ }
+
+ /// Sends one message; a request that fails gets a JSON-RPC error, so the client doesn't wait for ever
+ async fn forward(&self, msg: Value) {
+ let id = msg.get("method").and(msg.get("id")).cloned().filter(|i| !i.is_null());
+ if let Err(e) = self.send(&msg, id.as_ref()).await {
+ match id {
+ Some(id) => {
+ let _ = self.tx.send(rpc_error(id, -32603, &e));
+ }
+ // a notification has nobody to tell but the log (stdout is the protocol)
+ None => eprintln!("iphone-control mcp --url: {e}"),
+ }
+ }
+ }
+
+ async fn send(&self, msg: &Value, id: Option<&Value>) -> Result<(), String> {
+ let r = self.remote.request(reqwest::Method::POST, "/mcp");
+ let r = self.with_headers(r).header(reqwest::header::ACCEPT, "application/json, text/event-stream").json(msg);
+ let resp = r.send().await.map_err(|e| format!("{}: {e}", self.remote.base()))?;
+ if let Some(sid) = resp.headers().get("mcp-session-id").and_then(|v| v.to_str().ok()) {
+ self.session().id = Some(sid.to_owned());
+ }
+ if resp.status() == reqwest::StatusCode::ACCEPTED {
+ return Ok(());
+ }
+ if !resp.status().is_success() {
+ return Err(remote::failure(resp).await);
+ }
+ let initialize = msg["method"] == "initialize";
+ let pass = |v: Value| {
+ if initialize && let Some(version) = v["result"]["protocolVersion"].as_str() {
+ self.session().version = Some(version.to_owned());
+ }
+ let answered = id.is_some_and(|id| v.get("id") == Some(id) && v.get("method").is_none());
+ let _ = self.tx.send(v.to_string());
+ answered
+ };
+ let sse = resp
+ .headers()
+ .get(reqwest::header::CONTENT_TYPE)
+ .and_then(|v| v.to_str().ok())
+ .is_some_and(|c| c.starts_with("text/event-stream"));
+ if sse {
+ let mut events = remote::Events::new(resp);
+ while let Some((_, data)) = events.next_raw().await {
+ // the answer to this request ends it; what came before (progress, the server's requests) went too
+ if let Ok(v) = serde_json::from_str::<Value>(&data)
+ && pass(v)
+ {
+ break;
+ }
+ }
+ return Ok(());
+ }
+ let text = resp.text().await.map_err(|e| e.to_string())?;
+ if text.trim().is_empty() {
+ return Ok(());
+ }
+ match serde_json::from_str::<Value>(&text).map_err(|e| e.to_string())? {
+ Value::Array(batch) => batch.into_iter().for_each(|v| {
+ pass(v);
+ }),
+ v => {
+ pass(v);
+ }
+ }
+ Ok(())
+ }
+
+ /// Ends the session on the viewer (best effort)
+ async fn end(&self) {
+ if self.session().id.is_none() {
+ return;
+ }
+ let r = self.with_headers(self.remote.request(reqwest::Method::DELETE, "/mcp"));
+ let _ = r.timeout(std::time::Duration::from_secs(3)).send().await;
+ }
+}
+
+fn rpc_error(id: Value, code: i64, message: &str) -> String {
+ json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}}).to_string()
+}
diff --git a/apps/iphone-control/src/task/remote.rs b/apps/iphone-control/src/remote.rs
similarity index 62%
rename from apps/iphone-control/src/task/remote.rs
rename to apps/iphone-control/src/remote.rs
index 4d12fe1..34e2186 100644
--- a/apps/iphone-control/src/task/remote.rs
+++ b/apps/iphone-control/src/remote.rs
@@ -1,15 +1,17 @@
-//! `task run --url`: a task on another machine's phone, through its viewer (docs/task-control.md 7.6).
+//! Another machine's viewer, for the phone connected there (docs/task-control.md 7.6, 7.7): `task … --url` and
+//! `mcp --url`.
//!
-//! The viewer's `POST /api/agent/tasks/open` opens the task and keeps answering with its events (server-sent
-//! events); that response is the lease, as the socket's connection is for `task run` on the same machine. This side
-//! logs in with `IPHONE_CONTROL_VIEWER_TOKEN` (a token that may operate) and keeps it: the command only gets the
-//! task's token, with the viewer's address, so the agent can use `/mcp` for its task but can't control it.
+//! `task run --url`: the viewer's `POST /api/agent/tasks/open` opens the task and keeps answering with its events
+//! (server-sent events); that response is the lease, as the socket's connection is for `task run` on the same
+//! machine. This side logs in with `IPHONE_CONTROL_VIEWER_TOKEN` (a token that may operate) and keeps it: the command
+//! only gets the task's token, with the viewer's address, so the agent can use `/mcp` for its task but can't control
+//! it. The other `task` subcommands list, follow and steer tasks through the same viewer with that login.
use std::path::{Path, PathBuf};
use std::time::Duration;
use anyhow::{Context, bail};
-use ictl_daemon::protocol::{TaskEvent, TaskOpened};
+use ictl_daemon::protocol::{TaskEvent, TaskInfo, TaskOpened};
use serde_json::{Value, json};
/// The viewer's login token for `task run --url`
@@ -53,13 +55,6 @@ impl Remote {
Ok(Self { client: b.build()?, base, ca: ca.map(Path::to_owned), login })
}
- /// From inside a command `task run --url` started (its environment), with the task's token only
- pub fn from_env() -> Option<anyhow::Result<Self>> {
- let url = std::env::var(URL_ENV).ok().filter(|u| !u.is_empty())?;
- let ca = std::env::var_os(CA_ENV).filter(|c| !c.is_empty()).map(PathBuf::from);
- Some(Self::new(&url, ca.as_deref(), None))
- }
-
/// The login token for opening and controlling tasks
pub fn login_from_env() -> anyhow::Result<String> {
std::env::var(LOGIN_ENV).ok().filter(|t| !t.trim().is_empty()).map(|t| t.trim().to_owned()).with_context(|| {
@@ -79,14 +74,55 @@ impl Remote {
v
}
- fn post(&self, path: &str, body: &Value) -> reqwest::RequestBuilder {
- let r = self.client.post(format!("{}{path}", self.base)).json(body);
+ /// A request to `path` on the viewer, with the login if there is one
+ pub fn request(&self, method: reqwest::Method, path: &str) -> reqwest::RequestBuilder {
+ let r = self.client.request(method, format!("{}{path}", self.base));
match &self.login {
Some(t) => r.bearer_auth(t),
None => r,
}
}
+ fn post(&self, path: &str, body: &Value) -> reqwest::RequestBuilder {
+ self.request(reqwest::Method::POST, path).json(body)
+ }
+
+ /// The viewer's address, for messages
+ pub fn base(&self) -> &str {
+ &self.base
+ }
+
+ /// Recent tasks, as `task_list` on the socket
+ pub async fn list(&self) -> anyhow::Result<Vec<TaskInfo>> {
+ let r = self.request(reqwest::Method::GET, "/api/agent/tasks").timeout(Duration::from_secs(15));
+ let r = r.send().await.with_context(|| self.base.clone())?;
+ if !r.status().is_success() {
+ bail!("{}", failure(r).await);
+ }
+ let v: Value = r.json().await?;
+ Ok(serde_json::from_value(v["tasks"].clone())?)
+ }
+
+ /// A task's events so far, then new ones until it ends
+ pub async fn events(&self, id: &str) -> anyhow::Result<Events> {
+ let r = self.request(reqwest::Method::GET, &format!("/api/agent/tasks/{id}/events"));
+ let resp = r.send().await.with_context(|| self.base.clone())?;
+ if !resp.status().is_success() {
+ bail!("{}", failure(resp).await);
+ }
+ Ok(Events::new(resp))
+ }
+
+ /// `pause`, `resume`, `takeover`, `handback`, `stop`, `confirm` (`body`: `{step, approve}`)
+ pub async fn control(&self, id: &str, action: &str, body: &Value) -> anyhow::Result<()> {
+ let r = self.post(&format!("/api/agent/tasks/{id}/{action}"), body).timeout(Duration::from_secs(15));
+ let r = r.send().await.with_context(|| self.base.clone())?;
+ if !r.status().is_success() {
+ bail!("{}", failure(r).await);
+ }
+ Ok(())
+ }
+
/// Opens a task: its id and token, and its events, whose response is the lease
pub async fn open(&self, title: &str, owner: &str, apps: &[String]) -> anyhow::Result<(TaskOpened, Events)> {
let body = json!({"title": title, "owner": owner, "apps": apps});
@@ -94,7 +130,7 @@ impl Remote {
if !resp.status().is_success() {
bail!("{}", failure(resp).await);
}
- let mut events = Events { resp, buf: Vec::new() };
+ let mut events = Events::new(resp);
match events.next().await {
Some(e) if e.event == "opened" => Ok((serde_json::from_value(e.data)?, events)),
_ => bail!(ictl_l10n::tr!("控制台没有开出任务", "The viewer didn't open the task")),
@@ -134,7 +170,7 @@ impl Remote {
}
/// What the viewer said when it refused
-async fn failure(r: reqwest::Response) -> String {
+pub async fn failure(r: reqwest::Response) -> String {
let status = r.status();
let text = r.text().await.unwrap_or_default();
let message = serde_json::from_str::<Value>(&text).ok().and_then(|v| v["message"].as_str().map(str::to_owned));
@@ -153,12 +189,29 @@ pub struct Events {
}
impl Events {
+ pub fn new(resp: reqwest::Response) -> Self {
+ Self { resp, buf: Vec::new() }
+ }
+
/// The next event; `None` when the response ended (the task ended, or the viewer went away)
pub async fn next(&mut self) -> Option<TaskEvent> {
loop {
- if let Some(i) = self.buf.windows(2).position(|w| w == b"\n\n") {
- let block: Vec<u8> = self.buf.drain(..i + 2).collect();
- if let Some(e) = parse_event(&String::from_utf8_lossy(&block)) {
+ let (event, data) = self.next_raw().await?;
+ if let Some(e) = event.and_then(|event| Some(TaskEvent { event, data: serde_json::from_str(&data).ok()? }))
+ {
+ return Some(e);
+ }
+ }
+ }
+
+ /// The next event with data, as it came: its name if it had one, and its data
+ pub async fn next_raw(&mut self) -> Option<(Option<String>, String)> {
+ loop {
+ // events end with a blank line (CRLF too). Found in the bytes: a chunk may end inside a character
+ if let Some((end, next)) = event_end(&self.buf) {
+ let block = String::from_utf8_lossy(&self.buf[..end]).replace("\r\n", "\n");
+ self.buf.drain(..next);
+ if let Some(e) = parse_block(&block) {
return Some(e);
}
continue;
@@ -171,8 +224,19 @@ impl Events {
}
}
-/// One server-sent event (`event:` and `data:` lines); comments (`: ping`) and malformed ones are `None`
-fn parse_event(block: &str) -> Option<TaskEvent> {
+/// Where the first event in `buf` ends, and where the next one starts
+fn event_end(buf: &[u8]) -> Option<(usize, usize)> {
+ let lf = buf.windows(2).position(|w| w == b"\n\n").map(|i| (i, i + 2));
+ let crlf = buf.windows(4).position(|w| w == b"\r\n\r\n").map(|i| (i, i + 4));
+ match (lf, crlf) {
+ (Some(a), Some(b)) => Some(if a.0 <= b.0 { a } else { b }),
+ (a, b) => a.or(b),
+ }
+}
+
+/// One server-sent event: its `event:` name and `data:` lines; `None` for one without data (comments such as
+/// `: ping`, a `retry:` alone)
+fn parse_block(block: &str) -> Option<(Option<String>, String)> {
let (mut event, mut data) = (None, Vec::new());
for line in block.lines() {
if let Some(v) = line.strip_prefix("event:") {
@@ -181,7 +245,15 @@ fn parse_event(block: &str) -> Option<TaskEvent> {
data.push(v.strip_prefix(' ').unwrap_or(v));
}
}
- Some(TaskEvent { event: event?, data: serde_json::from_str(&data.join("\n")).ok()? })
+ let data = data.join("\n");
+ (!data.trim().is_empty()).then_some((event, data))
+}
+
+/// One task event (named, with JSON data); `None` otherwise
+#[cfg(test)]
+fn parse_event(block: &str) -> Option<TaskEvent> {
+ let (event, data) = parse_block(block)?;
+ Some(TaskEvent { event: event?, data: serde_json::from_str(&data).ok()? })
}
#[cfg(test)]
@@ -196,6 +268,12 @@ mod tests {
let e = parse_event("event: step\ndata:{\"id\":1}\n").unwrap();
assert_eq!(e.data["id"], 1);
assert!(parse_event("data: {}\n\n").is_none(), "no event name");
+ // MCP over HTTP: events without a name, priming ones without data
+ assert_eq!(parse_block("id: 1\nretry: 3000\ndata:\n"), None);
+ assert_eq!(parse_block("data: {\"id\":1}"), Some((None, "{\"id\":1}".into())));
+ assert_eq!(event_end(b"data: 1\r\n\r\ndata: 2\n\n"), Some((7, 11)));
+ assert_eq!(event_end(b"data: 1\n\ndata: 2\r\n\r\n"), Some((7, 9)));
+ assert_eq!(event_end("data: \"设".as_bytes()), None, "not yet");
}
#[test]
diff --git a/apps/iphone-control/src/task.rs b/apps/iphone-control/src/task.rs
index 1b0c94b..bc182b0 100644
--- a/apps/iphone-control/src/task.rs
+++ b/apps/iphone-control/src/task.rs
@@ -8,16 +8,18 @@
//! status; when the task ends elsewhere (stopped on the page, the phone changed), the command is stopped. Ctrl-C
//! stops the task. The other subcommands follow and steer tasks, whoever started them.
//!
-//! `task run --url <viewer>` does the same for a phone on another machine, through its viewer ([`remote`]).
+//! With `--url <viewer>` (or `IPHONE_CONTROL_URL`) every subcommand works on a phone on another machine, through
+//! its viewer ([`remote`]).
-mod remote;
-
-use std::path::{Path, PathBuf};
+use std::path::Path;
use std::time::Duration;
use anyhow::{Context, bail};
use clap::Subcommand;
use ictl_daemon::protocol::{self, Request, Response};
+use serde_json::json;
+
+use crate::remote;
#[derive(Subcommand)]
pub enum TaskAction {
@@ -29,10 +31,6 @@ pub enum TaskAction {
owner: String,
#[arg(long = "app", value_name = "APP", help = ictl_l10n::tr!("任务只在这些 App 里操作(App 名或 Bundle ID,可以写多次);到了别的 App 每一步都先等你确认。不写就不限制", "Limit the task to these apps (name or bundle ID, repeatable); in any other app each step waits for you first. No limit if not given"))]
apps: Vec<String>,
- #[arg(long, value_name = "URL", help = ictl_l10n::tr!("手机接在另一台机器上:那台机器的控制台地址,比如 https://192.168.1.5:8200。登录令牌放在环境变量 IPHONE_CONTROL_VIEWER_TOKEN 里;命令拿到的是 IPHONE_CONTROL_MCP_URL 和任务口令,agent 用 HTTP 方式的 MCP 接入", "The phone is on another machine: that machine's viewer, such as https://192.168.1.5:8200. The login token goes in IPHONE_CONTROL_VIEWER_TOKEN; the command gets IPHONE_CONTROL_MCP_URL and the task's token, and its agent connects to MCP over HTTP"))]
- url: Option<String>,
- #[arg(long, value_name = "PEM", requires = "url", help = ictl_l10n::tr!("--url 是本机生成的自签证书时,信任这张证书(那台机器上的 viewer-tls/cert.pem)", "With --url and a self-signed certificate made there: trust it (viewer-tls/cert.pem on that machine)"))]
- ca: Option<PathBuf>,
#[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true)]
command: Vec<String>,
},
@@ -78,7 +76,16 @@ pub fn prints_and_exits(a: &TaskAction) -> bool {
matches!(a, TaskAction::List { .. } | TaskAction::Events { .. })
}
-pub async fn run(socket: &Path, action: TaskAction) -> anyhow::Result<()> {
+/// `url`, `ca`: the viewer of another machine (`--url`, `IPHONE_CONTROL_URL`) instead of the daemon here
+pub async fn run(
+ socket: &Path,
+ url: Option<String>,
+ ca: Option<std::path::PathBuf>,
+ action: TaskAction,
+) -> anyhow::Result<()> {
+ if let Some(url) = url {
+ return run_remote(&url, ca.as_deref(), action).await;
+ }
let control = |id: String, action: &str, step: Option<u64>, approve: bool| Request::TaskControl {
id,
action: action.into(),
@@ -88,14 +95,8 @@ pub async fn run(socket: &Path, action: TaskAction) -> anyhow::Result<()> {
for_pid: None,
};
let req = match action {
- TaskAction::Run { title, owner, apps, url, ca, command } => {
- let backend = match url {
- Some(url) => {
- Backend::Remote(remote::Remote::new(&url, ca.as_deref(), Some(remote::Remote::login_from_env()?))?)
- }
- None => Backend::Local(socket),
- };
- return run_command(&backend, title, &owner, &apps, &command).await;
+ TaskAction::Run { title, owner, apps, command } => {
+ return run_command(&Backend::Local(socket), title, &owner, &apps, &command).await;
}
TaskAction::List { json } => return list(socket, json).await,
TaskAction::Events { id } => {
@@ -109,10 +110,6 @@ pub async fn run(socket: &Path, action: TaskAction) -> anyhow::Result<()> {
let token = std::env::var(protocol::TASK_TOKEN_ENV).ok().filter(|t| !t.is_empty()).with_context(|| {
ictl_l10n::trf!("没有设 {}:不在任务里", "{} isn't set: not inside a task", protocol::TASK_TOKEN_ENV)
})?;
- // under `task run --url`: the phone is on another machine
- if let Some(r) = remote::Remote::from_env() {
- return r?.finish(&token, !failed, &summary.join(" ")).await;
- }
let req = Request::TaskFinish { ok: !failed, summary: summary.join(" ") };
return expect_ok(protocol::as_task(Some(token), None, ask(socket, &req)).await);
}
@@ -147,7 +144,10 @@ fn expect_ok(r: anyhow::Result<Response>) -> anyhow::Result<()> {
}
async fn list(socket: &Path, json: bool) -> anyhow::Result<()> {
- let tasks = protocol::task_list(socket).await.map_err(anyhow::Error::msg)?;
+ print_list(protocol::task_list(socket).await.map_err(anyhow::Error::msg)?, json)
+}
+
+fn print_list(tasks: Vec<protocol::TaskInfo>, json: bool) -> anyhow::Result<()> {
if json {
println!("{}", serde_json::to_string_pretty(&tasks)?);
return Ok(());
@@ -162,6 +162,41 @@ async fn list(socket: &Path, json: bool) -> anyhow::Result<()> {
Ok(())
}
+/// Every subcommand through another machine's viewer: the login (`IPHONE_CONTROL_VIEWER_TOKEN`) for all of them but
+/// `finish`, which is the task's own (its token). In a command `task run --url` started the login isn't there, so
+/// the agent can't pause or confirm its own task, as on this machine
+async fn run_remote(url: &str, ca: Option<&Path>, action: TaskAction) -> anyhow::Result<()> {
+ if let TaskAction::Finish { failed, summary } = &action {
+ let token = std::env::var(protocol::TASK_TOKEN_ENV).ok().filter(|t| !t.is_empty()).with_context(|| {
+ ictl_l10n::trf!("没有设 {}:不在任务里", "{} isn't set: not inside a task", protocol::TASK_TOKEN_ENV)
+ })?;
+ return remote::Remote::new(url, ca, None)?.finish(&token, !failed, &summary.join(" ")).await;
+ }
+ let r = remote::Remote::new(url, ca, Some(remote::Remote::login_from_env()?))?;
+ let (id, action, body) = match action {
+ TaskAction::Run { title, owner, apps, command } => {
+ return run_command(&Backend::Remote(r), title, &owner, &apps, &command).await;
+ }
+ TaskAction::List { json } => return print_list(r.list().await?, json),
+ TaskAction::Events { id } => {
+ let mut events = r.events(&id).await?;
+ while let Some(e) = events.next().await {
+ println!("{}", serde_json::to_string(&e)?);
+ }
+ return Ok(());
+ }
+ TaskAction::Finish { .. } => unreachable!("handled above"),
+ TaskAction::Pause { id } => (id, "pause", json!({})),
+ TaskAction::Resume { id } => (id, "resume", json!({})),
+ TaskAction::Takeover { id } => (id, "takeover", json!({})),
+ TaskAction::Handback { id } => (id, "handback", json!({})),
+ TaskAction::Stop { id } => (id, "stop", json!({})),
+ TaskAction::Approve { id, step } => (id, "confirm", json!({"step": step, "approve": true})),
+ TaskAction::Reject { id, step } => (id, "confirm", json!({"step": step, "approve": false})),
+ };
+ r.control(&id, action, &body).await
+}
+
/// Where `task run` opens its task
enum Backend<'a> {
/// The daemon's socket, on this machine
diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs
index 2aad13d..943ad98 100644
--- a/apps/iphone-control/src/viewer.rs
+++ b/apps/iphone-control/src/viewer.rs
@@ -1597,6 +1597,82 @@ mod tests {
);
}
+ /// `iphone-control mcp --url`: stdio on one side, this viewer's /mcp on the other; with the login, and with a
+ /// task's token alone (which lists the confirm tool)
+ #[tokio::test]
+ async fn a_stdio_client_reaches_mcp_over_http_through_the_bridge() {
+ use tokio::io::{AsyncBufReadExt, BufReader};
+ let temp = tempfile::tempdir_in("/tmp").unwrap();
+ let socket = temp.path().join("daemon.sock");
+ let daemon = tokio::net::UnixListener::bind(&socket).unwrap();
+ // a daemon that knows one active task, with the token `good`
+ tokio::spawn(async move {
+ while let Ok((mut peer, _)) = daemon.accept().await {
+ let mut line = String::new();
+ BufReader::new(&mut peer).read_line(&mut line).await.unwrap();
+ let req: Value = serde_json::from_str(&line).unwrap();
+ let reply = if req["task"] == "good" { Response::text("t1") } else { Response::error("no such task") };
+ let _ = peer.write_all(format!("{}\n", serde_json::to_string(&reply).unwrap()).as_bytes()).await;
+ }
+ });
+ let mut ctx = test_ctx(temp.path(), &socket);
+ let login = "o".repeat(64);
+ let entry = auth::Entry { name: "owner".into(), role: auth::Role::Operate, token: login.clone(), created: 0 };
+ ctx.auth = Some(auth::Auth::fixed(vec![entry], 8202));
+ ctx.mcp = Some(ictl_mcp::http_service(socket.clone()));
+ let ctx = Arc::new(ctx);
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let served = ctx.clone();
+ tokio::spawn(async move {
+ while let Ok((tcp, _)) = listener.accept().await {
+ let ctx = served.clone();
+ tokio::spawn(async move { serve(Conn::Plain(tcp), &ctx).await });
+ }
+ });
+
+ for (login, task, confirm) in [(Some(login), None, false), (None, Some("good".to_owned()), true)] {
+ let remote = crate::remote::Remote::new(&url, None, login).unwrap();
+ let (mut to_bridge, from_client) = tokio::io::duplex(1 << 16);
+ let (to_client, from_bridge) = tokio::io::duplex(1 << 16);
+ let bridge = tokio::spawn(crate::mcp_bridge::bridge(remote, task, BufReader::new(from_client), to_client));
+ let mut answers = BufReader::new(from_bridge).lines();
+ let mut say = async |line: &str| to_bridge.write_all(format!("{line}\n").as_bytes()).await.unwrap();
+ say(r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"t","version":"1"}}}"#).await;
+ let a: Value = serde_json::from_str(&answers.next_line().await.unwrap().unwrap()).unwrap();
+ assert_eq!(a["id"], 1, "{a}");
+ assert!(a["result"]["serverInfo"].is_object(), "{a}");
+ say(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#).await;
+ say(r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#).await;
+ let a: Value = serde_json::from_str(&answers.next_line().await.unwrap().unwrap()).unwrap();
+ let names: Vec<&str> =
+ a["result"]["tools"].as_array().unwrap().iter().filter_map(|t| t["name"].as_str()).collect();
+ assert!(names.contains(&"iphone_tap"), "{names:?}");
+ assert_eq!(names.contains(&"iphone_confirm"), confirm, "the confirm tool only in a task");
+ // a broken line gets an error instead of silence
+ say("not json").await;
+ let a: Value = serde_json::from_str(&answers.next_line().await.unwrap().unwrap()).unwrap();
+ assert_eq!(a["error"]["code"], -32700);
+ drop(to_bridge);
+ bridge.await.unwrap().unwrap();
+ }
+
+ // a wrong login: the request gets an error, not a hang
+ let remote = crate::remote::Remote::new(&url, None, Some("nope".into())).unwrap();
+ let (mut to_bridge, from_client) = tokio::io::duplex(1 << 16);
+ let (to_client, from_bridge) = tokio::io::duplex(1 << 16);
+ let bridge = tokio::spawn(crate::mcp_bridge::bridge(remote, None, BufReader::new(from_client), to_client));
+ to_bridge.write_all(b"{\"jsonrpc\":\"2.0\",\"id\":7,\"method\":\"initialize\",\"params\":{}}\n").await.unwrap();
+ let line = BufReader::new(from_bridge).lines().next_line().await.unwrap().unwrap();
+ let a: Value = serde_json::from_str(&line).unwrap();
+ assert!(
+ a["id"] == 7 && a["error"]["message"].as_str().is_some_and(|m| m.contains("登录") || m.contains("login")),
+ "{a}"
+ );
+ drop(to_bridge);
+ bridge.await.unwrap().unwrap();
+ }
+
#[test]
fn plain_http_from_the_network_goes_to_the_same_page_over_https() {
let at = |raw: &[u8]| https_location(raw, &Head::parse(raw).unwrap(), 8202);
diff --git a/docs/task-control.md b/docs/task-control.md
index 43fbeb4..216bdc9 100644
--- a/docs/task-control.md
+++ b/docs/task-control.md
@@ -136,7 +136,8 @@ Running → Waiting(等确认)→ Running
| 四 | HTTP MCP(7.4) | 已完成(2026-11-13) |
| 四 | 登录(7.5,一个令牌) | 已完成(2026-11-13) |
| 四 | 有名字的令牌和只读令牌、跨主机开任务(7.6) | 已完成(2026-11-13) |
-| 四 | 远端 stdio MCP 转接、多设备租约 | 等需要时 |
+| 四 | 远端 stdio 转接、`task --url`(7.7) | 已完成(2026-11-13) |
+| 四 | 更细的权限、多设备租约 | 等需要时 |
## 5. 阶段一的具体设计
@@ -318,4 +319,11 @@ Running → Waiting(等确认)→ Running
- `POST /api/agent/tasks/open`(能操作的令牌,`{title, owner?, apps?}`):控制台替平台在守护进程的 socket 上 `task_open`,把 `{id, token}` 作为第一条 `opened` 事件发回,之后转发任务事件。这个 HTTP 响应就是租约:客户端断开,控制台丢掉 socket 上的租约,任务记为 abandoned。和本机一样不用心跳;每 15 秒一条注释防代理掐断空闲连接。控制台重启时这些任务也会中断。
- **执行和控制分开**:平台留着登录令牌(控制方:`/api/agent/tasks/<id>/<动作>`),只把任务口令交给 agent(执行方)。`/mcp` 和 `POST /api/agent/tasks/finish` 认进行中任务的口令(请求头 `Iphone-Control-Task-Token`,控制台用新的守护进程请求 `task_check` 核对),别的路径不认。所以远端 agent 能为任务操作手机、结束任务,碰不到暂停、继续、接管、确认。这是 5.6 的进程检查在跨主机时做不到的部分;错的任务口令和错的登录令牌一起计入限速。
- `task run --url <控制台> [--ca <证书>]`:登录令牌从 `IPHONE_CONTROL_VIEWER_TOKEN` 读,**不传给命令**(启动前从环境里去掉);命令拿到 `IPHONE_CONTROL_TASK_TOKEN`、`IPHONE_CONTROL_TASK_ID`、`IPHONE_CONTROL_URL`、`IPHONE_CONTROL_MCP_URL`(和 `IPHONE_CONTROL_CA`)。命令里的 `task finish` 看到 `IPHONE_CONTROL_URL` 就经控制台结束任务。其余行为(Ctrl-C 停止、命令结束任务结束、在别处停止时停掉命令、`task finish` 后给 5 秒退出)和本机一样。
-- **局限**:stdio 方式的 MCP 客户端在远端还用不了(要有一个 stdio 到 HTTP 的转接,比如以后的 `iphone-control mcp --url`);同一个控制台上的令牌都是全权或只读,还没有「只能开任务」这类更细的权限。
+- **局限**:同一个控制台上的令牌都是全权或只读,还没有「只能开任务」这类更细的权限。远端的 stdio 客户端和其他 `task` 命令见 7.7。
+
+### 7.7 远端的 stdio 转接和 `task --url`(2026-11-13)
+
+- **`iphone-control mcp --url <控制台> [--ca <证书>]`**:stdin/stdout 上是 MCP(每行一条 JSON-RPC),另一边是控制台的 `/mcp`(Streamable HTTP)。在 JSON-RPC 这一层转发,不用 rmcp 的 HTTP 客户端(免得多带一个 reqwest 版本):每条消息 POST 过去,回来的 JSON 或 SSE(收到这个请求的回复就停)写回 stdout;`initialize` 单独先发,之后带上它给的 `Mcp-Session-Id` 和协议版本;请求并发(工具调用可能等人很久),通知和对服务端请求的回复按顺序发(`notifications/initialized` 先到);HTTP 出错时给这条请求回一个 JSON-RPC 错误,客户端不会一直等;stdin 关了就 `DELETE` 会话。
+- **凭据**:有 `IPHONE_CONTROL_TASK_TOKEN` 就只带任务口令(不带登录,所以不能控制任务),否则用 `IPHONE_CONTROL_VIEWER_TOKEN` 登录。`--url` 默认取 `IPHONE_CONTROL_URL`、`--ca` 取 `IPHONE_CONTROL_CA`,正是 `task run --url` 给命令设的:里面的 agent 照常配置 `iphone-control mcp`,不用改。
+- **`task … --url`**:`--url`、`--ca` 放到 `task` 这一层(各子命令都能写,也从 `IPHONE_CONTROL_URL`、`IPHONE_CONTROL_CA` 取)。`list`、`events`、各种控制经控制台的 `GET /api/agent/tasks`、`GET /api/agent/tasks/<id>/events`、`POST /api/agent/tasks/<id>/<动作>`,用登录令牌;`finish` 用任务口令。`task run --url` 启动的命令有 `IPHONE_CONTROL_URL` 但没有登录令牌,所以 agent 在里面执行 `task approve` 之类会在本地就失败,即使绕过去也会被控制台 401。
+- **SSE 解析**:在字节里找事件边界(`\n\n` 或 `\r\n\r\n`),再把完整的事件转成文字,免得一块数据断在中文字符中间。
diff --git a/tests/device/tasks.py b/tests/device/tasks.py
index 8b8366a..b2ddfd3 100644
--- a/tests/device/tasks.py
+++ b/tests/device/tasks.py
@@ -527,6 +527,17 @@ async def remote(stack):
data.append(line[5:].lstrip())
return None, None
+ url = ["--url", VIEWER] + (["--ca", ca] if ca else [])
+ # the platform's command line (the login) and the agent's shell (the task's token and the address, no login)
+ platform_env = {k: v for k, v in os.environ.items() if k not in (TOKEN_ENV, "ICTL_VIEWER_TOKEN")}
+ platform_env["IPHONE_CONTROL_VIEWER_TOKEN"] = login
+
+ async def rcli(*args, env=None):
+ p = await asyncio.create_subprocess_exec(*BIN, "task", *args, *url, env=env or platform_env,
+ stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT)
+ out, _ = await asyncio.wait_for(p.communicate(), 30)
+ return p.returncode, out.decode(errors="replace").strip()
+
name, opened = await asyncio.wait_for(next_event(), 30)
check(c, "the platform opens a task over HTTP (server-sent events)", resp.status_code == 200 and name == "opened",
f"{resp.status_code} {name}")
@@ -558,6 +569,19 @@ async def remote(stack):
r = await nobody.get("/api/info", headers=hdr)
check(c, "nor see the page's API", r.status_code == 401, str(r.status_code))
+ # the platform's command line, through the viewer
+ code, out = await rcli("list")
+ check(c, "`task list --url` shows the task", code == 0 and task_id in out and "running" in out, out[-200:])
+ code, out = await rcli("pause", task_id)
+ check(c, "`task pause --url` pauses it", code == 0 and await state_is(task_id, "paused"), out)
+ code, out = await rcli("resume", task_id)
+ check(c, "`task resume --url` resumes it", code == 0 and await state_is(task_id, "running"), out)
+ agent_env = {k: v for k, v in os.environ.items() if k not in ("ICTL_VIEWER_TOKEN", "IPHONE_CONTROL_VIEWER_TOKEN")}
+ agent_env.update({TOKEN_ENV: token, "IPHONE_CONTROL_URL": VIEWER, **({"IPHONE_CONTROL_CA": ca} if ca else {})})
+ code, out = await rcli("pause", task_id, env=agent_env)
+ check(c, "in the agent's shell (no login) `task pause` is refused",
+ code != 0 and await state_is(task_id, "running"), out)
+
# the platform pauses: the agent's next call waits until it resumes
r = await platform.post(f"/api/agent/tasks/{task_id}/pause", json={})
check(c, "the platform pauses it over HTTP", r.status_code == 200 and await state_is(task_id, "paused"), r.text)
@@ -575,9 +599,11 @@ async def remote(stack):
waiting = await state_is(task_id, "waiting", 30)
r = await nobody.post(f"/api/agent/tasks/{task_id}/confirm", json={"approve": True}, headers=hdr)
check(c, "the agent waits for a confirmation it can't give itself", waiting and r.status_code == 401, str(r.status_code))
- r = await platform.post(f"/api/agent/tasks/{task_id}/confirm", json={"approve": True})
+ code, out = await rcli("approve", task_id, env=agent_env)
+ check(c, "nor with `task approve` in its shell", code != 0 and await state_is(task_id, "waiting", 2), out)
+ code, out = await rcli("approve", task_id)
err, text, _ = await asyncio.wait_for(asking, 30)
- check(c, "the platform approves it over HTTP", r.status_code == 200 and not err, text)
+ check(c, "the platform's `task approve --url` answers it", code == 0 and not err, f"{out} / {text}")
by = [d.get("by") for n, d in seen if n == "control"]
check(c, "the log names the login token", bool(by) and all(str(b).startswith("viewer:") for b in by), json.dumps(by))
@@ -590,12 +616,16 @@ async def remote(stack):
except Exception as e: # noqa: BLE001 - any refusal will do
err, text = True, f"{type(e).__name__}: {e}"
check(c, "after that the agent is refused", err, text)
+ code, out = await rcli("events", task_id)
+ lines = [json.loads(line) for line in out.splitlines() if line.startswith("{")]
+ check(c, "`task events --url` replays the task to its end",
+ code == 0 and bool(lines) and lines[0]["event"] == "task" and lines[-1]["event"] == "done",
+ f"{len(lines)} events, last {lines[-1]['event'] if lines else None}")
# `task run --url`: run.py under it, through the viewer only (no daemon socket here)
env = {k: v for k, v in os.environ.items() if k not in (TOKEN_ENV, "MCP_URL", "MCP_CA", "ICTL_VIEWER_TOKEN")}
env.update({"IPHONE_CONTROL_VIEWER_TOKEN": login, "ICTL_SOCKET": "/nonexistent/ctl.sock",
"SHOTS_DIR": tempfile.mkdtemp(prefix="ictl-shots-")})
- url = ["--url", VIEWER] + (["--ca", ca] if ca else [])
steps = [["iphone_status", {}], ["iphone_press_button", {"button": "home"}], ["iphone_list_elements", {"limit": 3}]]
title = f"真机回归:task run --url {int(time.time())}"
p = await asyncio.create_subprocess_exec(
@@ -611,6 +641,22 @@ async def remote(stack):
check(c, "its task completed with every call as a step",
t.get("state") == "completed" and t.get("steps", 0) >= len(steps), json.dumps(t, ensure_ascii=False))
+ # an agent that only starts a command: plain `iphone-control mcp`, which bridges to the viewer by itself
+ title = f"真机回归:task run --url,stdio 转接 {int(time.time())}"
+ stdio_env = {**env, "MCP_CMD": shlex.join([*BIN, "mcp"])}
+ p = await asyncio.create_subprocess_exec(
+ *BIN, "task", "run", *url, "--title", title, "--owner", OWNER, "--",
+ "env", "-u", "IPHONE_CONTROL_MCP_URL", sys.executable, os.path.join(HERE, "run.py"), json.dumps(steps),
+ env=stdio_env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT,
+ )
+ out, _ = await asyncio.wait_for(p.communicate(), 300)
+ out = out.decode(errors="replace")
+ last = [line for line in out.splitlines() if line.startswith("---")]
+ t = next((t for t in reversed(await tasks()) if t["title"] == title), {})
+ check(c, "a stdio MCP client under `task run --url` works through `iphone-control mcp` (the bridge)",
+ p.returncode == 0 and t.get("state") == "completed" and t.get("steps", 0) >= len(steps),
+ (last[-1] if last else out[-300:]) + f" / {t.get('state')}, {t.get('steps')} steps")
+
title = f"真机回归:task run --url finish {int(time.time())}"
script = '[ -z "$IPHONE_CONTROL_VIEWER_TOKEN" ] || exit 9; "$@" task finish 远端完成'
p = await asyncio.create_subprocess_exec(
diff --git a/website/en/guide/cli.md b/website/en/guide/cli.md
index da46c10..685940a 100644
--- a/website/en/guide/cli.md
+++ b/website/en/guide/cli.md
@@ -18,7 +18,7 @@ These go before the command, for example `iphone-control --socket /path/ctl.sock
| Command | What it does |
|---|---|
| `daemon` | The long-running daemon. Usually started by the background service; you can also run it in a terminal |
-| `mcp` | MCP stdio server, started by the AI client |
+| `mcp [--url <viewer> [--ca <PEM>]]` | MCP stdio server, started by the AI client. With `--url` (or `IPHONE_CONTROL_URL` set), a bridge to another machine's viewer `/mcp`: for a phone on that machine and a client that only starts a command. With a task's token (`IPHONE_CONTROL_TASK_TOKEN`) only that is sent, otherwise the login from `IPHONE_CONTROL_VIEWER_TOKEN`; a command under `task run --url` has these set, so a plain `iphone-control mcp` works there |
| `mcp-config` | Prints the command that registers the MCP server with Claude Code, with a program path that stays the same across upgrades (Homebrew's `opt` link) |
## Shell completion
@@ -135,7 +135,7 @@ See [Auto-unlock](./auto-unlock). `--device` takes a UDID or name, and the devic
| `viewer token add <name> [--read-only]`, `list`, `show <name> [--new]`, `remove <name>` | Named tokens, one per person or device, say; the page's task log records which token paused, took over or confirmed. A `--read-only` token can watch the picture, the device's state and tasks; every action is refused and the page hides them. `list` doesn't show the tokens themselves; the last token that may operate stays |
| `task run [--title <title>] [--app <app>…] -- <command>` | AI tasks for other agent platforms: opens a task on the controlled device and runs the command in it. An `iphone-control mcp` the command starts takes part (through `IPHONE_CONTROL_TASK_TOKEN`): the control page shows every step and can pause, take over and stop it, and it waits for you before paying or sending a message. The task ends when the command does; when the task is stopped elsewhere, so is the command; Ctrl-C stops the task. While a task runs, other clients can look but not act on the phone. `--app` (repeatable, name or bundle ID) limits the task to those apps: in any other app, or to open a link that isn't a web page, each step waits for you first. **With the phone on another machine**, add `--url https://<that machine>:8200` (and `--ca cert.pem` for a self-signed certificate) and put the login token in `IPHONE_CONTROL_VIEWER_TOKEN`: the task is opened through that machine's viewer, and the command gets the task's token and `IPHONE_CONTROL_MCP_URL`, for its agent to connect to MCP over HTTP (see [Connect an AI Client](./mcp-clients#connect-by-url-http)). The login token isn't passed to the command, so the agent can't pause or confirm its own task; `task finish` in the command works as usual |
| `task list` / `task events <id>` | Recent tasks (`--json` for programs); follow a task's events, one JSON per line |
-| `task pause\|resume\|takeover\|handback\|stop <id>`, `task approve\|reject <id>` | Control a task from the command line, like the buttons on the control page. Only for a person: from inside the task (the agent's environment or a process it started) they are refused, except `stop` |
+| `task pause\|resume\|takeover\|handback\|stop <id>`, `task approve\|reject <id>` | Control a task from the command line, like the buttons on the control page. Only for a person: from inside the task (the agent's environment or a process it started) they are refused, except `stop`. Every `task` subcommand (`list` and `events` too) takes `--url <viewer> [--ca <PEM>]` (or `IPHONE_CONTROL_URL`) to work on another machine's phone through its viewer, with the login token in `IPHONE_CONTROL_VIEWER_TOKEN`; a command under `task run --url` has no login, so an agent is refused there as well |
The `debug` subcommand for diagnostics isn't compiled by default; see the [contributing guide](https://github.com/Derrors/iphone-control/blob/main/CONTRIBUTING.md#testing-on-a-real-phone).
diff --git a/website/en/guide/mcp-clients.md b/website/en/guide/mcp-clients.md
index f62f6c9..178ec10 100644
--- a/website/en/guide/mcp-clients.md
+++ b/website/en/guide/mcp-clients.md
@@ -37,7 +37,7 @@ To turn on the [developer tools](./tools#developer-tools-opt-in) or English, add
macOS has no `XDG_RUNTIME_DIR`, so the socket is `~/.local/share/iphone-control/ctl.sock`; again, use what `mcp-config` prints. Claude Desktop's configuration file is `~/Library/Application Support/Claude/claude_desktop_config.json`.
::: warning Client and daemon on the same machine
-The MCP server reaches the daemon through a local Unix socket. If the client runs on another computer, connect [by URL](#connect-by-url-http) as below, or start it over SSH, followed by the program path and arguments `mcp-config` prints on that host, e.g. `"command": "ssh", "args": ["host", "/home/you/.local/bin/iphone-control", "--socket", "/run/user/1000/iphone-control/ctl.sock", "mcp"]`.
+The MCP server reaches the daemon through a local Unix socket. If the client runs on another computer, connect [by URL](#connect-by-url-http) as below; for a client that only starts a command, install iphone-control there and use `iphone-control mcp --url https://<address>:8200` (the login token in `IPHONE_CONTROL_VIEWER_TOKEN`, `--ca cert.pem` for a self-signed certificate), which bridges stdio to HTTP; or start it over SSH, followed by the program path and arguments `mcp-config` prints on that host, e.g. `"command": "ssh", "args": ["host", "/home/you/.local/bin/iphone-control", "--socket", "/run/user/1000/iphone-control/ctl.sock", "mcp"]`.
:::
## Connect by URL (HTTP)
@@ -48,7 +48,7 @@ The viewer (`iphone-control viewer`, or the service from `service viewer install
- **This machine**: `http://127.0.0.1:8200/mcp` (the viewer's port). Claude Code: `claude mcp add --transport http iphone http://127.0.0.1:8200/mcp --header "Authorization: Bearer <token>"`; in a configuration file `{"type": "http", "url": "http://127.0.0.1:8200/mcp", "headers": {"Authorization": "Bearer <token>"}}`.
- **Another computer on the local network**: the viewer needs `--lan` (`IPHONE_CONTROL_VIEWER_LAN=1`); the address is `https://<this machine's address>:8200/mcp`. With the self-signed certificate made there, the client has to trust it: copy `~/.local/share/iphone-control/viewer-tls/cert.pem` from that machine and start Node-based clients (Claude Code and others) with `NODE_EXTRA_CA_CERTS=cert.pem`; or give the viewer a certificate of your own (`--tls-cert`/`--tls-key`). If the client uses a proxy, add the machine's address to `NO_PROXY`.
- **In a task**: when an agent platform opens a task with `task run`, have the agent's MCP requests carry the header `Iphone-Control-Task-Token: <the value of IPHONE_CONTROL_TASK_TOKEN>`; it does what that variable does on stdio (each step shows on the page, calls wait while paused, `iphone_confirm` is listed). **That header alone, without a login, is enough**: while the task runs, `/mcp` takes its token, and the agent can act on the phone for that task only, with no way to pause or confirm. Across machines that is how it should be: the platform keeps the login, the agent gets the task's token.
-- **A platform on another machine**: `iphone-control task run --url https://<address>:8200 -- <command>` opens the task and holds its lease for you; the command can set up its agent with `$IPHONE_CONTROL_MCP_URL` and `$IPHONE_CONTROL_TASK_TOKEN`. A platform without iphone-control calls the API: `POST /api/agent/tasks/open` (`Authorization: Bearer <login token>`, JSON `{title, owner?, apps?}`) answers with server-sent events, `opened` with `{id, token}` first; the open connection is the lease, and when it closes the task is abandoned. Pause, resume, take over, hand back, stop and confirm are `POST /api/agent/tasks/<id>/<action>` (confirm with `{"approve": true}`), events `GET /api/agent/tasks/<id>/events`, the list `GET /api/agent/tasks`; the agent ends its own task with `POST /api/agent/tasks/finish` (its task's token, `{ok, summary}`).
+- **A platform on another machine**: `iphone-control task run --url https://<address>:8200 -- <command>` opens the task and holds its lease for you. The agent in the command can keep a plain stdio `iphone-control mcp` (seeing `IPHONE_CONTROL_URL`, it bridges by itself with the task's token only), or use `$IPHONE_CONTROL_MCP_URL` and `$IPHONE_CONTROL_TASK_TOKEN` over HTTP directly. A platform without iphone-control calls the API: `POST /api/agent/tasks/open` (`Authorization: Bearer <login token>`, JSON `{title, owner?, apps?}`) answers with server-sent events, `opened` with `{id, token}` first; the open connection is the lease, and when it closes the task is abandoned. Pause, resume, take over, hand back, stop and confirm are `POST /api/agent/tasks/<id>/<action>` (confirm with `{"approve": true}`), events `GET /api/agent/tasks/<id>/events`, the list `GET /api/agent/tasks`; the agent ends its own task with `POST /api/agent/tasks/finish` (its task's token, `{ok, summary}`).
- **Off**: `viewer --mcp off` (`IPHONE_CONTROL_VIEWER_MCP=off`).
::: warning The token is the key
diff --git a/website/guide/cli.md b/website/guide/cli.md
index 5ed8ea6..51fea16 100644
--- a/website/guide/cli.md
+++ b/website/guide/cli.md
@@ -18,7 +18,7 @@
| 命令 | 作用 |
|---|---|
| `daemon` | 常驻守护进程。一般由后台服务启动,也可以在终端里手动运行 |
-| `mcp` | MCP stdio 服务,由 AI 客户端拉起 |
+| `mcp [--url <控制台> [--ca <PEM>]]` | MCP stdio 服务,由 AI 客户端拉起。加 `--url`(或设了 `IPHONE_CONTROL_URL`)时转接另一台机器控制台的 `/mcp`:手机接在那台机器上、客户端又只能填命令时用。有任务口令(`IPHONE_CONTROL_TASK_TOKEN`)就只带它,否则用 `IPHONE_CONTROL_VIEWER_TOKEN` 登录;`task run --url` 启动的命令已经设好这些,照常配置 `iphone-control mcp` 就行 |
| `mcp-config` | 打印把 MCP 注册到 Claude Code 的命令。程序路径用升级后不变的那个(Homebrew 用 `opt` 下的链接) |
## Shell 补全
@@ -135,7 +135,7 @@ Viewer 只监听本机回环地址。同机其他用户也能查看安装信息
| `viewer token add <名字> [--read-only]`、`list`、`show <名字> [--new]`、`remove <名字>` | 有名字的令牌,比如每人一个、每台设备一个;控制台的任务记录里记下是哪个令牌暂停、接管、确认的。`--read-only` 的令牌只能看画面、设备状态和任务,所有操作都被拒绝,页面上也不显示操作入口。`list` 不显示令牌本身;最后一个能操作的令牌不能删 |
| `task run [--title <标题>] [--app <App>…] -- <命令>` | 给别的 agent 平台用的 AI 任务:在当前控制的设备上开一个任务,再运行这条命令。命令启动的 `iphone-control mcp` 自动加入任务(经环境变量 `IPHONE_CONTROL_TASK_TOKEN`),控制台上能看到每一步,可以暂停、接管、停止,付款、发消息之前会等你确认。命令结束,任务就结束;任务在别处被停止,命令也会被停止;按 Ctrl-C 等于停止任务。任务进行中,其他客户端只能看,不能操作手机。`--app`(可写多次,App 名或 Bundle ID)把任务限定在这些 App 里:到了别的 App、或者要打开网页以外的链接,每一步都先等你确认。**手机接在另一台机器上**时加 `--url https://<那台机器>:8200`(自签证书再加 `--ca cert.pem`),登录令牌放在环境变量 `IPHONE_CONTROL_VIEWER_TOKEN` 里:任务经那台机器的控制台开,命令拿到的是任务口令和 `IPHONE_CONTROL_MCP_URL`,它的 agent 用 HTTP 方式的 MCP 接入(见[接入 AI 客户端](./mcp-clients#通过-url-接入-http))。登录令牌不会传给命令,所以 agent 不能暂停、确认自己的任务;命令里的 `task finish` 照样能用 |
| `task list` / `task events <id>` | 最近的任务(`--json` 给程序读);跟着一个任务的事件,每行一个 JSON |
-| `task pause\|resume\|takeover\|handback\|stop <id>`、`task approve\|reject <id>` | 在命令行里控制任务,和控制台上的按钮一样。只能由人来做:在任务里面(Agent 的环境或它启动的进程)执行会被拒绝,`stop` 除外 |
+| `task pause\|resume\|takeover\|handback\|stop <id>`、`task approve\|reject <id>` | 在命令行里控制任务,和控制台上的按钮一样。只能由人来做:在任务里面(Agent 的环境或它启动的进程)执行会被拒绝,`stop` 除外。`task` 的所有子命令(`list`、`events` 也是)都可以加 `--url <控制台> [--ca <PEM>]`(或设 `IPHONE_CONTROL_URL`),经另一台机器的控制台操作那里的手机,登录令牌放在 `IPHONE_CONTROL_VIEWER_TOKEN`;`task run --url` 启动的命令没有登录令牌,所以 Agent 在里面执行这些也会被拒绝 |
调试用的 `debug` 子命令默认不编译,见[贡献指南](https://github.com/Derrors/iphone-control/blob/main/CONTRIBUTING.md#testing-on-a-real-phone)。
diff --git a/website/guide/mcp-clients.md b/website/guide/mcp-clients.md
index 8a8a555..271bf08 100644
--- a/website/guide/mcp-clients.md
+++ b/website/guide/mcp-clients.md
@@ -37,7 +37,7 @@ codex mcp add iphone -- /path/to/iphone-control --socket <路径> mcp
macOS 上没有 `XDG_RUNTIME_DIR`,socket 在 `~/.local/share/iphone-control/ctl.sock`,同样以 `mcp-config` 打印的为准。Claude Desktop 的配置文件在 `~/Library/Application Support/Claude/claude_desktop_config.json`。
::: warning 客户端和守护进程要在同一台机器上
-MCP 服务经本机的 Unix socket 找守护进程。客户端在另一台电脑上时,用下面的 [URL 方式](#通过-url-接入-http),或者用 SSH 拉起,后面跟那台主机上 `mcp-config` 打印的程序路径和参数,例如 `"command": "ssh", "args": ["主机", "/home/you/.local/bin/iphone-control", "--socket", "/run/user/1000/iphone-control/ctl.sock", "mcp"]`。
+MCP 服务经本机的 Unix socket 找守护进程。客户端在另一台电脑上时,用下面的 [URL 方式](#通过-url-接入-http);客户端只能填命令时,在那台电脑上装好 iphone-control,填 `iphone-control mcp --url https://<IP>:8200`(登录令牌放在 `IPHONE_CONTROL_VIEWER_TOKEN`,自签证书加 `--ca cert.pem`),它把 stdio 转到 HTTP;或者用 SSH 拉起,后面跟那台主机上 `mcp-config` 打印的程序路径和参数,例如 `"command": "ssh", "args": ["主机", "/home/you/.local/bin/iphone-control", "--socket", "/run/user/1000/iphone-control/ctl.sock", "mcp"]`。
:::
## 通过 URL 接入(HTTP)
@@ -48,7 +48,7 @@ MCP 服务经本机的 Unix socket 找守护进程。客户端在另一台电脑
- **本机**:`http://127.0.0.1:8200/mcp`(端口跟着控制台)。Claude Code:`claude mcp add --transport http iphone http://127.0.0.1:8200/mcp --header "Authorization: Bearer <令牌>"`;配置文件里写 `{"type": "http", "url": "http://127.0.0.1:8200/mcp", "headers": {"Authorization": "Bearer <令牌>"}}`。
- **局域网里另一台电脑**:控制台要开 `--lan`(`IPHONE_CONTROL_VIEWER_LAN=1`),地址是 `https://<这台机器的 IP>:8200/mcp`。证书是本机生成的自签证书时,客户端要信任它:把那台机器上的 `~/.local/share/iphone-control/viewer-tls/cert.pem` 拷过来,Node 写的客户端(Claude Code 等)用 `NODE_EXTRA_CA_CERTS=cert.pem` 启动;也可以用 `--tls-cert`/`--tls-key` 换成自己的证书。客户端配了代理时,把这台机器的 IP 加进 `NO_PROXY`。
- **在任务里**:agent 平台用 `task run` 开任务时,让 agent 的 MCP 请求带上请求头 `Iphone-Control-Task-Token: <IPHONE_CONTROL_TASK_TOKEN 的值>`,作用和 stdio 方式下的环境变量一样(每一步显示在控制台上,暂停时等待,多出 `iphone_confirm`)。**只带这个请求头、不带登录令牌也行**:任务进行中,`/mcp` 认这个任务口令,agent 只能为这个任务操作手机,碰不到暂停、确认这些控制接口。跨机器时就该这样:登录令牌留在平台手里,agent 只拿任务口令。
-- **另一台机器上的平台**:`iphone-control task run --url https://<IP>:8200 -- <命令>` 替你开任务并持有租约,命令里能用 `$IPHONE_CONTROL_MCP_URL` 和 `$IPHONE_CONTROL_TASK_TOKEN` 配置 agent。不装 iphone-control 的平台直接调接口:`POST /api/agent/tasks/open`(`Authorization: Bearer <登录令牌>`,JSON `{title, owner?, apps?}`)返回事件流,第一条 `opened` 带 `{id, token}`,连接保持着就是租约,断开任务就记为 abandoned;暂停、继续、接管、交还、停止、确认是 `POST /api/agent/tasks/<id>/<动作>`(确认带 `{"approve": true}`),事件是 `GET /api/agent/tasks/<id>/events`,任务列表是 `GET /api/agent/tasks`;agent 自己结束任务用 `POST /api/agent/tasks/finish`(带任务口令,`{ok, summary}`)。
+- **另一台机器上的平台**:`iphone-control task run --url https://<IP>:8200 -- <命令>` 替你开任务并持有租约。命令里的 agent 照常配置 stdio 方式的 `iphone-control mcp` 就行(它看到 `IPHONE_CONTROL_URL` 会自动转接、只带任务口令),也可以用 `$IPHONE_CONTROL_MCP_URL` 和 `$IPHONE_CONTROL_TASK_TOKEN` 直接走 HTTP。不装 iphone-control 的平台直接调接口:`POST /api/agent/tasks/open`(`Authorization: Bearer <登录令牌>`,JSON `{title, owner?, apps?}`)返回事件流,第一条 `opened` 带 `{id, token}`,连接保持着就是租约,断开任务就记为 abandoned;暂停、继续、接管、交还、停止、确认是 `POST /api/agent/tasks/<id>/<动作>`(确认带 `{"approve": true}`),事件是 `GET /api/agent/tasks/<id>/events`,任务列表是 `GET /api/agent/tasks`;agent 自己结束任务用 `POST /api/agent/tasks/finish`(带任务口令,`{ok, summary}`)。
- **关掉**:`viewer --mcp off`(`IPHONE_CONTROL_VIEWER_MCP=off`)。
::: warning 令牌就是钥匙