iphone-mcp 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- iphone_mcp/__init__.py +3 -0
- iphone_mcp/__main__.py +5 -0
- iphone_mcp/cli.py +150 -0
- iphone_mcp/connection.py +383 -0
- iphone_mcp/paths.py +41 -0
- iphone_mcp/server.py +458 -0
- iphone_mcp/setup_wda.py +261 -0
- iphone_mcp/wda.py +167 -0
- iphone_mcp/xctest_launcher.py +164 -0
- iphone_mcp-0.1.0.dist-info/METADATA +329 -0
- iphone_mcp-0.1.0.dist-info/RECORD +14 -0
- iphone_mcp-0.1.0.dist-info/WHEEL +4 -0
- iphone_mcp-0.1.0.dist-info/entry_points.txt +2 -0
- iphone_mcp-0.1.0.dist-info/licenses/LICENSE +674 -0
iphone_mcp/__init__.py
ADDED
iphone_mcp/__main__.py
ADDED
iphone_mcp/cli.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Command line: `iphone-mcp [serve|setup|doctor|start|stop]`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import asyncio
|
|
7
|
+
import shutil
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
from . import __version__, paths
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _doctor() -> int:
|
|
15
|
+
from .connection import Connection, coredevice_devices
|
|
16
|
+
from .setup_wda import find_teams
|
|
17
|
+
|
|
18
|
+
ok = True
|
|
19
|
+
|
|
20
|
+
def line(good: bool | None, text: str) -> None:
|
|
21
|
+
nonlocal ok
|
|
22
|
+
mark = "✓" if good else ("•" if good is None else "✗")
|
|
23
|
+
ok = ok and good is not False
|
|
24
|
+
print(f"{mark} {text}")
|
|
25
|
+
|
|
26
|
+
line(True, f"iphone-mcp {__version__} on {sys.platform}")
|
|
27
|
+
if paths.IS_MAC:
|
|
28
|
+
xb = shutil.which("xcodebuild")
|
|
29
|
+
ver = (
|
|
30
|
+
subprocess.run(["xcodebuild", "-version"], capture_output=True, text=True).stdout.split("\n")[0]
|
|
31
|
+
if xb
|
|
32
|
+
else ""
|
|
33
|
+
)
|
|
34
|
+
line(bool(ver), ver or "Xcode not found (needed for setup/start)")
|
|
35
|
+
teams = find_teams()
|
|
36
|
+
line(
|
|
37
|
+
bool(teams),
|
|
38
|
+
f"Signing teams: {', '.join(teams)}"
|
|
39
|
+
if teams
|
|
40
|
+
else "No 'Apple Development' certificate (Xcode → Settings → Accounts)",
|
|
41
|
+
)
|
|
42
|
+
devices = asyncio.run(coredevice_devices())
|
|
43
|
+
if not devices:
|
|
44
|
+
line(False, "No iPhone known to Xcode – connect it by cable once and tap 'Trust'")
|
|
45
|
+
for d in devices:
|
|
46
|
+
reach = d.get("tunnelState") != "unavailable"
|
|
47
|
+
via = {"wired": "cable", "localNetwork": "Wi-Fi"}.get(d.get("transportType"), d.get("transportType") or "-")
|
|
48
|
+
line(
|
|
49
|
+
reach,
|
|
50
|
+
f"{d['name']} ({d.get('model')}, iOS {d.get('os')}): {d.get('tunnelState')} via {via}, developer mode {d.get('developerMode')}",
|
|
51
|
+
)
|
|
52
|
+
else:
|
|
53
|
+
line(None, "Not macOS: WebDriverAgent is launched without Xcode (pymobiledevice3)")
|
|
54
|
+
conn = Connection()
|
|
55
|
+
for dev in asyncio.run(conn.usbmux_devices()):
|
|
56
|
+
line(True, f"usbmux sees {dev.serial} via {dev.connection_type}")
|
|
57
|
+
|
|
58
|
+
cfg = paths.load(paths.WDA_FILE)
|
|
59
|
+
launcher = conn.launcher
|
|
60
|
+
if launcher == "xcodebuild":
|
|
61
|
+
built = bool(list(paths.WDA_DERIVED.glob("Build/Products/*.xctestrun")))
|
|
62
|
+
line(
|
|
63
|
+
built,
|
|
64
|
+
f"WebDriverAgent built with Xcode for {cfg.get('udid')} (team {cfg.get('team')})"
|
|
65
|
+
if built
|
|
66
|
+
else "WebDriverAgent not built yet – run: iphone-mcp setup",
|
|
67
|
+
)
|
|
68
|
+
else:
|
|
69
|
+
runner = cfg.get("runner_bundle_id")
|
|
70
|
+
line(
|
|
71
|
+
bool(runner) or None,
|
|
72
|
+
f"Launch without Xcode, runner {runner}"
|
|
73
|
+
if runner
|
|
74
|
+
else "Launch without Xcode – install WebDriverAgent first: iphone-mcp setup --prebuilt, then --ipa",
|
|
75
|
+
)
|
|
76
|
+
line(True, f"Keep-awake during sessions: {'on' if conn.keep_awake else 'off'}")
|
|
77
|
+
|
|
78
|
+
async def probe() -> str:
|
|
79
|
+
try:
|
|
80
|
+
await conn.get()
|
|
81
|
+
return f"WebDriverAgent reachable via {conn.transport}"
|
|
82
|
+
except Exception as e: # noqa: BLE001
|
|
83
|
+
return f"WebDriverAgent not running ({str(e).split('.')[0]}) – the agent starts it with iphone_start_agent"
|
|
84
|
+
|
|
85
|
+
msg = asyncio.run(probe())
|
|
86
|
+
line(True if msg.startswith("WebDriverAgent reachable") else None, msg)
|
|
87
|
+
return 0 if ok else 1
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _start() -> int:
|
|
91
|
+
from .connection import Connection
|
|
92
|
+
|
|
93
|
+
async def go() -> str:
|
|
94
|
+
return await Connection().start_wda()
|
|
95
|
+
|
|
96
|
+
try:
|
|
97
|
+
print(asyncio.run(go()))
|
|
98
|
+
print("xcodebuild keeps running in the background; stop it with: iphone-mcp stop")
|
|
99
|
+
return 0
|
|
100
|
+
except Exception as e: # noqa: BLE001
|
|
101
|
+
print(f"✗ {e}", file=sys.stderr)
|
|
102
|
+
return 1
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _stop() -> int:
|
|
106
|
+
from .connection import Connection
|
|
107
|
+
|
|
108
|
+
print(asyncio.run(Connection().stop_wda()))
|
|
109
|
+
return 0
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def main(argv: list[str] | None = None) -> int:
|
|
113
|
+
parser = argparse.ArgumentParser(prog="iphone-mcp", description="Control a real iPhone from MCP clients.")
|
|
114
|
+
parser.add_argument("--version", action="version", version=__version__)
|
|
115
|
+
sub = parser.add_subparsers(dest="command")
|
|
116
|
+
sub.add_parser("serve", help="run the MCP server on stdio (default)")
|
|
117
|
+
p_setup = sub.add_parser("setup", help="build and install WebDriverAgent on your iPhone (macOS)")
|
|
118
|
+
p_setup.add_argument("--udid", help="device UDID if several iPhones are connected")
|
|
119
|
+
p_setup.add_argument("--team", help="Apple team ID used for signing")
|
|
120
|
+
p_setup.add_argument("--bundle-id", help="bundle ID for the WebDriverAgent runner")
|
|
121
|
+
p_setup.add_argument(
|
|
122
|
+
"--prebuilt",
|
|
123
|
+
action="store_true",
|
|
124
|
+
help="no Xcode: download Appium's prebuilt WebDriverAgent for you to sign (default on Linux/Windows)",
|
|
125
|
+
)
|
|
126
|
+
p_setup.add_argument("--ipa", help="no Xcode: install this signed WebDriverAgent .ipa over USB")
|
|
127
|
+
sub.add_parser("doctor", help="check Xcode, signing, iPhone and connection")
|
|
128
|
+
sub.add_parser("start", help="start WebDriverAgent without an MCP client")
|
|
129
|
+
sub.add_parser("stop", help="stop WebDriverAgent")
|
|
130
|
+
args = parser.parse_args(argv)
|
|
131
|
+
|
|
132
|
+
if args.command == "setup":
|
|
133
|
+
from .setup_wda import run
|
|
134
|
+
|
|
135
|
+
return run(args.udid, args.team, args.bundle_id, prebuilt=args.prebuilt, ipa=args.ipa)
|
|
136
|
+
if args.command == "doctor":
|
|
137
|
+
return _doctor()
|
|
138
|
+
if args.command == "start":
|
|
139
|
+
return _start()
|
|
140
|
+
if args.command == "stop":
|
|
141
|
+
return _stop()
|
|
142
|
+
|
|
143
|
+
from .server import serve
|
|
144
|
+
|
|
145
|
+
serve()
|
|
146
|
+
return 0
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
if __name__ == "__main__":
|
|
150
|
+
sys.exit(main())
|
iphone_mcp/connection.py
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
"""Finding and keeping a connection to WebDriverAgent on the iPhone.
|
|
2
|
+
|
|
3
|
+
Order of attempts:
|
|
4
|
+
1. IPHONE_MCP_WDA_URL (fixed address, works on any OS)
|
|
5
|
+
2. Xcode's CoreDevice tunnel (macOS; same address over cable *and* Wi-Fi)
|
|
6
|
+
3. usbmux port forwarding (USB, or Wi-Fi sync)
|
|
7
|
+
4. Last known Wi-Fi IP of the iPhone
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import glob
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import shutil
|
|
17
|
+
import signal
|
|
18
|
+
import socket
|
|
19
|
+
import subprocess
|
|
20
|
+
import tempfile
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
from . import paths
|
|
24
|
+
from .wda import WDAClient, WDAError
|
|
25
|
+
|
|
26
|
+
WDA_PORT = 8100
|
|
27
|
+
KEEP_AWAKE_INTERVAL = 10 # seconds; iOS Auto-Lock is at least 30 s
|
|
28
|
+
NOT_CONNECTED = (
|
|
29
|
+
"No connection to WebDriverAgent on the iPhone. Call iphone_start_agent first "
|
|
30
|
+
"(iPhone on USB or on the same Wi-Fi as this computer, unlocked)."
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _free_port(preferred: int) -> int:
|
|
35
|
+
for port in (preferred, 0):
|
|
36
|
+
with socket.socket() as s:
|
|
37
|
+
try:
|
|
38
|
+
s.bind(("127.0.0.1", port))
|
|
39
|
+
return s.getsockname()[1]
|
|
40
|
+
except OSError:
|
|
41
|
+
continue
|
|
42
|
+
raise RuntimeError("No free local port")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def url_host(ip: str) -> str:
|
|
46
|
+
return f"[{ip}]" if ":" in ip else ip
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
async def coredevice_devices() -> list[dict]:
|
|
50
|
+
"""Physical iOS devices known to Xcode (`xcrun devicectl list devices`). Empty off macOS."""
|
|
51
|
+
if not paths.IS_MAC or not shutil.which("xcrun"):
|
|
52
|
+
return []
|
|
53
|
+
with tempfile.NamedTemporaryFile(suffix=".json") as tmp:
|
|
54
|
+
try:
|
|
55
|
+
proc = await asyncio.create_subprocess_exec(
|
|
56
|
+
"xcrun",
|
|
57
|
+
"devicectl",
|
|
58
|
+
"list",
|
|
59
|
+
"devices",
|
|
60
|
+
"--json-output",
|
|
61
|
+
tmp.name,
|
|
62
|
+
stdout=asyncio.subprocess.DEVNULL,
|
|
63
|
+
stderr=asyncio.subprocess.DEVNULL,
|
|
64
|
+
)
|
|
65
|
+
await asyncio.wait_for(proc.wait(), 30)
|
|
66
|
+
data = json.loads(Path(tmp.name).read_text())
|
|
67
|
+
except Exception:
|
|
68
|
+
return []
|
|
69
|
+
result = []
|
|
70
|
+
for dev in data.get("result", {}).get("devices", []):
|
|
71
|
+
hw = dev.get("hardwareProperties", {})
|
|
72
|
+
if hw.get("platform") != "iOS" or hw.get("reality") != "physical":
|
|
73
|
+
continue
|
|
74
|
+
dp = dev.get("deviceProperties") or {}
|
|
75
|
+
props = dict(dev.get("connectionProperties") or {})
|
|
76
|
+
props.update(
|
|
77
|
+
udid=hw.get("udid"),
|
|
78
|
+
name=dp.get("name"),
|
|
79
|
+
model=hw.get("marketingName"),
|
|
80
|
+
os=dp.get("osVersionNumber"),
|
|
81
|
+
developerMode=dp.get("developerModeStatus"),
|
|
82
|
+
)
|
|
83
|
+
result.append(props)
|
|
84
|
+
return result
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class Connection:
|
|
88
|
+
"""Holds exactly one live connection to WebDriverAgent."""
|
|
89
|
+
|
|
90
|
+
def __init__(self) -> None:
|
|
91
|
+
self.mode = os.environ.get("IPHONE_MCP_MODE", "auto").lower() # auto | usb | wifi
|
|
92
|
+
self.udid = os.environ.get("IPHONE_MCP_UDID") or paths.load(paths.WDA_FILE).get("udid")
|
|
93
|
+
self.manual_url = os.environ.get("IPHONE_MCP_WDA_URL")
|
|
94
|
+
self.client: WDAClient | None = None
|
|
95
|
+
self.transport: str = "-"
|
|
96
|
+
self._forwarder = None
|
|
97
|
+
self._forward_task: asyncio.Task | None = None
|
|
98
|
+
self._lock = asyncio.Lock()
|
|
99
|
+
self._proc: subprocess.Popen | None = None
|
|
100
|
+
cfg = paths.load(paths.WDA_FILE)
|
|
101
|
+
default_launcher = (
|
|
102
|
+
"xcodebuild" if paths.IS_MAC and cfg.get("launcher", "xcodebuild") == "xcodebuild" else "pymobiledevice3"
|
|
103
|
+
)
|
|
104
|
+
self.launcher = os.environ.get("IPHONE_MCP_LAUNCHER", default_launcher).lower()
|
|
105
|
+
self._xct = None # XCTestLauncher when WebDriverAgent was started without Xcode
|
|
106
|
+
self.keep_awake = os.environ.get("IPHONE_MCP_KEEP_AWAKE", "1").lower() not in ("0", "false", "no", "off")
|
|
107
|
+
self._keep_awake_task: asyncio.Task | None = None
|
|
108
|
+
|
|
109
|
+
# ---------- discovery ----------
|
|
110
|
+
async def coredevice_info(self) -> dict | None:
|
|
111
|
+
for dev in await coredevice_devices():
|
|
112
|
+
if not self.udid or dev["udid"] == self.udid:
|
|
113
|
+
return dev
|
|
114
|
+
return None
|
|
115
|
+
|
|
116
|
+
async def usbmux_devices(self) -> list:
|
|
117
|
+
try:
|
|
118
|
+
from pymobiledevice3 import usbmux
|
|
119
|
+
|
|
120
|
+
devices = await usbmux.list_devices()
|
|
121
|
+
except Exception:
|
|
122
|
+
return []
|
|
123
|
+
if self.udid:
|
|
124
|
+
devices = [d for d in devices if d.serial == self.udid]
|
|
125
|
+
return sorted(devices, key=lambda d: 0 if d.connection_type == "USB" else 1)
|
|
126
|
+
|
|
127
|
+
async def _start_forward(self, serial: str, connection_type: str) -> int:
|
|
128
|
+
from pymobiledevice3.tcp_forwarder import UsbmuxTcpForwarder
|
|
129
|
+
|
|
130
|
+
await self._stop_forward()
|
|
131
|
+
port = _free_port(WDA_PORT)
|
|
132
|
+
ready = asyncio.Event()
|
|
133
|
+
self._forwarder = UsbmuxTcpForwarder(
|
|
134
|
+
serial, WDA_PORT, port, listening_event=ready, usbmux_connection_type=connection_type
|
|
135
|
+
)
|
|
136
|
+
self._forward_task = asyncio.create_task(self._forwarder.start())
|
|
137
|
+
await asyncio.wait_for(ready.wait(), 5)
|
|
138
|
+
return port
|
|
139
|
+
|
|
140
|
+
async def _stop_forward(self) -> None:
|
|
141
|
+
if self._forwarder is not None:
|
|
142
|
+
try:
|
|
143
|
+
self._forwarder.stop()
|
|
144
|
+
except Exception:
|
|
145
|
+
pass
|
|
146
|
+
if self._forward_task is not None:
|
|
147
|
+
self._forward_task.cancel()
|
|
148
|
+
self._forwarder = self._forward_task = None
|
|
149
|
+
|
|
150
|
+
async def _try(self, url: str, transport: str) -> WDAClient | None:
|
|
151
|
+
client = WDAClient(url, timeout=30)
|
|
152
|
+
try:
|
|
153
|
+
st = await asyncio.wait_for(client.status(), 4)
|
|
154
|
+
except (TimeoutError, WDAError):
|
|
155
|
+
await client.close()
|
|
156
|
+
return None
|
|
157
|
+
ip = (st.get("ios") or {}).get("ip") if isinstance(st, dict) else None
|
|
158
|
+
if ip:
|
|
159
|
+
paths.update(paths.STATE_FILE, last_ip=ip)
|
|
160
|
+
if self.client is not None and self.client is not client:
|
|
161
|
+
await self.client.close()
|
|
162
|
+
self.client, self.transport = client, transport
|
|
163
|
+
self._ensure_keep_awake()
|
|
164
|
+
return client
|
|
165
|
+
|
|
166
|
+
# ---------- keep the screen awake ----------
|
|
167
|
+
def _ensure_keep_awake(self) -> None:
|
|
168
|
+
if self.keep_awake and (self._keep_awake_task is None or self._keep_awake_task.done()):
|
|
169
|
+
self._keep_awake_task = asyncio.get_running_loop().create_task(self._keep_awake_loop())
|
|
170
|
+
|
|
171
|
+
async def _keep_awake_loop(self) -> None:
|
|
172
|
+
"""Reset the iPhone's idle timer while this server is connected.
|
|
173
|
+
|
|
174
|
+
A 1 ms touch just outside the screen counts as user activity for iOS but hits no UI
|
|
175
|
+
(verified: unlike a status-bar tap it does not even scroll to top). Skipped while locked.
|
|
176
|
+
"""
|
|
177
|
+
while self.keep_awake:
|
|
178
|
+
await asyncio.sleep(KEEP_AWAKE_INTERVAL)
|
|
179
|
+
client = self.client
|
|
180
|
+
if client is None:
|
|
181
|
+
continue
|
|
182
|
+
try:
|
|
183
|
+
if not await client.is_locked():
|
|
184
|
+
await client.tap(-5, -5, hold_ms=1)
|
|
185
|
+
except Exception: # noqa: BLE001 - connection hiccups are handled by get()
|
|
186
|
+
pass
|
|
187
|
+
|
|
188
|
+
def set_keep_awake(self, enabled: bool) -> None:
|
|
189
|
+
self.keep_awake = enabled
|
|
190
|
+
if enabled:
|
|
191
|
+
if self.client is not None:
|
|
192
|
+
self._ensure_keep_awake()
|
|
193
|
+
elif self._keep_awake_task is not None:
|
|
194
|
+
self._keep_awake_task.cancel()
|
|
195
|
+
self._keep_awake_task = None
|
|
196
|
+
|
|
197
|
+
# ---------- public ----------
|
|
198
|
+
async def get(self) -> WDAClient:
|
|
199
|
+
async with self._lock:
|
|
200
|
+
if self.client is not None:
|
|
201
|
+
try:
|
|
202
|
+
await asyncio.wait_for(self.client.status(), 4)
|
|
203
|
+
return self.client
|
|
204
|
+
except (TimeoutError, WDAError):
|
|
205
|
+
await self.client.close()
|
|
206
|
+
self.client = None
|
|
207
|
+
await self._stop_forward()
|
|
208
|
+
|
|
209
|
+
if self.manual_url:
|
|
210
|
+
if c := await self._try(self.manual_url, f"fixed URL ({self.manual_url})"):
|
|
211
|
+
return c
|
|
212
|
+
|
|
213
|
+
if self._xct is not None and self._xct.url:
|
|
214
|
+
if c := await self._try(self._xct.url, self._xct.transport):
|
|
215
|
+
return c
|
|
216
|
+
|
|
217
|
+
info = await self.coredevice_info()
|
|
218
|
+
if info and info.get("tunnelState") == "connected" and info.get("tunnelIPAddress"):
|
|
219
|
+
kind = "USB" if info.get("transportType") == "wired" else "Wi-Fi"
|
|
220
|
+
allowed = self.mode == "auto" or (self.mode == "usb") == (kind == "USB")
|
|
221
|
+
url = f"http://{url_host(info['tunnelIPAddress'])}:{WDA_PORT}"
|
|
222
|
+
if allowed and (c := await self._try(url, f"{kind} (Xcode tunnel)")):
|
|
223
|
+
return c
|
|
224
|
+
|
|
225
|
+
if self.mode in ("auto", "usb"):
|
|
226
|
+
for dev in await self.usbmux_devices():
|
|
227
|
+
try:
|
|
228
|
+
port = await self._start_forward(dev.serial, dev.connection_type)
|
|
229
|
+
except Exception:
|
|
230
|
+
continue
|
|
231
|
+
label = "USB (usbmux)" if dev.connection_type == "USB" else "Wi-Fi (usbmux)"
|
|
232
|
+
if c := await self._try(f"http://127.0.0.1:{port}", label):
|
|
233
|
+
return c
|
|
234
|
+
await self._stop_forward()
|
|
235
|
+
|
|
236
|
+
if self.mode in ("auto", "wifi"):
|
|
237
|
+
ip = paths.load(paths.STATE_FILE).get("last_ip")
|
|
238
|
+
if ip:
|
|
239
|
+
if c := await self._try(f"http://{url_host(ip)}:{WDA_PORT}", f"Wi-Fi ({ip})"):
|
|
240
|
+
return c
|
|
241
|
+
|
|
242
|
+
raise WDAError(NOT_CONNECTED)
|
|
243
|
+
|
|
244
|
+
# ---------- WebDriverAgent process (macOS only) ----------
|
|
245
|
+
def wda_running_pid(self) -> int | None:
|
|
246
|
+
if self._proc is not None:
|
|
247
|
+
return self._proc.pid if self._proc.poll() is None else None
|
|
248
|
+
pid = paths.load(paths.STATE_FILE).get("wda_pid")
|
|
249
|
+
if not pid:
|
|
250
|
+
return None
|
|
251
|
+
try:
|
|
252
|
+
os.kill(pid, 0)
|
|
253
|
+
return pid
|
|
254
|
+
except OSError:
|
|
255
|
+
return None
|
|
256
|
+
|
|
257
|
+
async def start_wda(self, timeout: float = 150) -> str:
|
|
258
|
+
try:
|
|
259
|
+
await self.get()
|
|
260
|
+
return f"WebDriverAgent is already running, connected via {self.transport}."
|
|
261
|
+
except WDAError:
|
|
262
|
+
pass
|
|
263
|
+
|
|
264
|
+
if self.launcher != "xcodebuild":
|
|
265
|
+
return await self._start_without_xcode(timeout)
|
|
266
|
+
cfg = paths.load(paths.WDA_FILE)
|
|
267
|
+
udid = self.udid or cfg.get("udid")
|
|
268
|
+
runs = sorted(glob.glob(os.path.join(cfg.get("derived_data") or "", "Build/Products/*.xctestrun")))
|
|
269
|
+
if not runs or not udid:
|
|
270
|
+
raise WDAError("WebDriverAgent is not built yet. Run once in a terminal: iphone-mcp setup")
|
|
271
|
+
|
|
272
|
+
if self.wda_running_pid() and self._proc is None:
|
|
273
|
+
await self.stop_wda() # leftover xcodebuild from an earlier run without a reachable WDA
|
|
274
|
+
|
|
275
|
+
def launch() -> None:
|
|
276
|
+
log = open(paths.WDA_LOG, "a")
|
|
277
|
+
self._proc = subprocess.Popen(
|
|
278
|
+
["xcodebuild", "test-without-building", "-xctestrun", runs[-1], "-destination", f"id={udid}"],
|
|
279
|
+
stdout=log,
|
|
280
|
+
stderr=subprocess.STDOUT,
|
|
281
|
+
stdin=subprocess.DEVNULL,
|
|
282
|
+
start_new_session=True,
|
|
283
|
+
)
|
|
284
|
+
paths.update(paths.STATE_FILE, wda_pid=self._proc.pid)
|
|
285
|
+
|
|
286
|
+
if not self.wda_running_pid(): # an xcodebuild of ours may still be waiting, e.g. for an unlock
|
|
287
|
+
paths.LOG_DIR.mkdir(parents=True, exist_ok=True)
|
|
288
|
+
paths.WDA_LOG.write_text("")
|
|
289
|
+
launch()
|
|
290
|
+
attempts = 1
|
|
291
|
+
loop = asyncio.get_running_loop()
|
|
292
|
+
deadline = loop.time() + timeout
|
|
293
|
+
while loop.time() < deadline:
|
|
294
|
+
try:
|
|
295
|
+
await self.get()
|
|
296
|
+
return f"WebDriverAgent is running, connected via {self.transport}."
|
|
297
|
+
except WDAError:
|
|
298
|
+
log = paths.WDA_LOG.read_text(errors="ignore")
|
|
299
|
+
if log.rfind("because the device is locked") > log.rfind("ServerURLHere"):
|
|
300
|
+
# xcodebuild keeps waiting and continues by itself once the iPhone is unlocked
|
|
301
|
+
raise WDAError(
|
|
302
|
+
"The iPhone is locked, so Xcode cannot start WebDriverAgent. Ask the user to unlock it "
|
|
303
|
+
"(passcode / Face ID), then call iphone_start_agent again."
|
|
304
|
+
) from None
|
|
305
|
+
if not self.wda_running_pid():
|
|
306
|
+
# e.g. the cable flaked or the Wi-Fi tunnel was still coming up: retry
|
|
307
|
+
if attempts >= 4:
|
|
308
|
+
tail = paths.WDA_LOG.read_text()[-1500:]
|
|
309
|
+
raise WDAError(f"xcodebuild exited {attempts} times. End of {paths.WDA_LOG}:\n{tail}") from None
|
|
310
|
+
attempts += 1
|
|
311
|
+
await asyncio.sleep(3)
|
|
312
|
+
launch()
|
|
313
|
+
await asyncio.sleep(3)
|
|
314
|
+
raise WDAError(f"WebDriverAgent not ready after {timeout:.0f}s. Log: {paths.WDA_LOG}")
|
|
315
|
+
|
|
316
|
+
async def _start_without_xcode(self, timeout: float) -> str:
|
|
317
|
+
"""Launch through pymobiledevice3 (no Xcode; works on Linux and Windows too)."""
|
|
318
|
+
from .xctest_launcher import XCTestLauncher
|
|
319
|
+
|
|
320
|
+
cfg = paths.load(paths.WDA_FILE)
|
|
321
|
+
if self._xct is None or not self._xct.running:
|
|
322
|
+
if self._xct is not None:
|
|
323
|
+
await self._xct.stop()
|
|
324
|
+
self._xct = XCTestLauncher(
|
|
325
|
+
udid=self.udid or cfg.get("udid"),
|
|
326
|
+
runner_bundle_id=os.environ.get("IPHONE_MCP_RUNNER_BUNDLE_ID") or cfg.get("runner_bundle_id"),
|
|
327
|
+
wifi=self.mode == "wifi",
|
|
328
|
+
)
|
|
329
|
+
try:
|
|
330
|
+
await asyncio.wait_for(self._xct.start(), 60)
|
|
331
|
+
except Exception as e: # noqa: BLE001
|
|
332
|
+
await self._xct.stop()
|
|
333
|
+
self._xct = None
|
|
334
|
+
hint = " Is the iPhone unlocked?" if "lock" in str(e).lower() else ""
|
|
335
|
+
raise WDAError(f"Could not launch WebDriverAgent via pymobiledevice3: {e!r}.{hint}") from None
|
|
336
|
+
loop = asyncio.get_running_loop()
|
|
337
|
+
deadline = loop.time() + timeout
|
|
338
|
+
while loop.time() < deadline:
|
|
339
|
+
if (err := self._xct.runner_failed) is not None:
|
|
340
|
+
await self._xct.stop()
|
|
341
|
+
self._xct = None
|
|
342
|
+
raise WDAError(
|
|
343
|
+
f"WebDriverAgent runner stopped: {err!r}. Unlock the iPhone and check that "
|
|
344
|
+
"Settings → Developer → Enable UI Automation is on."
|
|
345
|
+
)
|
|
346
|
+
try:
|
|
347
|
+
await self.get()
|
|
348
|
+
return f"WebDriverAgent is running (started without Xcode), connected via {self.transport}."
|
|
349
|
+
except WDAError:
|
|
350
|
+
await asyncio.sleep(2)
|
|
351
|
+
raise WDAError(f"WebDriverAgent not ready after {timeout:.0f}s.")
|
|
352
|
+
|
|
353
|
+
async def stop_wda(self) -> str:
|
|
354
|
+
pid = self.wda_running_pid()
|
|
355
|
+
if self.client is not None:
|
|
356
|
+
await self.client.close()
|
|
357
|
+
self.client = None
|
|
358
|
+
await self._stop_forward()
|
|
359
|
+
if self._xct is not None:
|
|
360
|
+
await self._xct.stop()
|
|
361
|
+
self._xct = None
|
|
362
|
+
if not pid:
|
|
363
|
+
return "WebDriverAgent stopped."
|
|
364
|
+
if not pid:
|
|
365
|
+
return "WebDriverAgent was not running (not started by iphone-mcp)."
|
|
366
|
+
try:
|
|
367
|
+
killpg = getattr(os, "killpg", None) # not on Windows
|
|
368
|
+
if killpg is None:
|
|
369
|
+
raise OSError
|
|
370
|
+
killpg(pid, signal.SIGTERM)
|
|
371
|
+
except OSError:
|
|
372
|
+
try:
|
|
373
|
+
os.kill(pid, signal.SIGTERM)
|
|
374
|
+
except OSError:
|
|
375
|
+
pass
|
|
376
|
+
if self._proc is not None:
|
|
377
|
+
try:
|
|
378
|
+
self._proc.wait(5)
|
|
379
|
+
except subprocess.TimeoutExpired:
|
|
380
|
+
pass
|
|
381
|
+
self._proc = None
|
|
382
|
+
paths.update(paths.STATE_FILE, wda_pid=None)
|
|
383
|
+
return "WebDriverAgent stopped."
|
iphone_mcp/paths.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Where iphone-mcp keeps its config, build output and logs (never inside the repo)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
IS_MAC = sys.platform == "darwin"
|
|
11
|
+
|
|
12
|
+
CONFIG_DIR = Path(os.environ.get("IPHONE_MCP_CONFIG_DIR") or Path.home() / ".config" / "iphone-mcp")
|
|
13
|
+
if IS_MAC:
|
|
14
|
+
_default_data = Path.home() / "Library" / "Application Support" / "iphone-mcp"
|
|
15
|
+
_default_logs = Path.home() / "Library" / "Logs" / "iphone-mcp"
|
|
16
|
+
else:
|
|
17
|
+
_default_data = Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local" / "share") / "iphone-mcp"
|
|
18
|
+
_default_logs = _default_data / "logs"
|
|
19
|
+
DATA_DIR = Path(os.environ.get("IPHONE_MCP_DATA_DIR") or _default_data)
|
|
20
|
+
LOG_DIR = _default_logs
|
|
21
|
+
|
|
22
|
+
STATE_FILE = CONFIG_DIR / "state.json" # runtime state: last Wi-Fi IP, xcodebuild pid
|
|
23
|
+
WDA_FILE = CONFIG_DIR / "wda.json" # result of `iphone-mcp setup`
|
|
24
|
+
WDA_SRC = DATA_DIR / "WebDriverAgent"
|
|
25
|
+
WDA_DERIVED = DATA_DIR / "DerivedData"
|
|
26
|
+
WDA_LOG = LOG_DIR / "wda.log"
|
|
27
|
+
BUILD_LOG = LOG_DIR / "build.log"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def load(path: Path) -> dict:
|
|
31
|
+
try:
|
|
32
|
+
return json.loads(path.read_text())
|
|
33
|
+
except (OSError, ValueError):
|
|
34
|
+
return {}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def update(path: Path, **values) -> None:
|
|
38
|
+
data = load(path)
|
|
39
|
+
data.update(values)
|
|
40
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
41
|
+
path.write_text(json.dumps(data, indent=2))
|