Coverage for fastblocks / mcp / tools.py: 72%

171 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-02 20:00 -0800

1"""MCP tools for FastBlocks template, component, and adapter management.""" 

2 

3import logging 

4import operator 

5from pathlib import Path 

6from typing import Any 

7 

8from oneiric.core.resolution import Resolver 

9 

10from .discovery import AdapterDiscoveryServer 

11from .health import HealthCheckSystem 

12 

13logger = logging.getLogger(__name__) 

14 

15# Oneiric resolver for dependency injection 

16depends = Resolver() 

17 

18 

19# Template Management Tools 

20 

21 

22async def create_template( 

23 name: str, 

24 template_type: str = "jinja2", 

25 variant: str = "base", 

26 content: str = "", 

27) -> dict[str, Any]: 

28 """Create a new FastBlocks template. 

29 

30 Args: 

31 name: Template name (e.g., "user_card") 

32 template_type: Template engine (jinja2, htmy) 

33 variant: Template variant/theme (base, vanilla, etc.) 

34 content: Template content (optional, uses default if empty) 

35 

36 Returns: 

37 Dict with template creation status and path 

38 """ 

39 try: 

40 # Determine template directory 

41 templates_root = Path.cwd() / "templates" / variant / "blocks" 

42 templates_root.mkdir(parents=True, exist_ok=True) 

43 

44 # Determine file extension 

45 extension = ".html" if template_type == "jinja2" else ".py" 

46 template_path = templates_root / f"{name}{extension}" 

47 

48 if template_path.exists(): 

49 return { 

50 "success": False, 

51 "error": f"Template already exists: {template_path}", 

52 "path": str(template_path), 

53 } 

54 

55 # Generate default content if not provided 

56 if not content: 

57 if template_type == "jinja2": 

58 content = f"""[# {name} template #] 

59<div class="{name}"> 

60 [[ content ]] 

61</div> 

62""" 

63 else: # htmy 

64 content = f'''"""HTMY component: {name}""" 

65from dataclasses import dataclass 

66from typing import Any 

67 

68 

69@dataclass 

70class {name.title().replace("_", "")}: 

71 """HTMY component for {name}.""" 

72 

73 content: str = "" 

74 

75 def htmy(self, context: dict[str, Any]) -> str: 

76 return f""" 

77 <div class="{name}"> 

78 {{self.content}} 

79 </div> 

80 """ 

81''' 

82 

83 # Write template file 

84 template_path.write_text(content) 

85 

86 return { 

87 "success": True, 

88 "path": str(template_path), 

89 "type": template_type, 

90 "variant": variant, 

91 } 

92 

93 except Exception as e: 

94 logger.error(f"Error creating template: {e}") 

95 return {"success": False, "error": str(e)} 

96 

97 

98async def validate_template(template_path: str) -> dict[str, Any]: 

99 """Validate a FastBlocks template for syntax errors. 

100 

101 Args: 

102 template_path: Path to template file 

103 

104 Returns: 

105 Dict with validation status and any errors found 

106 """ 

107 try: 

108 path = Path(template_path) 

109 if not path.exists(): 

110 return {"success": False, "error": f"Template not found: {template_path}"} 

111 

112 content = path.read_text() 

113 

114 # Get syntax support from ACB registry 

115 syntax_support = await depends.resolve("fastblocks", "syntax_support") 

116 if syntax_support is None: 

117 return { 

118 "success": False, 

119 "error": "Syntax support not available", 

120 } 

121 

122 # Check syntax 

123 errors = syntax_support.check_syntax(content, path) 

124 

125 if not errors: 

126 return {"success": True, "errors": [], "path": template_path} 

127 

128 return { 

129 "success": False, 

130 "errors": [ 

131 { 

132 "line": e.line, 

133 "column": e.column, 

134 "message": e.message, 

135 "severity": e.severity, 

136 "code": e.code, 

137 "fix_suggestion": e.fix_suggestion, 

138 } 

139 for e in errors 

140 ], 

141 "path": template_path, 

142 } 

143 

144 except Exception as e: 

145 logger.error(f"Error validating template: {e}") 

146 return {"success": False, "error": str(e)} 

147 

148 

149def _should_skip_variant_dir(variant_dir: Path, variant_filter: str | None) -> bool: 

150 """Check if variant directory should be skipped. 

151 

152 Args: 

153 variant_dir: Variant directory path 

154 variant_filter: Optional variant filter 

155 

156 Returns: 

157 True if should skip, False otherwise 

158 """ 

159 # Skip if variant filter is set and directory name doesn't match 

160 if variant_filter and variant_dir.name != variant_filter: 

161 return True 

162 

163 return False 

164 

165 

166def _determine_template_type(suffix: str) -> str: 

167 """Determine template type from file suffix. 

168 

169 Args: 

170 suffix: File suffix (e.g., '.html', '.py') 

171 

172 Returns: 

173 Template type ('jinja2', 'htmy', or 'unknown') 

174 """ 

175 if suffix in (".html", ".jinja2", ".j2"): 

176 return "jinja2" 

177 elif suffix == ".py": 

178 return "htmy" 

179 return "unknown" 

180 

181 

182def _create_template_info(template_file: Path, variant_name: str) -> dict[str, str]: 

183 """Create template info dictionary. 

184 

185 Args: 

186 template_file: Template file path 

187 variant_name: Variant directory name 

188 

189 Returns: 

190 Template info dict 

191 """ 

192 return { 

193 "name": template_file.stem, 

194 "path": str(template_file), 

195 "variant": variant_name, 

196 "type": _determine_template_type(template_file.suffix), 

197 } 

198 

199 

200def _collect_variant_templates(variant_dir: Path) -> list[dict[str, str]]: 

201 """Collect all template files from a variant directory. 

202 

203 Args: 

204 variant_dir: Variant directory path 

205 

206 Returns: 

207 List of template info dicts 

208 """ 

209 templates: list[dict[str, str]] = [] 

210 blocks_dir = variant_dir / "blocks" 

211 

212 if not blocks_dir.exists(): 

213 return templates 

214 

215 for template_file in blocks_dir.rglob("*"): 

216 if template_file.is_file() and template_file.suffix in (".html", ".py"): 

217 templates.append(_create_template_info(template_file, variant_dir.name)) 

218 

219 return templates 

220 

221 

222async def list_templates(variant: str | None = None) -> dict[str, Any]: 

223 """List all available FastBlocks templates. 

224 

225 Args: 

226 variant: Optional variant filter (base, vanilla, etc.) 

227 

228 Returns: 

229 Dict with list of discovered templates 

230 """ 

231 try: 

232 templates_root = Path.cwd() / "templates" 

233 

234 # Guard clause: no templates directory 

235 if not templates_root.exists(): 

236 return {"success": True, "templates": [], "count": 0} 

237 

238 templates: list[dict[str, str]] = [] 

239 

240 # Search for template files in each variant directory 

241 for variant_dir in templates_root.iterdir(): 

242 if _should_skip_variant_dir(variant_dir, variant): 

243 continue 

244 

245 templates.extend(_collect_variant_templates(variant_dir)) 

246 

247 return { 

248 "success": True, 

249 "templates": sorted(templates, key=operator.itemgetter("name")), 

250 "count": len(templates), 

251 } 

252 

253 except Exception as e: 

254 logger.error(f"Error listing templates: {e}") 

255 return {"success": False, "error": str(e)} 

256 

257 

258async def render_template( 

259 template_name: str, context: dict[str, Any] | None = None, variant: str = "base" 

260) -> dict[str, Any]: 

261 """Render a template with given context for testing. 

262 

263 Args: 

264 template_name: Template name to render 

265 context: Template context variables 

266 variant: Template variant (base, vanilla, etc.) 

267 

268 Returns: 

269 Dict with rendered output or error 

270 """ 

271 try: 

272 # Get template adapter from ACB 

273 templates = await depends.resolve("fastblocks", "templates") 

274 if templates is None: 

275 return { 

276 "success": False, 

277 "error": "Template adapter not available", 

278 } 

279 

280 # Render template 

281 context = context or {} 

282 rendered = await templates.render( 

283 f"{variant}/blocks/{template_name}.html", context 

284 ) 

285 

286 return { 

287 "success": True, 

288 "output": rendered, 

289 "template": template_name, 

290 "variant": variant, 

291 } 

292 

293 except Exception as e: 

294 logger.error(f"Error rendering template: {e}") 

295 return {"success": False, "error": str(e)} 

296 

297 

298# Component Management Tools 

299 

300 

301async def create_component( 

302 name: str, 

303 component_type: str = "dataclass", 

304 props: dict[str, str] | None = None, 

305 htmx_enabled: bool = False, 

306) -> dict[str, Any]: 

307 """Create a new HTMY component. 

308 

309 Args: 

310 name: Component name 

311 component_type: Component type (basic, dataclass, htmx, composite) 

312 props: Component properties as {name: type} 

313 htmx_enabled: Enable HTMX features 

314 

315 Returns: 

316 Dict with component creation status 

317 """ 

318 try: 

319 htmy_adapter = await depends.resolve("fastblocks", "htmy") 

320 if htmy_adapter is None: 

321 return { 

322 "success": False, 

323 "error": "HTMY adapter not available", 

324 } 

325 

326 from fastblocks.adapters.templates._htmy_components import ComponentType 

327 

328 # Map string type to ComponentType enum 

329 type_map = { 

330 "basic": ComponentType.BASIC, 

331 "dataclass": ComponentType.DATACLASS, 

332 "htmx": ComponentType.HTMX, 

333 "composite": ComponentType.COMPOSITE, 

334 } 

335 

336 comp_type = type_map.get(component_type.lower(), ComponentType.DATACLASS) 

337 

338 # Scaffold component 

339 kwargs: dict[str, Any] = {} 

340 if props: 

341 kwargs["props"] = props 

342 if htmx_enabled: 

343 kwargs["htmx_enabled"] = htmx_enabled 

344 

345 created_path = await htmy_adapter.scaffold_component( 

346 name=name, component_type=comp_type, **kwargs 

347 ) 

348 

349 return { 

350 "success": True, 

351 "path": str(created_path), 

352 "name": name, 

353 "type": component_type, 

354 } 

355 

356 except Exception as e: 

357 logger.error(f"Error creating component: {e}") 

358 return {"success": False, "error": str(e)} 

359 

360 

361async def list_components() -> dict[str, Any]: 

362 """List all discovered HTMY components. 

363 

364 Returns: 

365 Dict with list of components and metadata 

366 """ 

367 try: 

368 htmy_adapter = await depends.resolve("fastblocks", "htmy") 

369 if htmy_adapter is None: 

370 return { 

371 "success": False, 

372 "error": "HTMY adapter not available", 

373 } 

374 

375 components = await htmy_adapter.discover_components() 

376 

377 return { 

378 "success": True, 

379 "components": [ 

380 { 

381 "name": name, 

382 "path": str(metadata.path), 

383 "type": metadata.type.value, 

384 "status": metadata.status.value, 

385 "docstring": metadata.docstring, 

386 "error": metadata.error_message, 

387 } 

388 for name, metadata in components.items() 

389 ], 

390 "count": len(components), 

391 } 

392 

393 except Exception as e: 

394 logger.error(f"Error listing components: {e}") 

395 return {"success": False, "error": str(e)} 

396 

397 

398async def validate_component(component_name: str) -> dict[str, Any]: 

399 """Validate an HTMY component. 

400 

401 Args: 

402 component_name: Component name to validate 

403 

404 Returns: 

405 Dict with validation status and metadata 

406 """ 

407 try: 

408 htmy_adapter = await depends.resolve("fastblocks", "htmy") 

409 if htmy_adapter is None: 

410 return { 

411 "success": False, 

412 "error": "HTMY adapter not available", 

413 } 

414 

415 metadata = await htmy_adapter.validate_component(component_name) 

416 

417 if metadata is None: 

418 return { 

419 "success": False, 

420 "error": f"Component '{component_name}' not found", 

421 } 

422 

423 return { 

424 "success": metadata.status.value != "error", 

425 "component": component_name, 

426 "type": metadata.type.value, 

427 "status": metadata.status.value, 

428 "path": str(metadata.path), 

429 "docstring": metadata.docstring, 

430 "error": metadata.error_message, 

431 "dependencies": metadata.dependencies, 

432 } 

433 

434 except Exception as e: 

435 logger.error(f"Error validating component: {e}") 

436 return {"success": False, "error": str(e)} 

437 

438 

439# Adapter Configuration Tools 

440 

441 

442async def configure_adapter( 

443 adapter_name: str, settings: dict[str, Any] 

444) -> dict[str, Any]: 

445 """Configure a FastBlocks adapter. 

446 

447 Args: 

448 adapter_name: Adapter name (e.g., "templates", "auth") 

449 settings: Adapter configuration settings 

450 

451 Returns: 

452 Dict with configuration status 

453 """ 

454 try: 

455 # Get adapter from ACB registry 

456 adapter = await depends.resolve("fastblocks", adapter_name) 

457 if adapter is None: 

458 return { 

459 "success": False, 

460 "error": f"Adapter '{adapter_name}' not found", 

461 } 

462 

463 # Update adapter settings 

464 for key, value in settings.items(): 

465 if hasattr(adapter, key): 

466 setattr(adapter, key, value) 

467 

468 return { 

469 "success": True, 

470 "adapter": adapter_name, 

471 "settings": settings, 

472 } 

473 

474 except Exception as e: 

475 logger.error(f"Error configuring adapter: {e}") 

476 return {"success": False, "error": str(e)} 

477 

478 

479async def list_adapters(category: str | None = None) -> dict[str, Any]: 

480 """List all available FastBlocks adapters. 

481 

482 Args: 

483 category: Optional category filter 

484 

485 Returns: 

486 Dict with list of adapters and metadata 

487 """ 

488 try: 

489 discovery = AdapterDiscoveryServer() 

490 adapters = await discovery.discover_adapters() 

491 

492 # Filter by category if specified 

493 if category: 

494 adapters = { 

495 name: info 

496 for name, info in adapters.items() 

497 if info.category == category 

498 } 

499 

500 return { 

501 "success": True, 

502 "adapters": [info.to_dict() for info in adapters.values()], 

503 "count": len(adapters), 

504 "categories": list({info.category for info in adapters.values()}), 

505 } 

506 

507 except Exception as e: 

508 logger.error(f"Error listing adapters: {e}") 

509 return {"success": False, "error": str(e)} 

510 

511 

512async def check_adapter_health(adapter_name: str | None = None) -> dict[str, Any]: 

513 """Check health status of adapters. 

514 

515 Args: 

516 adapter_name: Optional specific adapter to check 

517 

518 Returns: 

519 Dict with health check results 

520 """ 

521 try: 

522 from .registry import AdapterRegistry 

523 

524 # Create registry and health system 

525 registry = AdapterRegistry() 

526 health_system = HealthCheckSystem(registry) 

527 results_dict = await health_system.check_all_adapters() 

528 

529 # Convert to list of dicts 

530 results = [ 

531 {"adapter": name} | result.to_dict() 

532 for name, result in results_dict.items() 

533 ] 

534 

535 # Filter by adapter if specified 

536 if adapter_name: 

537 results = [r for r in results if r["adapter"] == adapter_name] 

538 

539 return { 

540 "success": True, 

541 "checks": results, 

542 "count": len(results), 

543 "healthy": sum(1 for r in results if r["status"] == "healthy"), 

544 "unhealthy": sum(1 for r in results if r["status"] != "healthy"), 

545 } 

546 

547 except Exception as e: 

548 logger.error(f"Error checking adapter health: {e}") 

549 return {"success": False, "error": str(e)} 

550 

551 

552# Tool registration function 

553 

554 

555async def register_fastblocks_tools(server: Any) -> None: 

556 """Register all FastBlocks MCP tools with the server. 

557 

558 Args: 

559 server: MCP server instance from ACB 

560 """ 

561 try: 

562 # MIGRATED: Removed ACB MCP registration - Oneiric MCP not yet available 

563 

564 # Define tool registry 

565 tools = { 

566 # Template tools 

567 "create_template": create_template, 

568 "validate_template": validate_template, 

569 "list_templates": list_templates, 

570 "render_template": render_template, 

571 # Component tools 

572 "create_component": create_component, 

573 "list_components": list_components, 

574 "validate_component": validate_component, 

575 # Adapter tools 

576 "configure_adapter": configure_adapter, 

577 "list_adapters": list_adapters, 

578 "check_adapter_health": check_adapter_health, 

579 } 

580 

581 # Register tools with MCP server 

582 await register_tools(server, tools) # type: ignore[misc] 

583 

584 logger.info(f"Registered {len(tools)} FastBlocks MCP tools") 

585 

586 except Exception as e: 

587 logger.error(f"Failed to register MCP tools: {e}") 

588 raise