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

119 statements  

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

1""" 

2ROM Farmer MCP Server — modular entry point. 

3 

4Registers tools, resources, and prompts by importing domain modules 

5and using a registry-based dispatcher instead of a long if/elif chain. 

6""" 

7 

8import asyncio 

9import json 

10import logging 

11from collections.abc import Awaitable, Callable 

12from typing import Any 

13 

14# MCP imports 

15try: 

16 from mcp.server import Server 

17 from mcp.server.models import InitializationOptions 

18 from mcp.types import ( 

19 GetPromptResult, 

20 Prompt, 

21 PromptArgument, 

22 PromptMessage, 

23 Resource, 

24 TextContent, 

25 Tool, 

26 ) 

27 

28 MCP_AVAILABLE = True 

29except ImportError: 

30 MCP_AVAILABLE = False 

31 print("MCP not installed. Run: pip install mcp") 

32 

33from romfarmer.core.paths import get_paths 

34 

35# --------------------------------------------------------------------------- 

36# Configuration 

37# --------------------------------------------------------------------------- 

38 

39SERVER_NAME = "romfarmer" 

40SERVER_VERSION = "0.2.0" 

41WORKSPACE_ROOT = get_paths().workspace_root 

42logger = logging.getLogger(__name__) 

43 

44# --------------------------------------------------------------------------- 

45# Tool registry (name -> handler) 

46# --------------------------------------------------------------------------- 

47 

48ToolHandler = Callable[..., Awaitable[dict[str, Any]]] 

49_TOOL_HANDLERS: dict[str, ToolHandler] = {} 

50 

51 

52def _register_tools() -> None: 

53 """Import domain modules and populate the handler registry.""" 

54 from romfarmer.mcp.clonelist import ( 

55 tool_clonelist_diff, 

56 tool_clonelist_metadata_generate, 

57 tool_clonelist_patch, 

58 tool_clonelist_validate, 

59 ) 

60 from romfarmer.mcp.collection import ( 

61 tool_calculate_budget, 

62 tool_get_build_status, 

63 tool_get_compression_ratio, 

64 tool_get_platform_stats, 

65 tool_list_builds, 

66 tool_list_platforms, 

67 tool_query_collection, 

68 ) 

69 from romfarmer.mcp.dat import ( 

70 tool_dat_game_variants, 

71 tool_dat_hardware_games, 

72 tool_dat_hardware_list, 

73 tool_dat_search, 

74 ) 

75 from romfarmer.mcp.farmhand import ( 

76 tool_farmhand_analyze_fit, 

77 tool_farmhand_connect, 

78 tool_farmhand_deploy_status, 

79 tool_farmhand_generate_plan, 

80 tool_farmhand_get_target_info, 

81 tool_farmhand_remote_exec, 

82 tool_farmhand_scan_target, 

83 ) 

84 from romfarmer.mcp.farmhand_skills import ( 

85 tool_farmhand_skill_artifact, 

86 tool_farmhand_skill_capture_cancel, 

87 tool_farmhand_skill_capture_finish, 

88 tool_farmhand_skill_capture_start, 

89 tool_farmhand_skill_capture_step, 

90 tool_farmhand_skill_save, 

91 tool_farmhand_skill_save_artifact, 

92 tool_farmhand_skill_search, 

93 tool_farmhand_skill_show, 

94 ) 

95 from romfarmer.mcp.scraper import ( 

96 tool_scraper_game_info, 

97 tool_scraper_genres, 

98 tool_scraper_platforms, 

99 tool_scraper_search, 

100 tool_scraper_top_rated, 

101 ) 

102 from romfarmer.mcp.wiki import ( 

103 tool_wiki_find_game, 

104 tool_wiki_game_info, 

105 tool_wiki_get_section, 

106 tool_wiki_search, 

107 tool_wiki_stats, 

108 ) 

109 

110 _TOOL_HANDLERS.update( 

111 { 

112 # Collection / build / budget 

113 "list_platforms": tool_list_platforms, 

114 "list_builds": tool_list_builds, 

115 "get_build_status": tool_get_build_status, 

116 "get_platform_stats": tool_get_platform_stats, 

117 "query_collection": tool_query_collection, 

118 "calculate_budget": tool_calculate_budget, 

119 "get_compression_ratio": tool_get_compression_ratio, 

120 # Wikipedia 

121 "wiki_search": tool_wiki_search, 

122 "wiki_game_info": tool_wiki_game_info, 

123 "wiki_get_section": tool_wiki_get_section, 

124 "wiki_stats": tool_wiki_stats, 

125 "wiki_find_game": tool_wiki_find_game, 

126 # ScreenScraper 

127 "scraper_search": tool_scraper_search, 

128 "scraper_game_info": tool_scraper_game_info, 

129 "scraper_platforms": tool_scraper_platforms, 

130 "scraper_genres": tool_scraper_genres, 

131 "scraper_top_rated": tool_scraper_top_rated, 

132 # DAT files 

133 "dat_hardware_list": tool_dat_hardware_list, 

134 "dat_hardware_games": tool_dat_hardware_games, 

135 "dat_game_variants": tool_dat_game_variants, 

136 "dat_search": tool_dat_search, 

137 # Clone list maintenance 

138 "clonelist_diff": tool_clonelist_diff, 

139 "clonelist_validate": tool_clonelist_validate, 

140 "clonelist_patch": tool_clonelist_patch, 

141 "clonelist_metadata_generate": tool_clonelist_metadata_generate, 

142 # Farm-Hand deployment 

143 "farmhand_connect": tool_farmhand_connect, 

144 "farmhand_scan_target": tool_farmhand_scan_target, 

145 "farmhand_analyze_fit": tool_farmhand_analyze_fit, 

146 "farmhand_generate_plan": tool_farmhand_generate_plan, 

147 "farmhand_remote_exec": tool_farmhand_remote_exec, 

148 "farmhand_get_target_info": tool_farmhand_get_target_info, 

149 "farmhand_deploy_status": tool_farmhand_deploy_status, 

150 # Farm-Hand skills 

151 "farmhand_skill_search": tool_farmhand_skill_search, 

152 "farmhand_skill_show": tool_farmhand_skill_show, 

153 "farmhand_skill_artifact": tool_farmhand_skill_artifact, 

154 "farmhand_skill_save": tool_farmhand_skill_save, 

155 "farmhand_skill_save_artifact": tool_farmhand_skill_save_artifact, 

156 "farmhand_skill_capture_start": tool_farmhand_skill_capture_start, 

157 "farmhand_skill_capture_step": tool_farmhand_skill_capture_step, 

158 "farmhand_skill_capture_finish": tool_farmhand_skill_capture_finish, 

159 "farmhand_skill_capture_cancel": tool_farmhand_skill_capture_cancel, 

160 } 

161 ) 

162 

163 

164# --------------------------------------------------------------------------- 

165# Tool schemas (kept here for a single source of truth) 

166# --------------------------------------------------------------------------- 

167 

168TOOL_SCHEMAS: list[dict[str, Any]] = [ 

169 # ---- Collection tools ------------------------------------------------ 

170 { 

171 "name": "list_platforms", 

172 "description": "List all configured ROM platforms", 

173 "inputSchema": {"type": "object", "properties": {}}, 

174 }, 

175 { 

176 "name": "list_builds", 

177 "description": "List all available build configurations", 

178 "inputSchema": {"type": "object", "properties": {}}, 

179 }, 

180 { 

181 "name": "get_build_status", 

182 "description": "Get the status of a build", 

183 "inputSchema": { 

184 "type": "object", 

185 "properties": { 

186 "build_name": {"type": "string", "description": "Name of the build"}, 

187 }, 

188 "required": ["build_name"], 

189 }, 

190 }, 

191 { 

192 "name": "get_platform_stats", 

193 "description": "Get statistics for a platform's ROM collection", 

194 "inputSchema": { 

195 "type": "object", 

196 "properties": { 

197 "platform": {"type": "string", "description": "Platform name (saturn, psx, etc.)"}, 

198 }, 

199 "required": ["platform"], 

200 }, 

201 }, 

202 { 

203 "name": "query_collection", 

204 "description": "Search for ROMs in a platform's collection", 

205 "inputSchema": { 

206 "type": "object", 

207 "properties": { 

208 "platform": {"type": "string", "description": "Platform name"}, 

209 "query": {"type": "string", "description": "Search query"}, 

210 "limit": {"type": "integer", "description": "Max results", "default": 20}, 

211 }, 

212 "required": ["platform"], 

213 }, 

214 }, 

215 { 

216 "name": "calculate_budget", 

217 "description": "Calculate how many ROMs fit in a storage budget", 

218 "inputSchema": { 

219 "type": "object", 

220 "properties": { 

221 "platform": {"type": "string", "description": "Platform name"}, 

222 "budget_gb": {"type": "number", "description": "Storage budget in GB"}, 

223 "compression_format": { 

224 "type": "string", 

225 "description": "Compression format", 

226 "default": "chd", 

227 }, 

228 }, 

229 "required": ["platform", "budget_gb"], 

230 }, 

231 }, 

232 { 

233 "name": "get_compression_ratio", 

234 "description": "Get compression ratio for a platform/format combination", 

235 "inputSchema": { 

236 "type": "object", 

237 "properties": { 

238 "platform": {"type": "string", "description": "Platform name"}, 

239 "output_format": { 

240 "type": "string", 

241 "description": "Output format", 

242 "default": "chd", 

243 }, 

244 }, 

245 "required": ["platform"], 

246 }, 

247 }, 

248 # ---- Wikipedia tools ------------------------------------------------- 

249 { 

250 "name": "wiki_search", 

251 "description": "Semantic search over Wikipedia game articles. Use this to find games by description, gameplay style, themes, etc.", 

252 "inputSchema": { 

253 "type": "object", 

254 "properties": { 

255 "query": { 

256 "type": "string", 

257 "description": "Natural language search query (e.g., 'horror game with zombies', 'turn-based JRPG')", 

258 }, 

259 "limit": {"type": "integer", "description": "Max results to return", "default": 10}, 

260 "section_filter": { 

261 "type": "string", 

262 "description": "Filter to specific section type (Gameplay, Plot, Reception, etc.)", 

263 }, 

264 }, 

265 "required": ["query"], 

266 }, 

267 }, 

268 { 

269 "name": "wiki_game_info", 

270 "description": "Get full Wikipedia information about a specific game including all sections", 

271 "inputSchema": { 

272 "type": "object", 

273 "properties": { 

274 "game_title": {"type": "string", "description": "Game title to look up"}, 

275 }, 

276 "required": ["game_title"], 

277 }, 

278 }, 

279 { 

280 "name": "wiki_get_section", 

281 "description": "Get a specific section from a game's Wikipedia article (e.g., Gameplay, Plot, Reception)", 

282 "inputSchema": { 

283 "type": "object", 

284 "properties": { 

285 "game_title": {"type": "string", "description": "Game title"}, 

286 "section_name": { 

287 "type": "string", 

288 "description": "Section name (Gameplay, Plot, Reception, Development, etc.)", 

289 }, 

290 }, 

291 "required": ["game_title", "section_name"], 

292 }, 

293 }, 

294 { 

295 "name": "wiki_stats", 

296 "description": "Get statistics about the Wikipedia game database", 

297 "inputSchema": {"type": "object", "properties": {}}, 

298 }, 

299 { 

300 "name": "wiki_find_game", 

301 "description": "Fuzzy search for game titles by name. Use this when you need to find the exact title of a game. Returns candidates ranked by similarity.", 

302 "inputSchema": { 

303 "type": "object", 

304 "properties": { 

305 "query": { 

306 "type": "string", 

307 "description": "Game title to search for (handles typos, partial names, variations)", 

308 }, 

309 "limit": {"type": "integer", "description": "Max results to return", "default": 10}, 

310 "threshold": { 

311 "type": "number", 

312 "description": "Minimum similarity score 0-1 (default 0.5)", 

313 "default": 0.5, 

314 }, 

315 }, 

316 "required": ["query"], 

317 }, 

318 }, 

319 # ---- ScreenScraper tools --------------------------------------------- 

320 { 

321 "name": "scraper_search", 

322 "description": "Search ScreenScraper database for games with rich metadata (developer, publisher, genre, rating, description). Has 120K+ games across 49 platforms. By default, deduplicates regional variants (showing US > World > EU > JP preference).", 

323 "inputSchema": { 

324 "type": "object", 

325 "properties": { 

326 "query": { 

327 "type": "string", 

328 "description": "Search query (searches name and description)", 

329 }, 

330 "platform": { 

331 "type": "string", 

332 "description": "Filter by platform (megadrive, psx, snes, etc.)", 

333 }, 

334 "genre": { 

335 "type": "string", 

336 "description": "Filter by genre (Platform, RPG, Action, etc.)", 

337 }, 

338 "limit": {"type": "integer", "description": "Max results", "default": 20}, 

339 "show_variants": { 

340 "type": "boolean", 

341 "description": "If true, show all regional variants instead of deduplicating", 

342 "default": False, 

343 }, 

344 "title_only": { 

345 "type": "boolean", 

346 "description": "If true, search only game titles (more precise). If false, also search descriptions.", 

347 "default": True, 

348 }, 

349 }, 

350 "required": ["query"], 

351 }, 

352 }, 

353 { 

354 "name": "scraper_game_info", 

355 "description": "Get detailed ScreenScraper info for a specific game including description, developer, publisher, genre, rating, release date. Can also show all regional variants.", 

356 "inputSchema": { 

357 "type": "object", 

358 "properties": { 

359 "name": {"type": "string", "description": "Game name to look up"}, 

360 "platform": { 

361 "type": "string", 

362 "description": "Platform to search in (optional, helps with disambiguation)", 

363 }, 

364 "show_variants": { 

365 "type": "boolean", 

366 "description": "If true, include all regional variants of this game", 

367 "default": False, 

368 }, 

369 }, 

370 "required": ["name"], 

371 }, 

372 }, 

373 { 

374 "name": "scraper_platforms", 

375 "description": "List all platforms in ScreenScraper database with game counts", 

376 "inputSchema": {"type": "object", "properties": {}}, 

377 }, 

378 { 

379 "name": "scraper_genres", 

380 "description": "List all genres with game counts, optionally filtered by platform", 

381 "inputSchema": { 

382 "type": "object", 

383 "properties": { 

384 "platform": {"type": "string", "description": "Filter genres by platform"}, 

385 }, 

386 }, 

387 }, 

388 { 

389 "name": "scraper_top_rated", 

390 "description": "Get top-rated games for a platform, optionally filtered by genre", 

391 "inputSchema": { 

392 "type": "object", 

393 "properties": { 

394 "platform": {"type": "string", "description": "Platform name (required)"}, 

395 "genre": {"type": "string", "description": "Filter by genre"}, 

396 "limit": {"type": "integer", "description": "Max results", "default": 20}, 

397 }, 

398 "required": ["platform"], 

399 }, 

400 }, 

401 # ---- DAT tools ------------------------------------------------------- 

402 { 

403 "name": "dat_hardware_list", 

404 "description": "List all arcade hardware platforms with game counts (CPS1, Neo Geo, etc.)", 

405 "inputSchema": { 

406 "type": "object", 

407 "properties": { 

408 "dat_type": { 

409 "type": "string", 

410 "description": "DAT source (fbneo or mame)", 

411 "default": "fbneo", 

412 }, 

413 }, 

414 }, 

415 }, 

416 { 

417 "name": "dat_hardware_games", 

418 "description": "Get all games for a specific arcade hardware/driver (e.g., all CPS1 games, all Neo Geo games)", 

419 "inputSchema": { 

420 "type": "object", 

421 "properties": { 

422 "hardware": { 

423 "type": "string", 

424 "description": "Hardware name: cps1, cps2, neogeo, sys16b, taitof2, etc.", 

425 }, 

426 "dat_type": {"type": "string", "description": "DAT source", "default": "fbneo"}, 

427 "parents_only": { 

428 "type": "boolean", 

429 "description": "Only parent games, no clones/hacks", 

430 "default": True, 

431 }, 

432 }, 

433 "required": ["hardware"], 

434 }, 

435 }, 

436 { 

437 "name": "dat_game_variants", 

438 "description": "Get a game and ALL its variants, clones, bootlegs, and hacks. Use to understand game relationships.", 

439 "inputSchema": { 

440 "type": "object", 

441 "properties": { 

442 "game_name": { 

443 "type": "string", 

444 "description": "ROM name (e.g., sf2ce, dino, mslug, sf2rb)", 

445 }, 

446 "dat_type": {"type": "string", "description": "DAT source", "default": "fbneo"}, 

447 }, 

448 "required": ["game_name"], 

449 }, 

450 }, 

451 { 

452 "name": "dat_search", 

453 "description": "Search arcade games by name. Returns hardware info, video specs, and parent/clone status.", 

454 "inputSchema": { 

455 "type": "object", 

456 "properties": { 

457 "query": {"type": "string", "description": "Search query"}, 

458 "dat_type": {"type": "string", "description": "DAT source", "default": "fbneo"}, 

459 "hardware": { 

460 "type": "string", 

461 "description": "Filter by hardware (cps1, neogeo, etc.)", 

462 }, 

463 "parents_only": { 

464 "type": "boolean", 

465 "description": "Exclude clones/hacks", 

466 "default": False, 

467 }, 

468 "limit": {"type": "integer", "description": "Max results", "default": 30}, 

469 }, 

470 "required": ["query"], 

471 }, 

472 }, 

473 # ---- Clone list maintenance tools ------------------------------------ 

474 { 

475 "name": "clonelist_diff", 

476 "description": "Compare two DAT file versions by hash to detect renames, additions, and removals. Essential for tracking changes between DAT releases.", 

477 "inputSchema": { 

478 "type": "object", 

479 "properties": { 

480 "old_dat": {"type": "string", "description": "Path or name of the older DAT file"}, 

481 "new_dat": {"type": "string", "description": "Path or name of the newer DAT file"}, 

482 }, 

483 "required": ["old_dat", "new_dat"], 

484 }, 

485 }, 

486 { 

487 "name": "clonelist_validate", 

488 "description": "Validate a Retool clone list's searchTerms against a DAT — find broken references and suggest fixes.", 

489 "inputSchema": { 

490 "type": "object", 

491 "properties": { 

492 "clonelist": { 

493 "type": "string", 

494 "description": "Path or name of the clone list JSON", 

495 }, 

496 "dat_file": { 

497 "type": "string", 

498 "description": "Path or name of the DAT to validate against", 

499 }, 

500 }, 

501 "required": ["clonelist", "dat_file"], 

502 }, 

503 }, 

504 { 

505 "name": "clonelist_patch", 

506 "description": "Auto-patch clone list searchTerms based on renames detected between two DAT versions. Dry-run by default.", 

507 "inputSchema": { 

508 "type": "object", 

509 "properties": { 

510 "clonelist": { 

511 "type": "string", 

512 "description": "Path or name of the clone list JSON to patch", 

513 }, 

514 "old_dat": {"type": "string", "description": "Path or name of the older DAT file"}, 

515 "new_dat": {"type": "string", "description": "Path or name of the newer DAT file"}, 

516 "output": { 

517 "type": "string", 

518 "description": "Output path for patched clone list (default: in-place)", 

519 }, 

520 "dry_run": { 

521 "type": "boolean", 

522 "description": "If true, show changes without applying", 

523 "default": True, 

524 }, 

525 }, 

526 "required": ["clonelist", "old_dat", "new_dat"], 

527 }, 

528 }, 

529 { 

530 "name": "clonelist_metadata_generate", 

531 "description": "Auto-generate Retool metadata JSON (languages, localName) from DAT game filenames.", 

532 "inputSchema": { 

533 "type": "object", 

534 "properties": { 

535 "dat_file": {"type": "string", "description": "Path or name of the DAT file"}, 

536 "output": {"type": "string", "description": "Output path for the metadata JSON"}, 

537 }, 

538 "required": ["dat_file"], 

539 }, 

540 }, 

541 # ---- Farm-Hand deployment tools -------------------------------------- 

542 { 

543 "name": "farmhand_connect", 

544 "description": "Connect to a remote target (Batocera, RockNIX) via SSH and return basic system info. Caches the connection for subsequent calls.", 

545 "inputSchema": { 

546 "type": "object", 

547 "properties": { 

548 "host": {"type": "string", "description": "SSH host (IP address or hostname)"}, 

549 "user": {"type": "string", "description": "SSH username", "default": "root"}, 

550 "password": {"type": "string", "description": "SSH password"}, 

551 "port": {"type": "integer", "description": "SSH port", "default": 22}, 

552 }, 

553 "required": ["host"], 

554 }, 

555 }, 

556 { 

557 "name": "farmhand_scan_target", 

558 "description": "Full scan of a remote target — discovers storage volumes, existing ROMs, installed emulators/binaries, and system info. Saves a target profile for planning.", 

559 "inputSchema": { 

560 "type": "object", 

561 "properties": { 

562 "host": {"type": "string", "description": "SSH host"}, 

563 "user": {"type": "string", "description": "SSH username", "default": "root"}, 

564 "password": {"type": "string", "description": "SSH password"}, 

565 "name": { 

566 "type": "string", 

567 "description": "Target profile name (e.g., batocera-nuc-livingroom)", 

568 }, 

569 "frontend": { 

570 "type": "string", 

571 "description": "Frontend type", 

572 "default": "batocera", 

573 }, 

574 "port": {"type": "integer", "description": "SSH port", "default": 22}, 

575 "save": { 

576 "type": "boolean", 

577 "description": "Save profile to config/farmhand/", 

578 "default": True, 

579 }, 

580 }, 

581 "required": ["host"], 

582 }, 

583 }, 

584 { 

585 "name": "farmhand_analyze_fit", 

586 "description": "Analyze what ROM platforms fit in a given amount of storage. Returns platforms classified as include_all (tiny/small), budget_needed (large), or skip (massive). Provide available_gb directly or target_name to use saved profile.", 

587 "inputSchema": { 

588 "type": "object", 

589 "properties": { 

590 "available_gb": {"type": "number", "description": "Available storage in GB"}, 

591 "target_name": { 

592 "type": "string", 

593 "description": "Saved target profile name (alternative to available_gb)", 

594 }, 

595 }, 

596 }, 

597 }, 

598 { 

599 "name": "farmhand_generate_plan", 

600 "description": "Generate a full deployment plan for a target. Decides which platforms to include in full, which need rating_budget selection, and which to skip. Uses rom-farmer's size_data.json for platform sizes.", 

601 "inputSchema": { 

602 "type": "object", 

603 "properties": { 

604 "target_name": {"type": "string", "description": "Saved target profile name"}, 

605 "reserved_gb": { 

606 "type": "number", 

607 "description": "GB to reserve for saves, BIOS, metadata", 

608 "default": 30, 

609 }, 

610 "exclude_platforms": { 

611 "type": "string", 

612 "description": "Comma-separated platforms to exclude (e.g., 'xbox360,ps2')", 

613 }, 

614 "budget_overrides": { 

615 "type": "string", 

616 "description": "Comma-separated platform=GB pairs (e.g., 'ps2=80,psx=60')", 

617 }, 

618 }, 

619 "required": ["target_name"], 

620 }, 

621 }, 

622 { 

623 "name": "farmhand_remote_exec", 

624 "description": "Execute a shell command on a remote target via SSH. Use for ad-hoc inspection: check binaries, configs, file listings, disk usage, etc.", 

625 "inputSchema": { 

626 "type": "object", 

627 "properties": { 

628 "host": {"type": "string", "description": "SSH host"}, 

629 "command": {"type": "string", "description": "Shell command to execute"}, 

630 "user": {"type": "string", "description": "SSH username", "default": "root"}, 

631 "password": {"type": "string", "description": "SSH password"}, 

632 "port": {"type": "integer", "description": "SSH port", "default": 22}, 

633 }, 

634 "required": ["host", "command"], 

635 }, 

636 }, 

637 { 

638 "name": "farmhand_get_target_info", 

639 "description": "Get saved target profile information from the last scan — volumes, capabilities, existing ROMs.", 

640 "inputSchema": { 

641 "type": "object", 

642 "properties": { 

643 "target_name": {"type": "string", "description": "Target profile name"}, 

644 }, 

645 "required": ["target_name"], 

646 }, 

647 }, 

648 { 

649 "name": "farmhand_deploy_status", 

650 "description": "Get deployment status for a target — what's been planned, allocated, and pending.", 

651 "inputSchema": { 

652 "type": "object", 

653 "properties": { 

654 "target_name": {"type": "string", "description": "Target profile name"}, 

655 }, 

656 "required": ["target_name"], 

657 }, 

658 }, 

659 # ---- Farm-Hand skill tools ------------------------------------------- 

660 { 

661 "name": "farmhand_skill_search", 

662 "description": "Search the Farm-Hand skill library. Returns matching skills with summaries. Combine query text with category/tag/platform/target filters (AND-combined).", 

663 "inputSchema": { 

664 "type": "object", 

665 "properties": { 

666 "query": { 

667 "type": "string", 

668 "description": "Text to search in skill names, descriptions, tags", 

669 "default": "", 

670 }, 

671 "category": { 

672 "type": "string", 

673 "description": "Filter by category: deployment, build, target, curation, maintenance, scripting, workflow", 

674 "default": "", 

675 }, 

676 "tag": {"type": "string", "description": "Filter by tag", "default": ""}, 

677 "platform": { 

678 "type": "string", 

679 "description": "Filter by ROM platform", 

680 "default": "", 

681 }, 

682 "target": {"type": "string", "description": "Filter by target name", "default": ""}, 

683 }, 

684 }, 

685 }, 

686 { 

687 "name": "farmhand_skill_show", 

688 "description": "Get full details of a skill including procedure steps, parameters, artifacts, and SKILL.md body.", 

689 "inputSchema": { 

690 "type": "object", 

691 "properties": { 

692 "name": {"type": "string", "description": "Skill name (slug format)"}, 

693 }, 

694 "required": ["name"], 

695 }, 

696 }, 

697 { 

698 "name": "farmhand_skill_artifact", 

699 "description": "Retrieve the contents of an artifact file (script, game list, config) from a skill.", 

700 "inputSchema": { 

701 "type": "object", 

702 "properties": { 

703 "skill_name": {"type": "string", "description": "Skill name"}, 

704 "filename": { 

705 "type": "string", 

706 "description": "Artifact filename (e.g. setup-rom-symlinks.sh, essentials/saturn.yaml)", 

707 }, 

708 }, 

709 "required": ["skill_name", "filename"], 

710 }, 

711 }, 

712 { 

713 "name": "farmhand_skill_save", 

714 "description": "Create or update a user skill from explicit parameters. Use for directly saving agent knowledge.", 

715 "inputSchema": { 

716 "type": "object", 

717 "properties": { 

718 "name": {"type": "string", "description": "Skill name (slug: lowercase, hyphens)"}, 

719 "description": {"type": "string", "description": "What this skill does"}, 

720 "category": { 

721 "type": "string", 

722 "description": "Category: deployment, build, target, curation, maintenance, scripting, workflow", 

723 }, 

724 "body": { 

725 "type": "string", 

726 "description": "SKILL.md body content (markdown)", 

727 "default": "", 

728 }, 

729 "tags": {"type": "string", "description": "Comma-separated tags", "default": ""}, 

730 "platforms": { 

731 "type": "string", 

732 "description": "Comma-separated platforms", 

733 "default": "", 

734 }, 

735 "targets": { 

736 "type": "string", 

737 "description": "Comma-separated targets", 

738 "default": "", 

739 }, 

740 "tools_used": { 

741 "type": "string", 

742 "description": "Comma-separated tool names", 

743 "default": "", 

744 }, 

745 "preconditions": { 

746 "type": "string", 

747 "description": "Comma-separated preconditions", 

748 "default": "", 

749 }, 

750 }, 

751 "required": ["name", "description", "category"], 

752 }, 

753 }, 

754 { 

755 "name": "farmhand_skill_save_artifact", 

756 "description": "Save an artifact file (script, game list, config) to a user skill.", 

757 "inputSchema": { 

758 "type": "object", 

759 "properties": { 

760 "skill_name": {"type": "string", "description": "Skill name"}, 

761 "filename": {"type": "string", "description": "Artifact filename"}, 

762 "content": {"type": "string", "description": "File content"}, 

763 "description": { 

764 "type": "string", 

765 "description": "What this artifact is for", 

766 "default": "", 

767 }, 

768 "artifact_type": { 

769 "type": "string", 

770 "description": "Type: script, config, list, data, template", 

771 "default": "script", 

772 }, 

773 "executable": { 

774 "type": "boolean", 

775 "description": "Make the file executable", 

776 "default": False, 

777 }, 

778 }, 

779 "required": ["skill_name", "filename", "content"], 

780 }, 

781 }, 

782 { 

783 "name": "farmhand_skill_capture_start", 

784 "description": "Begin recording agent actions for skill auto-capture. Only one recording at a time.", 

785 "inputSchema": { 

786 "type": "object", 

787 "properties": { 

788 "task_description": { 

789 "type": "string", 

790 "description": "What workflow is being recorded", 

791 }, 

792 }, 

793 "required": ["task_description"], 

794 }, 

795 }, 

796 { 

797 "name": "farmhand_skill_capture_step", 

798 "description": "Record a step in the active skill capture session.", 

799 "inputSchema": { 

800 "type": "object", 

801 "properties": { 

802 "action": { 

803 "type": "string", 

804 "description": "Step type: mcp_call, shell, ssh, python, decision", 

805 }, 

806 "description": { 

807 "type": "string", 

808 "description": "What this step does", 

809 "default": "", 

810 }, 

811 "tool": { 

812 "type": "string", 

813 "description": "Tool name (for mcp_call)", 

814 "default": "", 

815 }, 

816 "command": { 

817 "type": "string", 

818 "description": "Shell command (for shell/ssh)", 

819 "default": "", 

820 }, 

821 "args": {"type": "string", "description": "JSON-encoded arguments", "default": ""}, 

822 "result": {"type": "string", "description": "Brief result summary", "default": ""}, 

823 "success": { 

824 "type": "boolean", 

825 "description": "Whether the step succeeded", 

826 "default": True, 

827 }, 

828 }, 

829 "required": ["action"], 

830 }, 

831 }, 

832 { 

833 "name": "farmhand_skill_capture_finish", 

834 "description": "Finish recording and save the captured workflow as a reusable skill.", 

835 "inputSchema": { 

836 "type": "object", 

837 "properties": { 

838 "name": {"type": "string", "description": "Skill name (slug: lowercase, hyphens)"}, 

839 "description": { 

840 "type": "string", 

841 "description": "Override description", 

842 "default": "", 

843 }, 

844 "category": {"type": "string", "description": "Category", "default": "workflow"}, 

845 "tags": {"type": "string", "description": "Comma-separated tags", "default": ""}, 

846 "platforms": { 

847 "type": "string", 

848 "description": "Comma-separated platforms", 

849 "default": "", 

850 }, 

851 "targets": { 

852 "type": "string", 

853 "description": "Comma-separated targets", 

854 "default": "", 

855 }, 

856 "save": {"type": "boolean", "description": "Save immediately", "default": True}, 

857 }, 

858 "required": ["name"], 

859 }, 

860 }, 

861 { 

862 "name": "farmhand_skill_capture_cancel", 

863 "description": "Cancel the active skill capture session without saving.", 

864 "inputSchema": { 

865 "type": "object", 

866 "properties": {}, 

867 }, 

868 }, 

869] 

870 

871# --------------------------------------------------------------------------- 

872# Argument-dispatch map 

873# 

874# Maps tool name -> (list of positional arg names, dict of optional arg defaults) 

875# so the generic dispatcher can unpack arguments without knowing each tool. 

876# --------------------------------------------------------------------------- 

877 

878_ARG_MAP: dict[str, tuple[list[str], dict[str, Any]]] = { 

879 # Collection 

880 "list_platforms": ([], {}), 

881 "list_builds": ([], {}), 

882 "get_build_status": (["build_name"], {}), 

883 "get_platform_stats": (["platform"], {}), 

884 "query_collection": (["platform"], {"query": None, "limit": 20}), 

885 "calculate_budget": (["platform", "budget_gb"], {"compression_format": "chd"}), 

886 "get_compression_ratio": (["platform"], {"output_format": "chd"}), 

887 # Wiki 

888 "wiki_search": (["query"], {"limit": 10, "section_filter": None}), 

889 "wiki_game_info": (["game_title"], {}), 

890 "wiki_get_section": (["game_title", "section_name"], {}), 

891 "wiki_stats": ([], {}), 

892 "wiki_find_game": (["query"], {"limit": 10, "threshold": 0.5}), 

893 # Scraper 

894 "scraper_search": ( 

895 ["query"], 

896 {"platform": None, "genre": None, "limit": 20, "show_variants": False, "title_only": True}, 

897 ), 

898 "scraper_game_info": (["name"], {"platform": None, "show_variants": False}), 

899 "scraper_platforms": ([], {}), 

900 "scraper_genres": ([], {"platform": None}), 

901 "scraper_top_rated": (["platform"], {"genre": None, "limit": 20}), 

902 # DAT 

903 "dat_hardware_list": ([], {"dat_type": "fbneo"}), 

904 "dat_hardware_games": (["hardware"], {"dat_type": "fbneo", "parents_only": True}), 

905 "dat_game_variants": (["game_name"], {"dat_type": "fbneo"}), 

906 "dat_search": ( 

907 ["query"], 

908 {"dat_type": "fbneo", "hardware": None, "parents_only": False, "limit": 30}, 

909 ), 

910 # Clone list maintenance 

911 "clonelist_diff": (["old_dat", "new_dat"], {}), 

912 "clonelist_validate": (["clonelist", "dat_file"], {}), 

913 "clonelist_patch": (["clonelist", "old_dat", "new_dat"], {"output": None, "dry_run": True}), 

914 "clonelist_metadata_generate": (["dat_file"], {"output": None}), 

915 # Farm-Hand deployment 

916 "farmhand_connect": ( 

917 [], 

918 {"host": "", "user": "root", "password": "", "port": 22, "target": ""}, 

919 ), 

920 "farmhand_scan_target": ( 

921 [], 

922 { 

923 "host": "", 

924 "user": "root", 

925 "password": "", 

926 "name": "", 

927 "frontend": "batocera", 

928 "port": 22, 

929 "save": True, 

930 "target": "", 

931 }, 

932 ), 

933 "farmhand_analyze_fit": ([], {"available_gb": 0, "target_name": ""}), 

934 "farmhand_generate_plan": ( 

935 ["target_name"], 

936 {"reserved_gb": 30.0, "exclude_platforms": "", "budget_overrides": ""}, 

937 ), 

938 "farmhand_remote_exec": (["host", "command"], {"user": "root", "password": "", "port": 22}), 

939 "farmhand_get_target_info": (["target_name"], {}), 

940 "farmhand_deploy_status": (["target_name"], {}), 

941 # Farm-Hand skills 

942 "farmhand_skill_search": ( 

943 [], 

944 {"query": "", "category": "", "tag": "", "platform": "", "target": ""}, 

945 ), 

946 "farmhand_skill_show": (["name"], {}), 

947 "farmhand_skill_artifact": (["skill_name", "filename"], {}), 

948 "farmhand_skill_save": ( 

949 ["name", "description", "category"], 

950 { 

951 "body": "", 

952 "tags": "", 

953 "platforms": "", 

954 "targets": "", 

955 "tools_used": "", 

956 "preconditions": "", 

957 }, 

958 ), 

959 "farmhand_skill_save_artifact": ( 

960 ["skill_name", "filename", "content"], 

961 {"description": "", "artifact_type": "script", "executable": False}, 

962 ), 

963 "farmhand_skill_capture_start": (["task_description"], {}), 

964 "farmhand_skill_capture_step": ( 

965 ["action"], 

966 {"description": "", "tool": "", "command": "", "args": "", "result": "", "success": True}, 

967 ), 

968 "farmhand_skill_capture_finish": ( 

969 ["name"], 

970 { 

971 "description": "", 

972 "category": "workflow", 

973 "tags": "", 

974 "platforms": "", 

975 "targets": "", 

976 "save": True, 

977 }, 

978 ), 

979 "farmhand_skill_capture_cancel": ([], {}), 

980} 

981 

982 

983# --------------------------------------------------------------------------- 

984# Resources 

985# --------------------------------------------------------------------------- 

986 

987 

988async def resource_platform_config(platform: str) -> str: 

989 """Get a platform's YAML configuration.""" 

990 config_path = WORKSPACE_ROOT / "config" / "platforms" / f"{platform}.yaml" 

991 if not config_path.exists(): 

992 return f"Platform config not found: {platform}" 

993 return config_path.read_text() 

994 

995 

996async def resource_build_config(build_name: str) -> str: 

997 """Get a build's YAML configuration.""" 

998 config_path = WORKSPACE_ROOT / "config" / "builds" / f"{build_name}.yaml" 

999 if not config_path.exists(): 

1000 return f"Build config not found: {build_name}" 

1001 return config_path.read_text() 

1002 

1003 

1004async def resource_platform_list(list_type: str, platform: str) -> str: 

1005 """Get a platform's keep or delete list.""" 

1006 list_path = WORKSPACE_ROOT / "lists" / f"{platform}-{list_type}" 

1007 if not list_path.exists(): 

1008 return f"List not found: {platform}-{list_type}" 

1009 return list_path.read_text() 

1010 

1011 

1012# --------------------------------------------------------------------------- 

1013# Prompts 

1014# --------------------------------------------------------------------------- 

1015 

1016PROMPTS: dict[str, dict[str, Any]] = { 

1017 "build_collection": { 

1018 "name": "build_collection", 

1019 "description": "Build a ROM collection for a target device", 

1020 "arguments": [ 

1021 { 

1022 "name": "platform", 

1023 "description": "Platform to build (saturn, psx, etc.)", 

1024 "required": True, 

1025 }, 

1026 { 

1027 "name": "target", 

1028 "description": "Target device (batocera, rocknix, etc.)", 

1029 "required": False, 

1030 }, 

1031 { 

1032 "name": "budget", 

1033 "description": "Storage budget (64GB, 128GB, unlimited)", 

1034 "required": False, 

1035 }, 

1036 ], 

1037 }, 

1038 "analyze_collection": { 

1039 "name": "analyze_collection", 

1040 "description": "Analyze a ROM collection's health and completeness", 

1041 "arguments": [ 

1042 {"name": "platform", "description": "Platform to analyze", "required": True}, 

1043 ], 

1044 }, 

1045 "recommend_games": { 

1046 "name": "recommend_games", 

1047 "description": "Get game recommendations within a budget", 

1048 "arguments": [ 

1049 {"name": "platform", "description": "Platform name", "required": True}, 

1050 {"name": "budget_gb", "description": "Storage budget in GB", "required": True}, 

1051 {"name": "preferences", "description": "Genre/style preferences", "required": False}, 

1052 ], 

1053 }, 

1054} 

1055 

1056 

1057# --------------------------------------------------------------------------- 

1058# MCP Server Registration 

1059# --------------------------------------------------------------------------- 

1060 

1061if MCP_AVAILABLE: 

1062 server = Server(SERVER_NAME) 

1063 

1064 @server.list_tools() 

1065 async def list_tools() -> list[Tool]: 

1066 """Return list of available tools.""" 

1067 return [Tool(**schema) for schema in TOOL_SCHEMAS] 

1068 

1069 @server.call_tool() 

1070 async def call_tool(name: str, arguments: dict[str, Any]) -> list[TextContent]: 

1071 """Generic dispatcher — looks up handler and unpacks args via _ARG_MAP.""" 

1072 if not _TOOL_HANDLERS: 

1073 _register_tools() 

1074 

1075 handler = _TOOL_HANDLERS.get(name) 

1076 if handler is None: 

1077 return [TextContent(type="text", text=json.dumps({"error": f"Unknown tool: {name}"}))] 

1078 

1079 try: 

1080 arg_spec = _ARG_MAP.get(name, ([], {})) 

1081 positional_keys, optional_defaults = arg_spec 

1082 

1083 args = [arguments[k] for k in positional_keys] 

1084 kwargs = {k: arguments.get(k, v) for k, v in optional_defaults.items()} 

1085 

1086 result = await handler(*args, **kwargs) 

1087 return [TextContent(type="text", text=json.dumps(result, indent=2))] 

1088 except Exception as e: 

1089 logger.exception(f"Error in tool {name}") 

1090 return [TextContent(type="text", text=f"Error: {e!s}")] 

1091 

1092 # -- Resources --------------------------------------------------------- 

1093 

1094 @server.list_resources() 

1095 async def list_resources() -> list[Resource]: 

1096 """Return list of available resources.""" 

1097 resources = [] 

1098 

1099 platforms_dir = WORKSPACE_ROOT / "config" / "platforms" 

1100 if platforms_dir.exists(): 

1101 for yaml_file in platforms_dir.glob("*.yaml"): 

1102 resources.append( 

1103 Resource( 

1104 uri=f"romfarmer://platforms/{yaml_file.stem}", 

1105 name=f"Platform: {yaml_file.stem}", 

1106 description=f"Configuration for {yaml_file.stem} platform", 

1107 mimeType="application/yaml", 

1108 ) 

1109 ) 

1110 

1111 builds_dir = WORKSPACE_ROOT / "config" / "builds" 

1112 if builds_dir.exists(): 

1113 for yaml_file in builds_dir.glob("*.yaml"): 

1114 resources.append( 

1115 Resource( 

1116 uri=f"romfarmer://builds/{yaml_file.stem}", 

1117 name=f"Build: {yaml_file.stem}", 

1118 description=f"Build configuration: {yaml_file.stem}", 

1119 mimeType="application/yaml", 

1120 ) 

1121 ) 

1122 

1123 return resources 

1124 

1125 @server.read_resource() 

1126 async def read_resource(uri: str) -> str: 

1127 """Read a resource by URI.""" 

1128 if uri.startswith("romfarmer://platforms/"): 

1129 platform = uri.replace("romfarmer://platforms/", "") 

1130 return await resource_platform_config(platform) 

1131 elif uri.startswith("romfarmer://builds/"): 

1132 build_name = uri.replace("romfarmer://builds/", "") 

1133 return await resource_build_config(build_name) 

1134 elif uri.startswith("romfarmer://lists/"): 

1135 parts = uri.replace("romfarmer://lists/", "").split("/") 

1136 if len(parts) == 2: 

1137 platform, list_type = parts 

1138 return await resource_platform_list(list_type, platform) 

1139 return f"Unknown resource: {uri}" 

1140 

1141 # -- Prompts ----------------------------------------------------------- 

1142 

1143 @server.list_prompts() 

1144 async def list_prompts() -> list[Prompt]: 

1145 """Return available prompts.""" 

1146 return [ 

1147 Prompt( 

1148 name=p["name"], 

1149 description=p["description"], 

1150 arguments=[ 

1151 PromptArgument( 

1152 name=a["name"], 

1153 description=a["description"], 

1154 required=a.get("required", False), 

1155 ) 

1156 for a in p["arguments"] 

1157 ], 

1158 ) 

1159 for p in PROMPTS.values() 

1160 ] 

1161 

1162 @server.get_prompt() 

1163 async def get_prompt(name: str, arguments: dict[str, str] | None) -> GetPromptResult: 

1164 """Get a prompt with arguments filled in.""" 

1165 if name == "build_collection": 

1166 platform = arguments.get("platform", "saturn") if arguments else "saturn" 

1167 target = arguments.get("target", "batocera") if arguments else "batocera" 

1168 budget = arguments.get("budget", "64GB") if arguments else "64GB" 

1169 

1170 return GetPromptResult( 

1171 description=f"Build {platform} collection for {target}", 

1172 messages=[ 

1173 PromptMessage( 

1174 role="user", 

1175 content=TextContent( 

1176 type="text", 

1177 text=f"""I want to build a ROM collection for {platform}. 

1178 

1179Target device: {target} 

1180Storage budget: {budget} 

1181 

1182Please: 

11831. Check the current collection status 

11842. Recommend a build configuration 

11853. Estimate the output size 

11864. Start the build when ready""", 

1187 ), 

1188 ), 

1189 ], 

1190 ) 

1191 

1192 elif name == "analyze_collection": 

1193 platform = arguments.get("platform", "saturn") if arguments else "saturn" 

1194 

1195 return GetPromptResult( 

1196 description=f"Analyze {platform} collection", 

1197 messages=[ 

1198 PromptMessage( 

1199 role="user", 

1200 content=TextContent( 

1201 type="text", 

1202 text=f"""Analyze my {platform} ROM collection. 

1203 

1204Please check: 

12051. How many games do I have? 

12062. What's the compression ratio? 

12073. Are there any missing games from the DAT? 

12084. Any recommendations for improvement?""", 

1209 ), 

1210 ), 

1211 ], 

1212 ) 

1213 

1214 return GetPromptResult(description="Unknown prompt", messages=[]) 

1215 

1216 

1217# --------------------------------------------------------------------------- 

1218# Entry point 

1219# --------------------------------------------------------------------------- 

1220 

1221 

1222async def main() -> None: 

1223 """Run the MCP server.""" 

1224 if not MCP_AVAILABLE: 

1225 print("MCP library not installed. Run: pip install mcp") 

1226 return 

1227 

1228 from mcp.server.lowlevel.server import NotificationOptions 

1229 from mcp.server.stdio import stdio_server 

1230 

1231 async with stdio_server() as (read_stream, write_stream): 

1232 await server.run( 

1233 read_stream, 

1234 write_stream, 

1235 InitializationOptions( 

1236 server_name=SERVER_NAME, 

1237 server_version=SERVER_VERSION, 

1238 capabilities=server.get_capabilities( 

1239 notification_options=NotificationOptions(), 

1240 experimental_capabilities={}, 

1241 ), 

1242 ), 

1243 ) 

1244 

1245 

1246if __name__ == "__main__": 

1247 asyncio.run(main())