|
| 1 | +import * as http from 'node:http'; |
| 2 | +import * as path from 'node:path'; |
| 3 | +import { spawn, type ChildProcess } from 'node:child_process'; |
| 4 | +import type { McpConfig } from './config.js'; |
| 5 | + |
| 6 | +const POLL_INTERVAL_MS = 500; |
| 7 | +const STARTUP_TIMEOUT_MS = 30_000; |
| 8 | +const SHUTDOWN_TIMEOUT_MS = 5_000; |
| 9 | + |
| 10 | +function isAppiumReady(host: string, port: number): Promise<boolean> { |
| 11 | + return new Promise((resolve) => { |
| 12 | + const req = http.get( |
| 13 | + { hostname: host, port, path: '/status', timeout: 2000 }, |
| 14 | + (res) => { |
| 15 | + let body = ''; |
| 16 | + res.on('data', (chunk) => { body += chunk; }); |
| 17 | + res.on('end', () => { |
| 18 | + try { |
| 19 | + const json = JSON.parse(body); |
| 20 | + resolve(json?.value?.ready === true); |
| 21 | + } catch { |
| 22 | + resolve(false); |
| 23 | + } |
| 24 | + }); |
| 25 | + } |
| 26 | + ); |
| 27 | + req.on('error', () => resolve(false)); |
| 28 | + req.on('timeout', () => { req.destroy(); resolve(false); }); |
| 29 | + }); |
| 30 | +} |
| 31 | + |
| 32 | +function waitForAppium(host: string, port: number): Promise<void> { |
| 33 | + return new Promise((resolve, reject) => { |
| 34 | + const deadline = Date.now() + STARTUP_TIMEOUT_MS; |
| 35 | + const poll = async () => { |
| 36 | + if (await isAppiumReady(host, port)) { |
| 37 | + resolve(); |
| 38 | + return; |
| 39 | + } |
| 40 | + if (Date.now() >= deadline) { |
| 41 | + reject(new Error(`Appium did not become ready within ${STARTUP_TIMEOUT_MS / 1000}s on ${host}:${port}`)); |
| 42 | + return; |
| 43 | + } |
| 44 | + setTimeout(poll, POLL_INTERVAL_MS); |
| 45 | + }; |
| 46 | + poll(); |
| 47 | + }); |
| 48 | +} |
| 49 | + |
| 50 | +function resolveAppiumBinary(configBinary?: string): string { |
| 51 | + if (configBinary) {return configBinary;} |
| 52 | + |
| 53 | + // Prefer a local node_modules/.bin/appium (3 levels up from build/lib/mcp/) |
| 54 | + const localBin = path.resolve(__dirname, '..', '..', '..', 'node_modules', '.bin', 'appium'); |
| 55 | + if (require('node:fs').existsSync(localBin)) {return localBin;} |
| 56 | + |
| 57 | + // Fall back to appium on the system PATH (global install: npm install -g appium) |
| 58 | + return 'appium'; |
| 59 | +} |
| 60 | + |
| 61 | +export class AppiumManager { |
| 62 | + private process: ChildProcess | null = null; |
| 63 | + private managed = false; |
| 64 | + |
| 65 | + async ensureRunning(config: McpConfig): Promise<void> { |
| 66 | + const { appiumHost: host, appiumPort: port } = config; |
| 67 | + |
| 68 | + if (await isAppiumReady(host, port)) { |
| 69 | + process.stderr.write(`[MCP] Appium already running on ${host}:${port}\n`); |
| 70 | + return; |
| 71 | + } |
| 72 | + |
| 73 | + if (!config.appiumAutoStart) { |
| 74 | + throw new Error( |
| 75 | + `Appium is not running on ${host}:${port}.\n` + |
| 76 | + `Start it with: appium --port ${port}\n` + |
| 77 | + `Or set APPIUM_AUTO_START=true to start it automatically.` |
| 78 | + ); |
| 79 | + } |
| 80 | + |
| 81 | + const binary = resolveAppiumBinary(config.appiumBinary); |
| 82 | + process.stderr.write(`[MCP] Starting Appium: ${binary} --port ${port} --address ${host}\n`); |
| 83 | + |
| 84 | + const child = spawn(binary, ['--port', String(port), '--address', host], { |
| 85 | + stdio: ['ignore', 'pipe', 'pipe'], |
| 86 | + shell: process.platform === 'win32', |
| 87 | + }); |
| 88 | + |
| 89 | + // Attach error handler immediately to prevent unhandled error crash |
| 90 | + await new Promise<void>((resolve, reject) => { |
| 91 | + child.once('error', (err) => { |
| 92 | + reject(new Error( |
| 93 | + `Failed to spawn Appium binary at "${binary}": ${err.message}\n` + |
| 94 | + `Install Appium globally with: npm install -g appium\n` + |
| 95 | + `Or set APPIUM_BINARY to the full path of the appium executable.` |
| 96 | + )); |
| 97 | + }); |
| 98 | + // If no error fires synchronously, we're past the spawn phase |
| 99 | + setImmediate(resolve); |
| 100 | + }); |
| 101 | + |
| 102 | + this.process = child; |
| 103 | + this.managed = true; |
| 104 | + |
| 105 | + this.process.stdout?.on('data', (data: Buffer) => { |
| 106 | + process.stderr.write(`[Appium] ${data}`); |
| 107 | + }); |
| 108 | + this.process.stderr?.on('data', (data: Buffer) => { |
| 109 | + process.stderr.write(`[Appium] ${data}`); |
| 110 | + }); |
| 111 | + this.process.on('exit', (code) => { |
| 112 | + process.stderr.write(`[MCP] Appium process exited with code ${code}\n`); |
| 113 | + }); |
| 114 | + |
| 115 | + await waitForAppium(host, port); |
| 116 | + process.stderr.write(`[MCP] Appium ready on ${host}:${port}\n`); |
| 117 | + } |
| 118 | + |
| 119 | + async shutdown(): Promise<void> { |
| 120 | + if (!this.managed || !this.process) {return;} |
| 121 | + |
| 122 | + process.stderr.write('[MCP] Stopping Appium...\n'); |
| 123 | + this.process.kill('SIGTERM'); |
| 124 | + |
| 125 | + const child = this.process; |
| 126 | + await new Promise<void>((resolve) => { |
| 127 | + const timeout = setTimeout(() => { |
| 128 | + child.kill('SIGKILL'); |
| 129 | + resolve(); |
| 130 | + }, SHUTDOWN_TIMEOUT_MS); |
| 131 | + |
| 132 | + child.on('exit', () => { |
| 133 | + clearTimeout(timeout); |
| 134 | + resolve(); |
| 135 | + }); |
| 136 | + }); |
| 137 | + |
| 138 | + this.process = null; |
| 139 | + this.managed = false; |
| 140 | + } |
| 141 | +} |
0 commit comments