Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools
Rust ai-agentautomationclaudeclaude-codedockeriosiphonelinuxmcpmcp-servermodel-context-protocolrustwebdriveragent
feat(viewer): serve MCP over HTTP at /mcp on the same port (#77)
Qinghe Li69a792e32c30
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 403ffe2..b8c3909 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ All notable changes to this project are documented here. The format is based on### Added+- MCP over HTTP: `/mcp` (Streamable HTTP) on the viewer's port serves the same tools as `iphone-control mcp`, for clients that only take a URL and for agents on another computer on the local network (`--lan`, over HTTPS), e.g. `claude mcp add --transport http iphone http://127.0.0.1:8200/mcp`. A task's agent sends the task's token in the `Iphone-Control-Task-Token` header. No login, as for the viewer; `--mcp off` (`IPHONE_CONTROL_VIEWER_MCP=off`) turns it off.- The viewer opened to the local network (`--lan`) now speaks HTTPS, on the same port: opened from another machine the picture can be H.264 or the phone's own HEVC instead of MJPEG, and traffic is encrypted. It uses a self-signed certificate made on this machine (kept in `viewer-tls/` in the data directory and reused); the browser warns the first time, so check the SHA-256 fingerprint shown at startup or by `service status` and go on. `--tls-cert`/`--tls-key` (`IPHONE_CONTROL_VIEWER_TLS_CERT`/`_KEY`) use a certificate of your own. `http://` from the network is redirected to `https://`; `http://127.0.0.1` on this machine works as before. `--tls off` (`IPHONE_CONTROL_VIEWER_TLS=off`) goes back to HTTP. It isn't a login: anyone on the network who can reach the page can still control the phone.- `iphone-control service viewer install` runs the viewer as a background service of its own that starts at login (`uninstall`, `start`, `stop`, `restart` too). It reads its port and whether it is open to the local network from the settings file (`IPHONE_CONTROL_VIEWER_PORT`, new; `IPHONE_CONTROL_VIEWER_LAN`; `IPHONE_CONTROL_VIEWER_LAN_HOSTS`, new) and keeps the installing shell's `PATH` to find `claude` and `codex`. Updates stop it and start it again; an automatic update waits while an AI task runs.- An AI task's agent can no longer pause, resume, take over, hand back or confirm its own task, so only a person answers out-of-scope steps and `iphone_confirm`. Control requests carrying the task's token (`IPHONE_CONTROL_TASK_TOKEN`) are refused, and so are those from an agent the control page or `task run` started, or any process it starts, even without the token or through the page's API. On macOS, calls through the page's API can't be traced to a process yet. Stopping a task is always allowed. The task's log records who controlled it (the page, the command line, the task's opener).diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.mdindex f4a902d..f3783cc 100644--- a/CHANGELOG.zh-CN.md+++ b/CHANGELOG.zh-CN.md@@ -8,6 +8,7 @@### 新增+- MCP over HTTP:控制台同一个端口上的 `/mcp`(Streamable HTTP)提供和 `iphone-control mcp` 一样的工具,只能填 URL 的客户端、局域网里另一台电脑上的 agent(`--lan`,走 HTTPS)都能接入,例如 `claude mcp add --transport http iphone http://127.0.0.1:8200/mcp`。任务里的 agent 在请求头 `Iphone-Control-Task-Token` 里带上任务口令。和控制台一样没有登录,`--mcp off`(`IPHONE_CONTROL_VIEWER_MCP=off`)关掉。- 控制台对局域网开放(`--lan`)时改用 HTTPS,还是同一个端口:局域网里打开时画面也能用 H.264 或手机自己的 HEVC,不再退回 MJPEG,传输也加了密。默认用本机生成的自签证书(存在数据目录的 `viewer-tls/`,一直沿用),浏览器第一次打开会提示不受信任,核对启动时或 `service status` 显示的 SHA-256 指纹后继续;也可以用 `--tls-cert`/`--tls-key`(`IPHONE_CONTROL_VIEWER_TLS_CERT`/`_KEY`)换成自己的证书。局域网来的 `http://` 跳转到 `https://`,本机的 `http://127.0.0.1` 照旧。`--tls off`(`IPHONE_CONTROL_VIEWER_TLS=off`)恢复成 HTTP。这不是登录:局域网里能连上的人照样能操作手机。- `iphone-control service viewer install` 把控制台装成登录后自动启动的后台服务(还有 `uninstall`、`start`、`stop`、`restart`)。端口和是否对局域网开放读设置文件(新增 `IPHONE_CONTROL_VIEWER_PORT`;`IPHONE_CONTROL_VIEWER_LAN`;新增 `IPHONE_CONTROL_VIEWER_LAN_HOSTS`),并记下安装时终端的 `PATH` 以找到 `claude` 和 `codex`。升级时先停下它、升级完再启动;有 AI 任务在跑时自动升级会推迟。- AI 任务的 Agent 不能再自己暂停、继续、接管、交还或确认,越界确认和 `iphone_confirm` 只能由人回答。带任务口令(`IPHONE_CONTROL_TASK_TOKEN`)的控制请求会被拒绝;控制台和 `task run` 启动的 Agent,连同它再启动的进程,也会被拒绝,即使去掉了口令,或者调用控制台的接口。在 macOS 上,调用控制台接口的这条路还查不出是哪个进程。停止任务不受限制。任务记录里会写下谁做了控制(控制台、命令行、任务的发起方)。diff --git a/Cargo.lock b/Cargo.lockindex 095ba5d..99d67a3 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2006,6 +2006,7 @@ name = "ictl-mcp"version = "0.2.3"dependencies = ["anyhow",+ "http","ictl-l10n","ictl-protocol","rmcp",@@ -2284,11 +2285,14 @@ name = "iphone-control"version = "0.2.3"dependencies = ["anyhow",+ "bytes","chrono","clap","clap_complete","console","flate2",+ "http",+ "http-body-util","ictl-daemon","ictl-device","ictl-l10n",@@ -3822,20 +3826,29 @@ version = "3.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8be15815186873ea063bf005011d16c356804973489e40c39116ae3a2878d1f"dependencies = [+ "async-trait","base64 0.23.1",+ "bytes","chrono","futures",+ "http",+ "http-body",+ "http-body-util","indexmap","libc","pastey","pin-project-lite",+ "rand 0.10.3","rmcp-macros","schemars","serde","serde_json",+ "sse-stream","thiserror 2.0.21","tokio",+ "tokio-stream","tokio-util",+ "tower-service","tracing","uuid",]@@ -4471,6 +4484,19 @@ dependencies = ["subtle",]+[[package]]+name = "sse-stream"+version = "0.2.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c25ac7aff0abd1dbc474536e40416e1102c7dd9bfba0b9861c6d357f835dcfb4"+dependencies = [+ "bytes",+ "futures-util",+ "http-body",+ "http-body-util",+ "pin-project-lite",+]+[[package]]name = "stable_deref_trait"version = "1.2.1"@@ -4783,6 +4809,17 @@ dependencies = ["tokio",]+[[package]]+name = "tokio-stream"+version = "0.1.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b"+dependencies = [+ "futures-core",+ "pin-project-lite",+ "tokio",+]+[[package]]name = "tokio-tungstenite"version = "0.27.0"diff --git a/Cargo.toml b/Cargo.tomlindex 69501e8..ea6ad61 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -50,7 +50,11 @@ idevice = { version = "=0.1.68", default-features = false, features = ["syslog_relay","crashreportcopymobile",] }-rmcp = { version = "=3.8.0", features = ["server", "transport-io"] }+# transport-streamable-http-server:控制台的 /mcp(MCP over HTTP)+rmcp = { version = "=3.8.0", features = ["server", "transport-io", "transport-streamable-http-server"] }+http = "=1.5.0"+http-body-util = "=0.1.5"+bytes = "=1.12.1"tokio = { version = "=1.54.1", features = ["full"] }# rustls-no-provider:不编进 aws-lc-rs(C 代码,编译慢、体积大);idevice/plume_core 用 ring,入口处显式装 ring 为默认 providerreqwest = { version = "=0.13.5", default-features = false, features = ["form", "rustls-no-provider"] }diff --git a/apps/iphone-control/Cargo.toml b/apps/iphone-control/Cargo.tomlindex 97ddd54..322b9fb 100644--- a/apps/iphone-control/Cargo.toml+++ b/apps/iphone-control/Cargo.toml@@ -24,6 +24,9 @@ tokio.workspace = trueanyhow.workspace = truerustls.workspace = truetokio-rustls.workspace = true+http.workspace = true+http-body-util.workspace = true+bytes.workspace = truercgen.workspace = truereqwest.workspace = trueserde.workspace = truediff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rsindex a506db6..8eb1061 100644--- a/apps/iphone-control/src/main.rs+++ b/apps/iphone-control/src/main.rs@@ -122,6 +122,8 @@ enum Command {tls_cert: Option<PathBuf>,#[arg(long = "tls-key", value_name = "PEM", env = "IPHONE_CONTROL_VIEWER_TLS_KEY", requires = "tls_cert", help = ictl_l10n::tr!("--tls-cert 的私钥(PEM)", "The private key of --tls-cert (PEM)"))]tls_key: Option<PathBuf>,+ #[arg(long, env = "IPHONE_CONTROL_VIEWER_MCP", value_name = "on|off", default_value = "on", action = clap::ArgAction::Set, value_parser = clap::builder::BoolishValueParser::new(), help = ictl_l10n::tr!("同一个端口上的 MCP(HTTP):/mcp,本机和(--lan 时)局域网的客户端用 URL 接入;off 关掉", "MCP over HTTP on the same port: /mcp, for clients on this machine and (with --lan) the local network that connect by URL; off turns it off"))]+ mcp: bool,},#[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 {@@ -311,9 +313,9 @@ async fn run() -> anyhow::Result<()> {Command::Devices => print_text(&cli.socket, Request::ListDevices).await,Command::Select { device } => print_text(&cli.socket, Request::SelectDevice { device }).await,Command::WdaBridge { port } => wda_bridge(&cli.socket, port).await,- Command::Viewer { port, lan, lan_hosts, tls, tls_cert, tls_key } => {+ Command::Viewer { port, lan, lan_hosts, tls, tls_cert, tls_key, mcp } => {let tls = viewer::tls::Setting { mode: tls, cert: tls_cert, key: tls_key };- viewer::run(&cli.socket, &cli.data_dir, port, lan, &lan_hosts, &tls).await+ viewer::run(&cli.socket, &cli.data_dir, port, lan, &lan_hosts, &tls, mcp).await}Command::Task { action } => task::run(&cli.socket, action).await,#[cfg(feature = "debug-cmds")]diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rsindex c2a3d9f..1fed527 100644--- a/apps/iphone-control/src/viewer.rs+++ b/apps/iphone-control/src/viewer.rs@@ -27,6 +27,7 @@//! replug (new usbmuxd id) doesn't break the picture.mod lan;+mod mcp;mod peer;pub mod tls;@@ -77,6 +78,8 @@ struct Ctx {acks: Arc<crate::video::Acks>,/// HTTPS on the same port (`--lan`); plain HTTP from the network is then sent theretls: Option<Arc<tls::Tls>>,+ /// MCP over HTTP at `/mcp` (`--mcp`, on by default)+ mcp: Option<ictl_mcp::HttpService>,}/// A picture handler can be cancelled at any await, including while opening its source.@@ -107,7 +110,7 @@ impl Ctx {}/// `lan`: also open the page to the local network (`--lan`); `lan_hosts`: more names it answers to there; `tls`:-/// whether and with which certificate it speaks HTTPS+/// whether and with which certificate it speaks HTTPS; `mcp`: MCP over HTTP at `/mcp`pub async fn run(socket: &Path,data_dir: &Path,@@ -115,6 +118,7 @@ pub async fn run(lan: bool,lan_hosts: &[String],tls: &tls::Setting,+ mcp: bool,) -> anyhow::Result<()> {// only a first guess: the page follows whichever device the daemon controls (see `info`). Not knowing yet is// fine: the daemon may still be starting (started together with this at login), and with several devices@@ -213,9 +217,21 @@ pub async fn run();}}+ if mcp {+ println!(+ "{}",+ ictl_l10n::trf!(+ "MCP(HTTP):http://127.0.0.1:{port}/mcp;任务里的 agent 在请求头 Iphone-Control-Task-Token 里带上任务口令",+ "MCP (HTTP): http://127.0.0.1:{port}/mcp; a task's agent sends the task's token in the Iphone-Control-Task-Token header"+ )+ );+ }if access.is_lan() {for a in access.addresses() {println!("{}", ictl_l10n::trf!("局域网:{scheme}://{a}:{port}/", "On the network: {scheme}://{a}:{port}/"));+ if mcp {+ println!("{}", ictl_l10n::trf!(" MCP:{scheme}://{a}:{port}/mcp", " MCP: {scheme}://{a}:{port}/mcp"));+ }}if tls.is_some() {println!(@@ -259,6 +275,7 @@ pub async fn run(video,acks: Arc::default(),tls,+ mcp: mcp.then(|| ictl_mcp::http_service(socket.to_path_buf())),});let slots = Arc::new(tokio::sync::Semaphore::new(crate::MAX_CONNECTIONS));loop {@@ -376,6 +393,22 @@ async fn handle(mut client: Conn, ctx: &Ctx, head: Vec<u8>, req: Head, mut body:Err(m) => json_reply(&mut client, 502, &json!({"message": m})).await,}}+ ("GET" | "POST" | "DELETE", "/mcp") if ctx.mcp.is_some() => {+ // a browser says where it comes from: only the page itself. Other clients send no Origin+ if req.origin.as_deref().is_some_and(|o| !ctx.access.origin_allowed(o, ctx.port)) {+ return reply(&mut client, 403, "text/plain", b"forbidden").await;+ }+ if req.method == "POST" && req.content_length.is_none() {+ return reply(&mut client, 411, "text/plain", b"length required").await;+ }+ let len = req.content_length.unwrap_or(0);+ if len > mcp::MAX_BODY {+ return reply(&mut client, 413, "text/plain", b"too large").await;+ }+ read_body(&mut client, &mut body, len).await?;+ let svc = ctx.mcp.as_ref().expect("checked above");+ mcp::serve(svc, &mut client, &head, body).await+ }("POST", p) if p.starts_with("/api/") => {if !action_allowed(&req, &ctx.access, ctx.port) {return reply(&mut client, 403, "text/plain", b"forbidden").await;@@ -384,15 +417,7 @@ async fn handle(mut client: Conn, ctx: &Ctx, head: Vec<u8>, req: Head, mut body:if len > MAX_BODY {return reply(&mut client, 413, "text/plain", b"too large").await;}- while body.len() < len {- let mut buf = [0u8; 4096];- let n = tokio::time::timeout(crate::READ_TIMEOUT, client.read(&mut buf)).await??;- if n == 0 {- bail!("body cut off");- }- body.extend_from_slice(&buf[..n]);- }- body.truncate(len);+ read_body(&mut client, &mut body, len).await?;let Ok(b) = serde_json::from_slice::<Value>(&body) else {return json_reply(&mut client, 400, &json!({"ok": false, "message": "bad request"})).await;};@@ -629,6 +654,20 @@ fn sse(e: &protocol::TaskEvent) -> String {format!("event: {}\ndata: {}\n\n", e.event, e.data)}+/// The rest of a request body: `body` holds what came with the head; `len` bytes in all+async fn read_body(client: &mut Conn, body: &mut Vec<u8>, len: usize) -> anyhow::Result<()> {+ while body.len() < len {+ let mut buf = [0u8; 4096];+ let n = tokio::time::timeout(crate::READ_TIMEOUT, client.read(&mut buf)).await??;+ if n == 0 {+ bail!("body cut off");+ }+ body.extend_from_slice(&buf[..n]);+ }+ body.truncate(len);+ Ok(())+}+async fn json_reply(client: &mut Conn, status: u16, v: &Value) -> anyhow::Result<()> {reply(client, status, "application/json", v.to_string().as_bytes()).await}@@ -641,6 +680,7 @@ async fn reply(client: &mut Conn, status: u16, kind: &str, body: &[u8]) -> anyho403 => "Forbidden",404 => "Not Found",409 => "Conflict",+ 411 => "Length Required",413 => "Payload Too Large",_ => "Bad Gateway",};@@ -1107,6 +1147,7 @@ mod tests {acks: Arc::default(),feeds: Mutex::default(),tls: None,+ mcp: None,}}diff --git a/apps/iphone-control/src/viewer/mcp.rs b/apps/iphone-control/src/viewer/mcp.rsnew file mode 100644index 0000000..1e13c51--- /dev/null+++ b/apps/iphone-control/src/viewer/mcp.rs@@ -0,0 +1,162 @@+//! MCP over HTTP at `/mcp`, on the viewer's port (docs/task-control.md 7.4).+//!+//! The same tools as `iphone-control mcp` on stdio, for clients that connect by URL: an agent on another machine+//! (with `--lan`, over HTTPS), or a client that only speaks HTTP. rmcp's Streamable HTTP server does the protocol+//! (sessions, SSE); this passes requests the viewer has already read to it and writes its answer back, one request+//! per connection like the rest of the viewer.+//!+//! Who may call it is who may open the page: the viewer checks the peer address, `Host` and `Sec-Fetch-Site` first,+//! and here a request that carries an `Origin` (a browser) must come from the page itself. Clients that aren't+//! browsers send none. No login yet, as for the page.+//!+//! A task's agent sends the task's token in `Iphone-Control-Task-Token` ([`ictl_daemon::protocol::TASK_TOKEN_HEADER`]),+//! as `IPHONE_CONTROL_TASK_TOKEN` does on stdio.++use bytes::Bytes;+use http_body_util::{BodyExt, Full};+use tokio::io::AsyncWriteExt;++use super::tls::Conn;++/// A request body bigger than this is refused (a tool call is a few KB)+pub const MAX_BODY: usize = 1024 * 1024;++/// Hands the request (`head` and its whole `body`) to `svc` and writes the answer, streaming it (SSE) until it ends+/// or the client goes away+pub async fn serve(svc: &ictl_mcp::HttpService, client: &mut Conn, head: &[u8], body: Vec<u8>) -> anyhow::Result<()> {+ let Some(req) = request(head, body) else {+ client.write_all(b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").await?;+ client.flush().await?;+ return Ok(());+ };+ let (parts, mut body) = svc.handle(req).await.into_parts();+ client.write_all(response_head(&parts).as_bytes()).await?;+ client.flush().await?;+ while let Some(frame) = body.frame().await {+ let frame = match frame {+ Ok(f) => f,+ Err(never) => match never {},+ };+ if let Some(data) = frame.data_ref() {+ client.write_all(data).await?;+ // each event goes out now (TLS holds the last record back otherwise)+ client.flush().await?;+ }+ }+ Ok(())+}++/// The request as rmcp takes it+fn request(head: &[u8], body: Vec<u8>) -> Option<http::Request<Full<Bytes>>> {+ let text = std::str::from_utf8(head).ok()?;+ let mut lines = text.split("\r\n");+ let mut first = lines.next()?.split(' ');+ let (method, target) = (first.next()?, first.next()?);+ let mut b = http::Request::builder().method(method).uri(target);+ for line in lines.filter(|l| !l.is_empty()) {+ let (k, v) = line.split_once(':')?;+ b = b.header(k.trim(), v.trim());+ }+ b.body(Full::new(Bytes::from(body))).ok()+}++/// Status line and headers; the body ends with the connection (`Connection: close`) unless it has a length+fn response_head(parts: &http::response::Parts) -> String {+ let mut out =+ format!("HTTP/1.1 {} {}\r\n", parts.status.as_u16(), parts.status.canonical_reason().unwrap_or("Unknown"));+ for (k, v) in &parts.headers {+ if k == http::header::CONNECTION || k == http::header::TRANSFER_ENCODING {+ continue;+ }+ out.push_str(&format!("{}: {}\r\n", k.as_str(), String::from_utf8_lossy(v.as_bytes())));+ }+ out.push_str("Connection: close\r\n\r\n");+ out+}++#[cfg(test)]+mod tests {+ use super::*;+ use tokio::io::AsyncReadExt;++ /// One HTTP request through [`serve`], as a client sees it: (head, body)+ async fn exchange(svc: &ictl_mcp::HttpService, raw: String) -> (String, String) {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let client = tokio::spawn(async move {+ let mut s = tokio::net::TcpStream::connect(addr).await.unwrap();+ s.write_all(raw.as_bytes()).await.unwrap();+ let mut out = String::new();+ s.read_to_string(&mut out).await.unwrap();+ out+ });+ let (tcp, _) = listener.accept().await.unwrap();+ let mut conn = Conn::Plain(tcp);+ let (head, body) = crate::read_head(&mut conn).await.unwrap();+ let len = Head::content_length(&head);+ let mut body = body;+ while body.len() < len {+ let mut buf = [0u8; 4096];+ let n = conn.read(&mut buf).await.unwrap();+ body.extend_from_slice(&buf[..n]);+ }+ serve(svc, &mut conn, &head, body).await.unwrap();+ drop(conn);+ let out = client.await.unwrap();+ let (h, b) = out.split_once("\r\n\r\n").unwrap();+ (h.to_owned(), b.to_owned())+ }++ struct Head;+ impl Head {+ fn content_length(head: &[u8]) -> usize {+ String::from_utf8_lossy(head)+ .lines()+ .find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse().unwrap()))+ .unwrap_or(0)+ }+ }++ fn post(body: &str, extra: &str) -> String {+ format!(+ "POST /mcp HTTP/1.1\r\nHost: 127.0.0.1:8202\r\nContent-Type: application/json\r\n\+ Accept: application/json, text/event-stream\r\nContent-Length: {}\r\n{extra}\r\n{body}",+ body.len()+ )+ }++ fn header<'a>(head: &'a str, name: &str) -> Option<&'a str> {+ head.lines().find_map(|l| {+ let (k, v) = l.split_once(':')?;+ k.trim().eq_ignore_ascii_case(name).then(|| v.trim())+ })+ }++ /// A session: initialize, then list the tools, with and without a task's token. The tool list doesn't need the+ /// daemon, so none runs here+ #[tokio::test]+ async fn an_mcp_session_over_http() {+ let svc = ictl_mcp::http_service("/nonexistent/ctl.sock".into());+ let init = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"1"}}}"#;+ let (head, body) = exchange(&svc, post(init, "")).await;+ assert!(head.starts_with("HTTP/1.1 200"), "{head}");+ assert!(body.contains("iphone"), "{body}");+ let session = header(&head, "mcp-session-id").expect("a session").to_owned();+ let sid = format!("Mcp-Session-Id: {session}\r\nMcp-Protocol-Version: 2025-06-18\r\n");+ let done = r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#;+ let (head, _) = exchange(&svc, post(done, &sid)).await;+ assert!(head.starts_with("HTTP/1.1 202"), "{head}");++ let list = r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#;+ let (_, body) = exchange(&svc, post(list, &sid)).await;+ assert!(body.contains("iphone_tap") && !body.contains("iphone_confirm"), "a plain client: no confirm tool");+ let (_, body) = exchange(&svc, post(list, &format!("{sid}Iphone-Control-Task-Token: abc\r\n"))).await;+ assert!(body.contains("iphone_confirm"), "a task's agent gets the confirm tool: {body}");+ }++ #[test]+ fn a_broken_request_head_isn_t_passed_on() {+ assert!(request(b"GET /mcp HTTP/1.1\r\nno colon here", Vec::new()).is_none());+ assert!(request(b"GET /mcp HTTP/1.1\r\nHost: x", Vec::new()).is_some());+ }+}diff --git a/crates/ictl-mcp/Cargo.toml b/crates/ictl-mcp/Cargo.tomlindex 666cba4..2479e79 100644--- a/crates/ictl-mcp/Cargo.toml+++ b/crates/ictl-mcp/Cargo.toml@@ -14,5 +14,6 @@ ictl-l10n.workspace = trueictl-protocol.workspace = truetokio.workspace = truermcp.workspace = true+http.workspace = trueserde_json.workspace = trueanyhow.workspace = truediff --git a/crates/ictl-mcp/src/lib.rs b/crates/ictl-mcp/src/lib.rsindex 82d2b1b..c4113c6 100644--- a/crates/ictl-mcp/src/lib.rs+++ b/crates/ictl-mcp/src/lib.rs@@ -876,10 +876,35 @@ pub fn to_result(r: Response) -> CallToolResult {#[derive(Debug, Clone)]pub struct McpServer {pub socket: PathBuf,- /// Working for a task (see [`task`])+ /// This process works for a task (`IPHONE_CONTROL_TASK_TOKEN`, see [`task`]); over HTTP a request may instead+ /// carry a task's token in [`protocol::TASK_TOKEN_HEADER`] ([`request_token`])pub task: bool,}+/// The task token an HTTP request carries ([`protocol::TASK_TOKEN_HEADER`]); `None` over stdio+fn request_token(context: &RequestContext<RoleServer>) -> Option<String> {+ let parts = context.extensions.get::<http::request::Parts>()?;+ let t = parts.headers.get(protocol::TASK_TOKEN_HEADER)?.to_str().ok()?.trim();+ (!t.is_empty()).then(|| t.to_owned())+}++/// MCP over HTTP (Streamable HTTP, one session per client) for the viewer's `/mcp`+pub type HttpService = rmcp::transport::streamable_http_server::StreamableHttpService<+ McpServer,+ rmcp::transport::streamable_http_server::session::local::LocalSessionManager,+>;++/// The service behind `/mcp`. It doesn't check `Host` or `Origin`: the viewer does, with the names of its page+pub fn http_service(socket: PathBuf) -> HttpService {+ use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};+ let config = StreamableHttpServerConfig::default().with_allowed_hosts(Vec::<String>::new());+ StreamableHttpService::new(+ move || Ok(McpServer { socket: socket.clone(), task: false }),+ std::sync::Arc::default(),+ config,+ )+}+impl ServerHandler for McpServer {fn get_info(&self) -> InitializeResult {InitializeResult::new(ServerCapabilities::builder().enable_tools().build()).with_instructions(instructions())@@ -888,10 +913,10 @@ impl ServerHandler for McpServer {async fn list_tools(&self,_request: Option<PaginatedRequestParams>,- _context: RequestContext<RoleServer>,+ context: RequestContext<RoleServer>,) -> Result<ListToolsResult, ErrorData> {let mut t = tools();- if self.task {+ if self.task || request_token(&context).is_some() {t.push(confirm_tool());}Ok(ListToolsResult::with_all_items(t))@@ -902,9 +927,22 @@ impl ServerHandler for McpServer {request: CallToolRequestParams,context: RequestContext<RoleServer>,) -> Result<CallToolResponse, ErrorData> {- if !self.task {+ let token = request_token(&context);+ if !self.task && token.is_none() {return self.call_tool_cancellable(request, &context).await;}+ // every request of this call goes out with the HTTP request's token (over stdio: the process's)+ protocol::as_task(token, None, self.call_tool_in_task(request, context)).await+ }+}++impl McpServer {+ /// [`ServerHandler::call_tool`] for a task's agent+ async fn call_tool_in_task(+ &self,+ request: CallToolRequestParams,+ context: RequestContext<RoleServer>,+ ) -> Result<CallToolResponse, ErrorData> {// working for a task: the daemon holds or refuses the calls; announce each so the page shows the toollet args = request.arguments.clone().unwrap_or_default();let work = async {@@ -933,9 +971,7 @@ impl ServerHandler for McpServer {_ = context.ct.cancelled() => Ok(to_result(Response::error(ictl_l10n::tr!("调用已取消", "Call cancelled"))).into()),}}-}-impl McpServer {async fn call_tool_cancellable(&self,request: CallToolRequestParams,@@ -993,7 +1029,7 @@ impl McpServer {// can take several minutes on its ownlet wait = if matches!(req, Request::InstallApp { .. }) { 660 } else { 150 };// in a task the daemon holds calls while the user has paused or taken over, as long as that takes- let wait = (!self.task).then(|| Duration::from_secs(wait));+ let wait = (!protocol::in_task()).then(|| Duration::from_secs(wait));protocol::call_expecting(&self.socket, req, wait, expect_udid).await.unwrap_or_else(|e| {Response::error(ictl_l10n::trf!("连不上守护进程({}):{e};确认守护进程在运行(iphone-control status)",diff --git a/crates/ictl-protocol/src/lib.rs b/crates/ictl-protocol/src/lib.rsindex 9daa19b..8173c48 100644--- a/crates/ictl-protocol/src/lib.rs+++ b/crates/ictl-protocol/src/lib.rs@@ -502,6 +502,8 @@ pub const TASK: &str = "task";pub const TASK_STEP: &str = "task_step";/// The environment variable that hands a task's token to `iphone-control mcp` (and anything else using this crate)pub const TASK_TOKEN_ENV: &str = "IPHONE_CONTROL_TASK_TOKEN";+/// The HTTP header that does the same for MCP over HTTP (the viewer's `/mcp`), per request+pub const TASK_TOKEN_HEADER: &str = "iphone-control-task-token";static PROCESS_TASK: std::sync::OnceLock<String> = std::sync::OnceLock::new();@@ -527,6 +529,11 @@ pub async fn as_task<F: std::future::Future>(token: Option<String>, step: OptionCALL_TASK.scope((token, step), f).await}+/// Whether the requests sent from here belong to a task ([`as_task`] or [`join_task`])+pub fn in_task() -> bool {+ current_task().0.is_some()+}+fn current_task() -> (Option<String>, Option<u64>) {let (token, step) = CALL_TASK.try_with(Clone::clone).unwrap_or_default();(token.or_else(|| process_task().map(str::to_owned)), step)diff --git a/docs/task-control.md b/docs/task-control.mdindex e395130..10cc375 100644--- a/docs/task-control.md+++ b/docs/task-control.md@@ -133,7 +133,8 @@ Running → Waiting(等确认)→ Running| 三 | 任务范围(App 白名单)和越界确认 | 已完成(2026-11-13,见 5.5) || 三 | 执行方不能控制自己的任务(2.5 的落地版,见 5.6) | 已完成(2026-11-13) || 四 | 局域网访问控制台(7.2)、控制台后台服务、HTTPS(7.3) | 已完成(2026-11-13) |-| 四 | 登录、HTTP MCP、多设备租约 | 等需要时 |+| 四 | HTTP MCP(7.4) | 已完成(2026-11-13) |+| 四 | 登录、跨主机开任务(HTTP 控制面)、多设备租约 | 等需要时 |## 5. 阶段一的具体设计@@ -272,3 +273,14 @@ Running → Waiting(等确认)→ Running- **写出**:TLS 会把最后一段留在缓冲里,所以每个响应、视频头、每条任务事件、每帧画面之后都 flush(明文 TCP 上 flush 什么也不做)。- **依赖**:`tokio-rustls`、`rcgen` 原本就在依赖树里(idevice、reqwest、plume_core),只用 ring,没有新增 crate。- **局限**:自签证书第一次要手动点「继续」;之后页面按规范是安全上下文,但各浏览器对点过警告的证书仍有限制(比如 Chrome 不注册 Service Worker),WebCodecs 能不能用以真机浏览器实测为准。++### 7.4 HTTP MCP(2026-11-13)++7.1 第 6 条的一部分:外部 Agent 跨主机接入,用和控制台同一个端口、同一套访问规则,不另开一个口子。++- **在哪**:控制台的 `/mcp`,Streamable HTTP(rmcp 的服务端:会话、SSE 都由它做)。控制台照旧一个连接一个请求:读完请求头和请求体交给 rmcp,再把它的回应(JSON 或 SSE)一段段写回去、每段 flush,直到结束或客户端断开。POST 必须带 `Content-Length`(否则 411),请求体最多 1 MB。+- **工具**:和 stdio 的 `iphone-control mcp` 是同一个 `McpServer`,没有任何差别(D10)。+- **任务**:stdio 靠进程的环境变量 `IPHONE_CONTROL_TASK_TOKEN` 加入任务;HTTP 是一个进程服务许多客户端,所以口令放在每个请求的头 `Iphone-Control-Task-Token` 里,`McpServer` 按请求读取,用 `as_task` 让这次调用发出的所有请求都带上它。「是否在任务里」也改成按请求判断(`protocol::in_task`)。带了口令就列出 `iphone_confirm`、每次调用报告步骤,和 stdio 一样。+- **访问**:和控制台页面一样,对端地址、`Host`、`Sec-Fetch-Site` 先查;带 `Origin` 的请求(浏览器)必须来自控制台自己,命令行客户端不带 `Origin`。rmcp 自己的 Host 白名单设为不检查,免得两套名单不一致。`--lan` 时局域网的明文请求 307 到 HTTPS。+- **开关**:`--mcp on|off`(`IPHONE_CONTROL_VIEWER_MCP`),默认开:它能做的事控制台的接口本来就能做,没有多开口子。+- **还没有的**:登录(和控制台一起做);从别的机器**开**任务(任务的租约还是本机 socket 上的连接,外部平台目前在本机用 `task run` 开任务、把口令交给远端的 agent)。diff --git a/packaging/env.example b/packaging/env.exampleindex 0e2cd1f..c440529 100644--- a/packaging/env.example+++ b/packaging/env.example@@ -37,6 +37,9 @@ IPHONE_CONTROL_VIEWER_LAN_HOSTS=IPHONE_CONTROL_VIEWER_TLS=IPHONE_CONTROL_VIEWER_TLS_CERT=IPHONE_CONTROL_VIEWER_TLS_KEY=+# 控制台同一个端口上的 MCP over HTTP(/mcp):on(默认)、off+# MCP over HTTP on the viewer's port (/mcp): on (default), off.+IPHONE_CONTROL_VIEWER_MCP=# 固定控制哪台设备,设了就不能切换。留空为自动选:正在控制的那台一直用到它断开;# 运行中可以用 `iphone-control select` 或 iphone_select_device 工具切换diff --git a/tests/device/mcp_http.py b/tests/device/mcp_http.pynew file mode 100644index 0000000..4fc819c--- /dev/null+++ b/tests/device/mcp_http.py@@ -0,0 +1,29 @@+"""MCP over HTTP for the device scripts: with MCP_URL set (the viewer's `/mcp`, e.g. `http://127.0.0.1:8202/mcp`),+run.py and tasks.py connect there instead of starting `iphone-control mcp` on stdio. A task's token goes in the+`Iphone-Control-Task-Token` header. MCP_CA: a certificate to trust for an `https://` URL (the viewer's self-signed+one, `<data dir>/viewer-tls/cert.pem`)."""++import os+import ssl+from contextlib import AsyncExitStack++import httpx2+from mcp.client.streamable_http import streamable_http_client++URL = os.environ.get("MCP_URL", "")+TOKEN_HEADER = "Iphone-Control-Task-Token"+++async def streams(stack: AsyncExitStack, token: str | None):+ """(read, write) streams of an MCP session at MCP_URL, as the task with `token` (None: no task)"""+ headers = {TOKEN_HEADER: token} if token else None+ ca = os.environ.get("MCP_CA")+ verify = ssl.create_default_context(cafile=ca) if ca else True+ # the SDK's default timeouts (create_mcp_http_client), plus the certificate; never through a proxy from the+ # environment (the viewer is on this machine or the local network)+ client = httpx2.AsyncClient(+ headers=headers, timeout=httpx2.Timeout(30, read=300), verify=verify, trust_env=False+ )+ await stack.enter_async_context(client)+ s = await stack.enter_async_context(streamable_http_client(URL, http_client=client))+ return s[0], s[1]diff --git a/tests/device/run.py b/tests/device/run.pyindex af41c21..436b7f6 100644--- a/tests/device/run.py+++ b/tests/device/run.py@@ -6,7 +6,8 @@ result with its wall time, and save screenshots.python tests/device/run.py '[["iphone_status", {}], ["sleep", 1], ["iphone_screenshot", {}]]'The MCP server command comes from MCP_CMD (default: `iphone-control mcp`; for a build of your branch use its-full path, e.g. `target/release/iphone-control mcp`). Screenshots go to SHOTS_DIR (default: ./shots).+full path, e.g. `target/release/iphone-control mcp`). With MCP_URL set it connects there over HTTP instead (the+viewer's `/mcp`; MCP_CA trusts its self-signed certificate), see mcp_http.py. Screenshots go to SHOTS_DIR (default: ./shots).A step `["sleep", seconds]` waits without calling a tool. Exit code is 1 if any tool returned an error.The last line sums it up (calls, failures, total time): paste the output into the pull request, seeCONTRIBUTING.md, "Required tests".@@ -19,10 +20,13 @@ import osimport shleximport sysimport time+from contextlib import AsyncExitStack, asynccontextmanagerfrom mcp import ClientSessionfrom mcp.client.stdio import StdioServerParameters, stdio_client+import mcp_http+# Harmless by design: no messages, purchases, deletions or settings changes.DEFAULT_STEPS = [["iphone_status", {}],@@ -42,6 +46,17 @@ DEFAULT_STEPS = []+@asynccontextmanager+async def connect(params: StdioServerParameters):+ """The MCP session: over stdio (MCP_CMD), or at MCP_URL over HTTP (with the task's token, if any)"""+ async with AsyncExitStack() as stack:+ if mcp_http.URL:+ r, w = await mcp_http.streams(stack, os.environ.get("IPHONE_CONTROL_TASK_TOKEN"))+ else:+ r, w = await stack.enter_async_context(stdio_client(params))+ yield await stack.enter_async_context(ClientSession(r, w))++async def main() -> int:steps = json.loads(sys.argv[1]) if len(sys.argv) > 1 else DEFAULT_STEPScmd = shlex.split(os.environ.get("MCP_CMD", "iphone-control mcp"))@@ -53,7 +68,7 @@ async def main() -> int:params = StdioServerParameters(command=cmd[0], args=cmd[1:], env=dict(os.environ))calls = 0t0 = time.time()- async with stdio_client(params) as (r, w), ClientSession(r, w) as session:+ async with connect(params) as session:await session.initialize()n = 0for name, args in steps:diff --git a/tests/device/tasks.py b/tests/device/tasks.pyindex 212866c..ebd75af 100644--- a/tests/device/tasks.py+++ b/tests/device/tasks.py@@ -15,7 +15,7 @@ Harmless by design: it presses Home, opens Settings and Clock, takes screenshotsto open (one of them a scheme no app handles). Nothing is sent, bought, deleted or changed.Environment: ICTL_BIN (default `iphone-control`; your branch's build for a pull request), MCP_CMD (default-`$ICTL_BIN mcp`), ICTL_SOCKET (default `$XDG_RUNTIME_DIR/iphone-control/ctl.sock`), ICTL_VIEWER (the control page of+`$ICTL_BIN mcp`; or MCP_URL for MCP over HTTP, see mcp_http.py), ICTL_SOCKET (default `$XDG_RUNTIME_DIR/iphone-control/ctl.sock`), ICTL_VIEWER (the control page ofthe same build, such as `http://127.0.0.1:8202`; the `self` scenario then also tries the page's API from inside atask)."""@@ -33,6 +33,8 @@ from contextlib import AsyncExitStackfrom mcp import ClientSessionfrom mcp.client.stdio import StdioServerParameters, stdio_client+import mcp_http+BIN = shlex.split(os.environ.get("ICTL_BIN", "iphone-control"))MCP_CMD = shlex.split(os.environ.get("MCP_CMD", "")) or [*BIN, "mcp"]SOCKET = os.environ.get("ICTL_SOCKET") or os.path.join(@@ -183,7 +185,10 @@ async def mcp(stack: AsyncExitStack, token: str | None) -> ClientSession:if token:env[TOKEN_ENV] = tokenparams = StdioServerParameters(command=MCP_CMD[0], args=MCP_CMD[1:], env=env)- r, w = await stack.enter_async_context(stdio_client(params))+ if mcp_http.URL:+ r, w = await mcp_http.streams(stack, token)+ else:+ r, w = await stack.enter_async_context(stdio_client(params))s = await stack.enter_async_context(ClientSession(r, w))await s.initialize()return sdiff --git a/website/en/guide/cli.md b/website/en/guide/cli.mdindex d014e0f..4e1faaa 100644--- a/website/en/guide/cli.md+++ b/website/en/guide/cli.md@@ -130,7 +130,7 @@ See [Auto-unlock](./auto-unlock). `--device` takes a UDID or name, and the devic|---|---|| `notify-test [event]` | Send test notifications: one per event type, or one type (`resign`, `session`, `pin`, `pin-recovered`, `unlock`, `offline`, `online`) || `wda-bridge [--port <port>]` | Expose WDA on `127.0.0.1` (default port 8100) for other tools. WDA has no authentication and every local user can reach it, so stop it when done |-| `viewer [--port <port>] [--lan] [--lan-host <name>…] [--tls auto\|on\|off] [--tls-cert <PEM> --tls-key <PEM>]` | Control page in the browser at `http://127.0.0.1:8200/` (default port); with `--lan` also at `https://<this machine's address>:8200/` on the local network (same port; `http://` from the network is sent to `https://`). There is no login yet, so anyone on the network can control the phone. The certificate is a self-signed one made on this machine (kept in `viewer-tls/` in the data directory and reused), so the first time the browser warns that it isn't trusted: check that the SHA-256 fingerprint matches the one printed at startup or by `service status`, then go on. With a certificate of your own (`--tls-cert`/`--tls-key`: mkcert, `tailscale cert`…) there is no warning. With `--tls off` the network gets plain HTTP and the picture falls back to MJPEG (browsers only offer WebCodecs on localhost or HTTPS), in English or Chinese (follows `IPHONE_CONTROL_LANG`, switchable on the page). **Screen:** the live picture works like a touchscreen: click to tap, drag to swipe, hold to long-press, scroll with the mouse wheel or trackpad, plus a text field and the hardware buttons. On iOS 27 and later the finger follows the pointer as it moves (over CoreDevice HID, which keeps the phone awake until 30 seconds after the last touch); older versions get the whole gesture on release. Everything goes through the daemon like an MCP call, so it queues with the agent and unlocks the phone first. On iOS 27 and later the picture is the phone's own video; otherwise it comes from WDA (none until WDA is ready), as H.264 or MJPEG; see [Picture](#viewer-picture) below. Touch is available when the frame matches the measured size and orientation. After rotating or switching devices, start a new gesture on the updated picture. Settings at the bottom of the sidebar controls the theme and text size. The picture has its own zoom controls, the − and + above it (pinching doesn't zoom, so a drag can't turn into one). **Device panel:** state and readiness checks, installed apps, on-screen elements. The page follows the device the daemon controls: switch on the page or anywhere else, and the picture and panels move over; see [Several Devices](./multi-device#control-page). **AI tasks:** type a task and a local agent carries it out (Claude Code or Codex, whichever is on `PATH`; picked on the page). Before it starts you can limit it to some apps with the App button next to the agent; in any other app each step waits for you. You can pause, take over and hand back, or stop it, and it asks on the page before paying, deleting or sending messages. Every local user can reach the port, so stop it when done |+| `viewer [--port <port>] [--lan] [--lan-host <name>…] [--tls auto\|on\|off] [--tls-cert <PEM> --tls-key <PEM>] [--mcp on\|off]` | Control page in the browser (and MCP over HTTP at `/mcp` on the same port, see [Connect an AI Client](./mcp-clients#connect-by-url-http); `--mcp off` turns it off) at `http://127.0.0.1:8200/` (default port); with `--lan` also at `https://<this machine's address>:8200/` on the local network (same port; `http://` from the network is sent to `https://`). There is no login yet, so anyone on the network can control the phone. The certificate is a self-signed one made on this machine (kept in `viewer-tls/` in the data directory and reused), so the first time the browser warns that it isn't trusted: check that the SHA-256 fingerprint matches the one printed at startup or by `service status`, then go on. With a certificate of your own (`--tls-cert`/`--tls-key`: mkcert, `tailscale cert`…) there is no warning. With `--tls off` the network gets plain HTTP and the picture falls back to MJPEG (browsers only offer WebCodecs on localhost or HTTPS), in English or Chinese (follows `IPHONE_CONTROL_LANG`, switchable on the page). **Screen:** the live picture works like a touchscreen: click to tap, drag to swipe, hold to long-press, scroll with the mouse wheel or trackpad, plus a text field and the hardware buttons. On iOS 27 and later the finger follows the pointer as it moves (over CoreDevice HID, which keeps the phone awake until 30 seconds after the last touch); older versions get the whole gesture on release. Everything goes through the daemon like an MCP call, so it queues with the agent and unlocks the phone first. On iOS 27 and later the picture is the phone's own video; otherwise it comes from WDA (none until WDA is ready), as H.264 or MJPEG; see [Picture](#viewer-picture) below. Touch is available when the frame matches the measured size and orientation. After rotating or switching devices, start a new gesture on the updated picture. Settings at the bottom of the sidebar controls the theme and text size. The picture has its own zoom controls, the − and + above it (pinching doesn't zoom, so a drag can't turn into one). **Device panel:** state and readiness checks, installed apps, on-screen elements. The page follows the device the daemon controls: switch on the page or anywhere else, and the picture and panels move over; see [Several Devices](./multi-device#control-page). **AI tasks:** type a task and a local agent carries it out (Claude Code or Codex, whichever is on `PATH`; picked on the page). Before it starts you can limit it to some apps with the App button next to the agent; in any other app each step waits for you. You can pause, take over and hand back, or stop it, and it asks on the page before paying, deleting or sending messages. Every local user can reach the port, so stop it when done || `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 || `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` |diff --git a/website/en/guide/configuration.md b/website/en/guide/configuration.mdindex 07ad76a..4e14062 100644--- a/website/en/guide/configuration.md+++ b/website/en/guide/configuration.md@@ -32,6 +32,7 @@ iphone-control service restart| `IPHONE_CONTROL_VIEWER_LAN` | off | Set to `1` to open the viewer to the local network too, like `viewer --lan`, over HTTPS there. There is no login yet: anyone on the network who can reach this machine can control the phone and start AI tasks, so only on a trusted network || `IPHONE_CONTROL_VIEWER_TLS` | `auto` | The viewer's HTTPS, like `--tls`: `auto` turns it on when open to the network or given a certificate; `on`, `off`. `http://127.0.0.1` on this machine always works || `IPHONE_CONTROL_VIEWER_TLS_CERT`, `IPHONE_CONTROL_VIEWER_TLS_KEY` | empty | The viewer's own certificate and key (PEM), like `--tls-cert`, `--tls-key`; without them a self-signed one made on this machine |+| `IPHONE_CONTROL_VIEWER_MCP` | `on` | MCP over HTTP on the viewer's port (`/mcp`), like `--mcp`; `off` turns it off || `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/mcp-clients.md b/website/en/guide/mcp-clients.mdindex 38ec1ac..af4ce4f 100644--- a/website/en/guide/mcp-clients.md+++ b/website/en/guide/mcp-clients.md@@ -37,7 +37,20 @@ To turn on the [developer tools](./tools#developer-tools-opt-in) or English, addmacOS 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, 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, 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)++The viewer (`iphone-control viewer`, or the service from `service viewer install`) also serves MCP over HTTP (Streamable HTTP) on its port, at `/mcp`, with the same tools as stdio above. For clients that only take a URL, and agents on another computer.++- **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`; in a configuration file `{"type": "http", "url": "http://127.0.0.1:8200/mcp"}`.+- **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).+- **Off**: `viewer --mcp off` (`IPHONE_CONTROL_VIEWER_MCP=off`).++::: warning No login yet+Whoever can open the viewer can use `/mcp`: every user on this machine, and with `--lan` anyone on the network who can reach it. As for the page, only local-network addresses may connect and `Host` is checked; other web pages in a browser can't use it (a request with an `Origin` must come from the page itself).:::## Tips for the agentdiff --git a/website/en/guide/security.md b/website/en/guide/security.mdindex 12e2adf..d2e92d7 100644--- a/website/en/guide/security.md+++ b/website/en/guide/security.md@@ -12,7 +12,7 @@ This page has the essentials. What is stored, who can reach it and the details o## Built-in protections-- **No network ports.** WDA is reached through usbmuxd. `wda-bridge` and the live `viewer` are explicit opt-ins that bind 127.0.0.1 only, and other web pages in your browser can't act through them. They have no login, though: every local user can use them, including starting AI tasks from the viewer, so stop them when done. `viewer --lan` opens the viewer to the local network too, still without a login: anyone on the network who can reach this machine can control the phone. It only accepts connections from local-network addresses; use it only on a trusted network.+- **No network ports.** WDA is reached through usbmuxd. `wda-bridge` and the live `viewer` are explicit opt-ins that bind 127.0.0.1 only, and other web pages in your browser can't act through them. They have no login, though: every local user can use them, including starting AI tasks from the viewer, so stop them when done. `viewer --lan` opens the viewer to the local network too, still without a login: anyone on the network who can reach this machine can control the phone. It only accepts connections from local-network addresses; use it only on a trusted network. The same goes for MCP on the viewer's port (`/mcp`); `--mcp off` turns it off.- **No root.** The daemon runs as your regular user, as a per-user service; the install script refuses to run as root.- **Auto-unlock is off by default** and disables itself after one wrong attempt.- **Developer tools are off by default.**diff --git a/website/guide/cli.md b/website/guide/cli.mdindex d64c9aa..d87f26e 100644--- a/website/guide/cli.md+++ b/website/guide/cli.md@@ -130,7 +130,7 @@ Viewer 只监听本机回环地址。同机其他用户也能查看安装信息|---|---|| `notify-test [事件]` | 发测试通知:每类事件各一条,或只发一类(`resign`、`session`、`pin`、`pin-recovered`、`unlock`、`offline`、`online`) || `wda-bridge [--port <端口>]` | 把 WDA 桥接到 `127.0.0.1`,端口默认 8100,给别的工具用。WDA 没有认证,本机任何用户都能连上,用完就停 |-| `viewer [--port <端口>] [--lan] [--lan-host <名字>…] [--tls auto\|on\|off] [--tls-cert <PEM> --tls-key <PEM>]` | 浏览器里的控制台,地址 `http://127.0.0.1:8200/`(默认端口);加 `--lan` 时局域网里也能用 `https://<这台机器的 IP>:8200/` 打开(同一个端口;局域网来的 `http://` 会跳到 `https://`)。还没有登录,局域网里任何人都能操作手机。证书默认是本机生成的自签证书(存在数据目录的 `viewer-tls/`,一直沿用),浏览器第一次打开会提示不受信任:核对启动时或 `service status` 显示的 SHA-256 指纹一致后继续。用 `--tls-cert`/`--tls-key` 换成自己的证书(mkcert、`tailscale cert` 等)就没有这个提示。`--tls off` 时局域网里是 HTTP,画面退回 MJPEG(浏览器只在 localhost 或 HTTPS 上提供 WebCodecs)。中英文(默认跟着 `IPHONE_CONTROL_LANG`,页面上可切换)。**画面:** 实时画面像触摸屏一样用:点一下是点击,拖动是滑动,按住是长按,滚动鼠标滚轮或触控板也能滚动页面,另有输入框和硬件键。iOS 27 起手指跟着鼠标实时移动(经 CoreDevice HID,最后一次触摸后 30 秒内手机保持亮屏);更低的版本在松开后发整段手势。操作都和 MCP 调用一样经守护进程,和 agent 的操作排队,并先自动解锁。iOS 27 及以上画面直接用手机自己的视频;其余来自 WDA(WDA 没就绪时没有画面),是 H.264 或 MJPEG,见下面的[画面编码](#viewer-picture)。画面与设备实测的尺寸、方向一致时可以点按。转屏或换机后,请在新画面上重新操作。侧栏底部的「设置」可调整主题和字号,画面缩放用画面上方的加减号调整(双指捏合不缩放,免得拖动时误触)。**设备面板:** 状态和就绪检查、已安装的 App、屏幕上的元素。页面跟着守护进程控制的设备走,在页面上或别处切换设备,画面和面板都会跟过去,见[多台设备](./multi-device#control-page)。**AI 任务:** 写下任务,交给本机的 agent 执行(PATH 里有的 Claude Code 或 Codex,在页面上选)。开任务前可以用 Agent 旁边的 App 按钮限定范围,到了别的 App 每一步都先等你确认。可以暂停、接管后交还、停止;付款、删除、发消息之前它会在页面上请你确认。本机任何用户都能连上这个端口,用完就停 |+| `viewer [--port <端口>] [--lan] [--lan-host <名字>…] [--tls auto\|on\|off] [--tls-cert <PEM> --tls-key <PEM>] [--mcp on\|off]` | 浏览器里的控制台,同一个端口的 `/mcp` 还提供 MCP over HTTP(见[接入 AI 客户端](./mcp-clients#通过-url-接入-http),`--mcp off` 关掉),地址 `http://127.0.0.1:8200/`(默认端口);加 `--lan` 时局域网里也能用 `https://<这台机器的 IP>:8200/` 打开(同一个端口;局域网来的 `http://` 会跳到 `https://`)。还没有登录,局域网里任何人都能操作手机。证书默认是本机生成的自签证书(存在数据目录的 `viewer-tls/`,一直沿用),浏览器第一次打开会提示不受信任:核对启动时或 `service status` 显示的 SHA-256 指纹一致后继续。用 `--tls-cert`/`--tls-key` 换成自己的证书(mkcert、`tailscale cert` 等)就没有这个提示。`--tls off` 时局域网里是 HTTP,画面退回 MJPEG(浏览器只在 localhost 或 HTTPS 上提供 WebCodecs)。中英文(默认跟着 `IPHONE_CONTROL_LANG`,页面上可切换)。**画面:** 实时画面像触摸屏一样用:点一下是点击,拖动是滑动,按住是长按,滚动鼠标滚轮或触控板也能滚动页面,另有输入框和硬件键。iOS 27 起手指跟着鼠标实时移动(经 CoreDevice HID,最后一次触摸后 30 秒内手机保持亮屏);更低的版本在松开后发整段手势。操作都和 MCP 调用一样经守护进程,和 agent 的操作排队,并先自动解锁。iOS 27 及以上画面直接用手机自己的视频;其余来自 WDA(WDA 没就绪时没有画面),是 H.264 或 MJPEG,见下面的[画面编码](#viewer-picture)。画面与设备实测的尺寸、方向一致时可以点按。转屏或换机后,请在新画面上重新操作。侧栏底部的「设置」可调整主题和字号,画面缩放用画面上方的加减号调整(双指捏合不缩放,免得拖动时误触)。**设备面板:** 状态和就绪检查、已安装的 App、屏幕上的元素。页面跟着守护进程控制的设备走,在页面上或别处切换设备,画面和面板都会跟过去,见[多台设备](./multi-device#control-page)。**AI 任务:** 写下任务,交给本机的 agent 执行(PATH 里有的 Claude Code 或 Codex,在页面上选)。开任务前可以用 Agent 旁边的 App 按钮限定范围,到了别的 App 每一步都先等你确认。可以暂停、接管后交还、停止;付款、删除、发消息之前它会在页面上请你确认。本机任何用户都能连上这个端口,用完就停 || `task run [--title <标题>] [--app <App>…] -- <命令>` | 给别的 agent 平台用的 AI 任务:在当前控制的设备上开一个任务,再运行这条命令。命令启动的 `iphone-control mcp` 自动加入任务(经环境变量 `IPHONE_CONTROL_TASK_TOKEN`),控制台上能看到每一步,可以暂停、接管、停止,付款、发消息之前会等你确认。命令结束,任务就结束;任务在别处被停止,命令也会被停止;按 Ctrl-C 等于停止任务。任务进行中,其他客户端只能看,不能操作手机。`--app`(可写多次,App 名或 Bundle ID)把任务限定在这些 App 里:到了别的 App、或者要打开网页以外的链接,每一步都先等你确认 || `task list` / `task events <id>` | 最近的任务(`--json` 给程序读);跟着一个任务的事件,每行一个 JSON || `task pause\|resume\|takeover\|handback\|stop <id>`、`task approve\|reject <id>` | 在命令行里控制任务,和控制台上的按钮一样。只能由人来做:在任务里面(Agent 的环境或它启动的进程)执行会被拒绝,`stop` 除外 |diff --git a/website/guide/configuration.md b/website/guide/configuration.mdindex 7f20810..aa748e8 100644--- a/website/guide/configuration.md+++ b/website/guide/configuration.md@@ -32,6 +32,7 @@ iphone-control service restart| `IPHONE_CONTROL_VIEWER_LAN` | 关 | 设为 `1` 时控制台也对局域网开放,同 `viewer --lan`,局域网里用 HTTPS。还没有登录:局域网里任何能连上这台机器的人都能操作手机、开 AI 任务,只在可信的网络里开 || `IPHONE_CONTROL_VIEWER_TLS` | `auto` | 控制台的 HTTPS,同 `--tls`:`auto` 在对局域网开放或给了证书时开启,`on`、`off`。本机的 `http://127.0.0.1` 一直能用 || `IPHONE_CONTROL_VIEWER_TLS_CERT`、`IPHONE_CONTROL_VIEWER_TLS_KEY` | 空 | 控制台用自己的证书和私钥(PEM),同 `--tls-cert`、`--tls-key`;不设就用本机生成的自签证书 |+| `IPHONE_CONTROL_VIEWER_MCP` | `on` | 控制台同一个端口上的 MCP over HTTP(`/mcp`),同 `--mcp`;`off` 关掉 || `IPHONE_UDID` | 自动选 | 固定控制哪台设备。不设时自动选:正在控制的那台一直用到它断开;运行中可以用 `select` 命令或 `iphone_select_device` 工具切换。设了就不能切换 || `RESIGN_MIN_DAYS` | `2` | 描述文件剩余不到几天时重签 || `RESIGN_CHECK_HOURS` | `6` | 每隔几小时检查一次;手机重新连上或切换设备后 1 分钟内也查一次 |diff --git a/website/guide/mcp-clients.md b/website/guide/mcp-clients.mdindex ee8a47d..b27168d 100644--- a/website/guide/mcp-clients.md+++ b/website/guide/mcp-clients.md@@ -37,7 +37,20 @@ codex mcp add iphone -- /path/to/iphone-control --socket <路径> mcpmacOS 上没有 `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 找守护进程。客户端在另一台电脑上时,用 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),或者用 SSH 拉起,后面跟那台主机上 `mcp-config` 打印的程序路径和参数,例如 `"command": "ssh", "args": ["主机", "/home/you/.local/bin/iphone-control", "--socket", "/run/user/1000/iphone-control/ctl.sock", "mcp"]`。+:::++## 通过 URL 接入(HTTP)++控制台(`iphone-control viewer`,或装成服务的 `service viewer install`)在同一个端口上还提供 MCP over HTTP(Streamable HTTP),路径是 `/mcp`,工具和上面的 stdio 方式完全一样。适合只能填 URL 的客户端,以及另一台电脑上的 agent。++- **本机**:`http://127.0.0.1:8200/mcp`(端口跟着控制台)。Claude Code:`claude mcp add --transport http iphone http://127.0.0.1:8200/mcp`;配置文件里写 `{"type": "http", "url": "http://127.0.0.1:8200/mcp"}`。+- **局域网里另一台电脑**:控制台要开 `--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`)。+- **关掉**:`viewer --mcp off`(`IPHONE_CONTROL_VIEWER_MCP=off`)。++::: warning 还没有登录+能打开控制台的人就能用 `/mcp`:本机是本机所有用户,开了 `--lan` 就是局域网里所有能连上这台机器的人。和控制台一样只接受局域网地址来的连接、检查 `Host`;浏览器里别的网页借不了它(带 `Origin` 的请求必须来自控制台自己)。:::## 给 agent 的建议diff --git a/website/guide/security.md b/website/guide/security.mdindex e2d1db9..ff5a265 100644--- a/website/guide/security.md+++ b/website/guide/security.md@@ -12,7 +12,7 @@ iphone-control 本质上是一个手机遥控器:能访问它的人,就能## 默认的保护-- **不开网络端口。** WDA 经 usbmuxd 直连手机。`wda-bridge` 和实时画面 `viewer` 都要显式开启,只绑 127.0.0.1,浏览器里的其他网页借不了它们操作手机。但它们没有登录,本机任何用户都能用(包括在 viewer 上发起 AI 任务),用完就停。`viewer --lan` 会把控制台也开放给局域网,仍然没有登录,局域网里任何能连上这台机器的人都能操作手机;只接受局域网地址来的连接,只在可信的网络里开。+- **不开网络端口。** WDA 经 usbmuxd 直连手机。`wda-bridge` 和实时画面 `viewer` 都要显式开启,只绑 127.0.0.1,浏览器里的其他网页借不了它们操作手机。但它们没有登录,本机任何用户都能用(包括在 viewer 上发起 AI 任务),用完就停。`viewer --lan` 会把控制台也开放给局域网,仍然没有登录,局域网里任何能连上这台机器的人都能操作手机;只接受局域网地址来的连接,只在可信的网络里开。控制台同一个端口上的 MCP(`/mcp`)也一样,`--mcp off` 关掉。- **不用 root。** 守护进程以你的普通用户身份作为用户服务运行,安装脚本拒绝以 root 运行。- **自动解锁默认关闭**,输错一次即停用。- **开发者工具默认关闭**。