Coverage for src/romfarmer/mcp/farmhand.py: 0%

170 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-01 23:08 -0700

1"""MCP tools for Farm-Hand deployment system. 

2 

3Exposes target introspection, space planning, and deployment operations 

4as MCP tools for AI agent-driven workflows. 

5""" 

6 

7from __future__ import annotations 

8 

9import logging 

10from pathlib import Path 

11from typing import Any 

12 

13logger = logging.getLogger(__name__) 

14 

15# Module-level SSH client cache — persists across tool calls in a session 

16_active_clients: dict[str, Any] = {} # host -> SSHClient 

17 

18 

19def _get_workspace_root() -> Path: 

20 from romfarmer.core.paths import get_paths 

21 

22 return get_paths().workspace_root 

23 

24 

25def _resolve_ssh_kwargs( 

26 *, 

27 host: str = "", 

28 user: str = "root", 

29 password: str = "", 

30 port: int = 22, 

31 target: str = "", 

32) -> dict[str, Any]: 

33 """Resolve SSH kwargs from either direct args or a target config name.""" 

34 if target: 

35 from romfarmer.farmhand.config import load_target_config, target_config_to_ssh_kwargs 

36 

37 config = load_target_config(_get_workspace_root(), target) 

38 return target_config_to_ssh_kwargs(config) 

39 if not host: 

40 raise ValueError("Provide either 'host' or 'target' config name") 

41 kwargs: dict[str, Any] = {"host": host, "port": port, "user": user} 

42 if password: 

43 kwargs["password"] = password 

44 return kwargs 

45 

46 

47def _resolve_target_full( 

48 *, 

49 host: str = "", 

50 user: str = "root", 

51 password: str = "", 

52 port: int = 22, 

53 target: str = "", 

54 name: str = "", 

55 frontend: str = "batocera", 

56) -> tuple[dict[str, Any], str, str]: 

57 """Resolve SSH kwargs + target name + frontend from target config or direct args.""" 

58 if target: 

59 from romfarmer.farmhand.config import load_target_config, target_config_to_ssh_kwargs 

60 

61 config = load_target_config(_get_workspace_root(), target) 

62 ssh_kwargs = target_config_to_ssh_kwargs(config) 

63 resolved_name = name or config.get("name", target) 

64 resolved_frontend = config.get("frontend", frontend) 

65 return ssh_kwargs, resolved_name, resolved_frontend 

66 if not host: 

67 raise ValueError("Provide either 'host' or 'target' config name") 

68 kwargs: dict[str, Any] = {"host": host, "port": port, "user": user} 

69 if password: 

70 kwargs["password"] = password 

71 return kwargs, name, frontend 

72 

73 

74def _check_paramiko() -> None: 

75 try: 

76 import paramiko # noqa: F401 

77 except ImportError: 

78 raise RuntimeError( 

79 "paramiko not installed. Run: pip install 'romfarmer[farmhand]'" 

80 ) from None 

81 

82 

83# --------------------------------------------------------------------------- 

84# Tool: farmhand_connect 

85# --------------------------------------------------------------------------- 

86 

87 

88async def tool_farmhand_connect( 

89 host: str = "", 

90 user: str = "root", 

91 password: str = "", 

92 port: int = 22, 

93 target: str = "", 

94) -> dict[str, Any]: 

95 """Connect to a remote target and return basic system info. 

96 

97 Provide either host (IP/hostname) or target (config name from 

98 config/farmhand/targets/) to look up connection details. 

99 """ 

100 _check_paramiko() 

101 from romfarmer.farmhand.ssh import SSHClient 

102 

103 try: 

104 ssh_kwargs = _resolve_ssh_kwargs( 

105 host=host, user=user, password=password, port=port, target=target 

106 ) 

107 actual_host = ssh_kwargs["host"] 

108 

109 client = SSHClient(**ssh_kwargs) 

110 client.connect() 

111 probe = client.run("hostname").strip() 

112 uname = client.run("uname -srm").strip() 

113 

114 # Cache the client for reuse 

115 _active_clients[actual_host] = client 

116 

117 return { 

118 "connected": True, 

119 "host": actual_host, 

120 "hostname": probe, 

121 "uname": uname, 

122 "message": f"Connected to {probe} ({actual_host}). Client cached for subsequent calls.", 

123 } 

124 except Exception as exc: 

125 return {"connected": False, "host": host or target, "error": str(exc)} 

126 

127 

128# --------------------------------------------------------------------------- 

129# Tool: farmhand_scan_target 

130# --------------------------------------------------------------------------- 

131 

132 

133async def tool_farmhand_scan_target( 

134 host: str = "", 

135 user: str = "root", 

136 password: str = "", 

137 name: str = "", 

138 frontend: str = "batocera", 

139 port: int = 22, 

140 save: bool = True, 

141 target: str = "", 

142) -> dict[str, Any]: 

143 """Full scan of a remote target — volumes, ROMs, capabilities. 

144 

145 Provide either host (IP/hostname) or target (config name from 

146 config/farmhand/targets/) to look up connection details. 

147 Returns complete target profile as a dict. 

148 """ 

149 _check_paramiko() 

150 from romfarmer.farmhand.analyzer import TargetAnalyzer 

151 from romfarmer.farmhand.config import save_profile as _save_profile 

152 from romfarmer.farmhand.ssh import SSHClient 

153 

154 try: 

155 ssh_kwargs, resolved_name, resolved_frontend = _resolve_target_full( 

156 host=host, 

157 user=user, 

158 password=password, 

159 port=port, 

160 target=target, 

161 name=name, 

162 frontend=frontend, 

163 ) 

164 actual_host = ssh_kwargs["host"] 

165 

166 # Reuse cached client or create new one 

167 client = _active_clients.get(actual_host) 

168 if client is None or not client.is_connected: 

169 client = SSHClient(**ssh_kwargs) 

170 client.connect() 

171 _active_clients[actual_host] = client 

172 

173 analyzer = TargetAnalyzer(client) 

174 target_name = resolved_name or f"{resolved_frontend}-{actual_host.replace('.', '-')}" 

175 profile = analyzer.full_scan(name=target_name, frontend=resolved_frontend) 

176 

177 # Save profile 

178 if save: 

179 _save_profile(_get_workspace_root(), profile) 

180 

181 # Build a clean summary dict 

182 result = { 

183 "name": profile.name, 

184 "host": profile.host, 

185 "system": None, 

186 "volumes": [], 

187 "capabilities": None, 

188 "existing_roms": {}, 

189 "total_available_gb": round(profile.total_available_gb(), 1), 

190 } 

191 

192 if profile.system_info: 

193 si = profile.system_info 

194 result["system"] = { 

195 "hostname": si.hostname, 

196 "os": f"{si.os_name} {si.os_version}", 

197 "arch": si.architecture, 

198 "cpu": si.cpu_model, 

199 "cores": si.cpu_cores, 

200 "threads": si.cpu_threads, 

201 "ram_mb": si.memory_total_mb, 

202 } 

203 

204 for vol in profile.volumes: 

205 result["volumes"].append( 

206 { 

207 "mount": vol.mount_point, 

208 "device": vol.device, 

209 "fs": vol.filesystem, 

210 "total_gb": round(vol.total_gb, 1), 

211 "available_gb": round(vol.available_gb, 1), 

212 "use_percent": vol.use_percent, 

213 "role": vol.role.value, 

214 "rom_path": vol.rom_path, 

215 } 

216 ) 

217 

218 if profile.capabilities: 

219 result["capabilities"] = { 

220 "binaries": profile.capabilities.binaries, 

221 "emulators": profile.capabilities.emulators[:20], 

222 "has_7z": profile.capabilities.has_7z, 

223 "has_chdman": profile.capabilities.has_chdman, 

224 } 

225 

226 for platform, files in profile.existing_roms.items(): 

227 result["existing_roms"][platform] = { 

228 "count": len(files), 

229 "sample": files[:5], 

230 } 

231 

232 return result 

233 except Exception as exc: 

234 return {"error": str(exc)} 

235 

236 

237# --------------------------------------------------------------------------- 

238# Tool: farmhand_analyze_fit 

239# --------------------------------------------------------------------------- 

240 

241 

242async def tool_farmhand_analyze_fit( 

243 available_gb: float = 0, 

244 target_name: str = "", 

245) -> dict[str, Any]: 

246 """Analyze what platforms fit in the available space. 

247 

248 Either provide available_gb directly, or target_name to load from saved profile. 

249 """ 

250 try: 

251 if target_name: 

252 from romfarmer.farmhand.config import load_profile 

253 

254 profile = load_profile(_get_workspace_root(), target_name) 

255 if profile: 

256 available_gb = profile.total_available_gb() 

257 

258 if available_gb <= 0: 

259 return {"error": "Provide available_gb or a valid target_name"} 

260 

261 from romfarmer.farmhand.planner import SpacePlanner 

262 

263 planner = SpacePlanner() 

264 return planner.estimate_platforms_count(available_gb) 

265 except Exception as exc: 

266 return {"error": str(exc)} 

267 

268 

269# --------------------------------------------------------------------------- 

270# Tool: farmhand_generate_plan 

271# --------------------------------------------------------------------------- 

272 

273 

274async def tool_farmhand_generate_plan( 

275 target_name: str, 

276 reserved_gb: float = 30.0, 

277 exclude_platforms: str = "", 

278 budget_overrides: str = "", 

279) -> dict[str, Any]: 

280 """Generate a deployment plan for a saved target profile. 

281 

282 Args: 

283 target_name: Name of the saved target profile. 

284 reserved_gb: Space to reserve for saves, BIOS, etc. 

285 exclude_platforms: Comma-separated list of platforms to exclude. 

286 budget_overrides: Comma-separated platform=gb pairs (e.g., "ps2=80,psx=60"). 

287 """ 

288 try: 

289 from romfarmer.farmhand.config import load_profile 

290 

291 profile = load_profile(_get_workspace_root(), target_name) 

292 if not profile: 

293 return { 

294 "error": f"Target profile '{target_name}' not found. Run farmhand_scan_target first." 

295 } 

296 

297 from romfarmer.farmhand.planner import SpacePlanner 

298 

299 planner = SpacePlanner() 

300 

301 excludes = [p.strip() for p in exclude_platforms.split(",") if p.strip()] 

302 

303 budgets: dict[str, float] = {} 

304 if budget_overrides: 

305 for pair in budget_overrides.split(","): 

306 if "=" in pair: 

307 k, v = pair.split("=", 1) 

308 budgets[k.strip()] = float(v.strip()) 

309 

310 plan = planner.create_plan( 

311 target=profile, 

312 reserved_gb=reserved_gb, 

313 exclude_platforms=excludes, 

314 budget_overrides=budgets, 

315 ) 

316 

317 # Save plan 

318 plan_dir = _get_workspace_root() / "config" / "farmhand" 

319 plan_path = plan_dir / f"{target_name}-plan.json" 

320 plan_path.write_text(plan.model_dump_json(indent=2)) 

321 

322 # Build summary 

323 allocs = [] 

324 for a in plan.allocations: 

325 allocs.append( 

326 { 

327 "platform": a.platform, 

328 "tier": a.tier.value, 

329 "action": a.action.value, 

330 "full_set_gb": round(a.full_set_gb, 1), 

331 "allocated_gb": round(a.allocated_gb, 1), 

332 "volume": a.target_volume, 

333 "strategy": a.selection_strategy or None, 

334 "budget_gb": a.selection_max_gb or None, 

335 } 

336 ) 

337 

338 return { 

339 "target": target_name, 

340 "summary": plan.summary(), 

341 "platforms_included": plan.platforms_included, 

342 "platforms_skipped": plan.platforms_skipped, 

343 "total_allocated_gb": round(plan.total_allocated_gb, 1), 

344 "headroom_gb": round(plan.headroom_gb, 1), 

345 "builds_needed": plan.builds_needed, 

346 "allocations": allocs, 

347 "notes": plan.notes, 

348 "plan_saved_to": str(plan_path), 

349 } 

350 except Exception as exc: 

351 return {"error": str(exc)} 

352 

353 

354# --------------------------------------------------------------------------- 

355# Tool: farmhand_remote_exec 

356# --------------------------------------------------------------------------- 

357 

358 

359async def tool_farmhand_remote_exec( 

360 host: str, command: str, user: str = "root", password: str = "", port: int = 22 

361) -> dict[str, Any]: 

362 """Execute an arbitrary command on a remote target via SSH. 

363 

364 Use this for ad-hoc inspection: check binaries, configs, file listings, etc. 

365 """ 

366 _check_paramiko() 

367 from romfarmer.farmhand.ssh import SSHClient 

368 

369 try: 

370 client = _active_clients.get(host) 

371 if client is None or not client.is_connected: 

372 client = SSHClient(host, port=port, user=user, password=password) 

373 client.connect() 

374 _active_clients[host] = client 

375 

376 output = client.run(command, timeout=60) 

377 return { 

378 "host": host, 

379 "command": command, 

380 "output": output, 

381 } 

382 except Exception as exc: 

383 return {"error": str(exc)} 

384 

385 

386# --------------------------------------------------------------------------- 

387# Tool: farmhand_get_target_info 

388# --------------------------------------------------------------------------- 

389 

390 

391async def tool_farmhand_get_target_info(target_name: str) -> dict[str, Any]: 

392 """Get saved target profile information (from last scan).""" 

393 try: 

394 profile_path = _get_workspace_root() / "config" / "farmhand" / f"{target_name}.json" 

395 if not profile_path.exists(): 

396 return {"error": f"Target profile '{target_name}' not found"} 

397 

398 from romfarmer.farmhand.models import TargetProfile 

399 

400 profile = TargetProfile.model_validate_json(profile_path.read_text()) 

401 

402 return { 

403 "name": profile.name, 

404 "host": profile.host, 

405 "frontend": profile.frontend, 

406 "last_scanned": str(profile.last_scanned) if profile.last_scanned else None, 

407 "total_available_gb": round(profile.total_available_gb(), 1), 

408 "volumes": [ 

409 { 

410 "mount": v.mount_point, 

411 "total_gb": round(v.total_gb, 1), 

412 "available_gb": round(v.available_gb, 1), 

413 "role": v.role.value, 

414 "rom_path": v.rom_path, 

415 } 

416 for v in profile.volumes 

417 ], 

418 "existing_rom_platforms": list(profile.existing_roms.keys()), 

419 "existing_rom_count": sum(len(v) for v in profile.existing_roms.values()), 

420 } 

421 except Exception as exc: 

422 return {"error": str(exc)} 

423 

424 

425# --------------------------------------------------------------------------- 

426# Tool: farmhand_deploy_status 

427# --------------------------------------------------------------------------- 

428 

429 

430async def tool_farmhand_deploy_status(target_name: str) -> dict[str, Any]: 

431 """Get deployment status — what's been planned and deployed for a target.""" 

432 try: 

433 ws = _get_workspace_root() 

434 plan_path = ws / "config" / "farmhand" / f"{target_name}-plan.json" 

435 profile_path = ws / "config" / "farmhand" / f"{target_name}.json" 

436 

437 result: dict[str, Any] = {"target": target_name} 

438 

439 if profile_path.exists(): 

440 from romfarmer.farmhand.models import TargetProfile 

441 

442 profile = TargetProfile.model_validate_json(profile_path.read_text()) 

443 result["last_scanned"] = str(profile.last_scanned) if profile.last_scanned else None 

444 result["total_available_gb"] = round(profile.total_available_gb(), 1) 

445 else: 

446 result["profile"] = "not found" 

447 

448 if plan_path.exists(): 

449 from romfarmer.farmhand.models import DeploymentPlan 

450 

451 plan = DeploymentPlan.model_validate_json(plan_path.read_text()) 

452 result["plan_status"] = plan.status.value 

453 result["platforms_included"] = plan.platforms_included 

454 result["platforms_skipped"] = plan.platforms_skipped 

455 result["total_allocated_gb"] = round(plan.total_allocated_gb, 1) 

456 result["builds_needed"] = plan.builds_needed 

457 else: 

458 result["plan"] = "no plan generated yet" 

459 

460 return result 

461 except Exception as exc: 

462 return {"error": str(exc)}