Coverage for fastblocks / mcp / resources.py: 47%

51 statements  

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

1"""MCP resources for FastBlocks schemas, documentation, and patterns.""" 

2 

3import logging 

4from typing import Any 

5 

6from oneiric.core.resolution import Resolver 

7 

8logger = logging.getLogger(__name__) 

9 

10# Oneiric resolver for dependency injection 

11depends = Resolver() 

12 

13 

14# Template Resources 

15 

16 

17async def get_template_syntax_reference() -> dict[str, Any]: 

18 """Get FastBlocks template syntax reference. 

19 

20 Returns: 

21 Dict with comprehensive syntax documentation 

22 """ 

23 return { 

24 "name": "FastBlocks Template Syntax Reference", 

25 "version": "0.16.0", 

26 "delimiters": { 

27 "variable": { 

28 "open": "[[", 

29 "close": "]]", 

30 "description": "Output variable values", 

31 "examples": [ 

32 "[[ user.name ]]", 

33 "[[ items|length ]]", 

34 "[[ price|currency ]]", 

35 ], 

36 }, 

37 "statement": { 

38 "open": "[%", 

39 "close": "%]", 

40 "description": "Control flow and logic", 

41 "examples": [ 

42 "[% if user.is_active %]", 

43 "[% for item in items %]", 

44 "[% block content %]", 

45 ], 

46 }, 

47 "comment": { 

48 "open": "[#", 

49 "close": "#]", 

50 "description": "Template comments (not rendered)", 

51 "examples": ["[# TODO: Add user avatar #]"], 

52 }, 

53 }, 

54 "common_patterns": { 

55 "conditionals": { 

56 "if": "[% if condition %]...[% endif %]", 

57 "if_else": "[% if condition %]...[% else %]...[% endif %]", 

58 "if_elif": "[% if cond1 %]...[% elif cond2 %]...[% else %]...[% endif %]", 

59 }, 

60 "loops": { 

61 "for": "[% for item in items %]...[% endfor %]", 

62 "for_with_index": "[% for idx, item in enumerate(items) %]...[% endfor %]", 

63 "loop_controls": "loop.index, loop.index0, loop.first, loop.last", 

64 }, 

65 "blocks": { 

66 "define": "[% block name %]...[% endblock %]", 

67 "override": "Child templates can override parent blocks", 

68 "super": "[[ super() ]] calls parent block content", 

69 }, 

70 "includes": { 

71 "basic": "[% include 'path/to/template.html' %]", 

72 "with_context": "[% include 'template.html' with context %]", 

73 "with_vars": "[% include 'template.html' with {'var': value} %]", 

74 }, 

75 }, 

76 "best_practices": [ 

77 "Use meaningful variable names", 

78 "Keep templates focused and small", 

79 "Extract reusable components", 

80 "Use blocks for layout inheritance", 

81 "Add comments for complex logic", 

82 ], 

83 } 

84 

85 

86async def get_available_filters() -> dict[str, Any]: 

87 """Get list of available template filters. 

88 

89 Returns: 

90 Dict with filter documentation 

91 """ 

92 return { 

93 "name": "FastBlocks Template Filters", 

94 "builtin_filters": { 

95 "string_filters": [ 

96 { 

97 "name": "upper", 

98 "description": "Convert to uppercase", 

99 "example": "[[ name|upper ]]", 

100 }, 

101 { 

102 "name": "lower", 

103 "description": "Convert to lowercase", 

104 "example": "[[ name|lower ]]", 

105 }, 

106 { 

107 "name": "title", 

108 "description": "Title case", 

109 "example": "[[ name|title ]]", 

110 }, 

111 { 

112 "name": "capitalize", 

113 "description": "Capitalize first letter", 

114 "example": "[[ name|capitalize ]]", 

115 }, 

116 { 

117 "name": "trim", 

118 "description": "Remove whitespace", 

119 "example": "[[ text|trim ]]", 

120 }, 

121 ], 

122 "number_filters": [ 

123 { 

124 "name": "round", 

125 "description": "Round to N decimal places", 

126 "example": "[[ price|round(2) ]]", 

127 }, 

128 { 

129 "name": "abs", 

130 "description": "Absolute value", 

131 "example": "[[ number|abs ]]", 

132 }, 

133 ], 

134 "list_filters": [ 

135 { 

136 "name": "length", 

137 "description": "Get list/string length", 

138 "example": "[[ items|length ]]", 

139 }, 

140 { 

141 "name": "first", 

142 "description": "Get first item", 

143 "example": "[[ items|first ]]", 

144 }, 

145 { 

146 "name": "last", 

147 "description": "Get last item", 

148 "example": "[[ items|last ]]", 

149 }, 

150 { 

151 "name": "join", 

152 "description": "Join list with separator", 

153 "example": "[[ tags|join(', ') ]]", 

154 }, 

155 ], 

156 "formatting_filters": [ 

157 { 

158 "name": "date", 

159 "description": "Format date", 

160 "example": "[[ created_at|date('%Y-%m-%d') ]]", 

161 }, 

162 { 

163 "name": "currency", 

164 "description": "Format as currency", 

165 "example": "[[ price|currency ]]", 

166 }, 

167 { 

168 "name": "truncate", 

169 "description": "Truncate string", 

170 "example": "[[ text|truncate(100) ]]", 

171 }, 

172 ], 

173 }, 

174 "fastblocks_filters": { 

175 "htmx_filters": [ 

176 { 

177 "name": "htmx_attrs", 

178 "description": "Generate HTMX attributes", 

179 "example": "[[ attrs|htmx_attrs ]]", 

180 }, 

181 ], 

182 "component_filters": [ 

183 { 

184 "name": "render_component", 

185 "description": "Render HTMY component", 

186 "example": "[[ render_component('user_card', {'name': 'John'}) ]]", 

187 }, 

188 ], 

189 }, 

190 } 

191 

192 

193async def get_htmy_component_catalog() -> dict[str, Any]: 

194 """Get catalog of available HTMY components. 

195 

196 Returns: 

197 Dict with component catalog 

198 """ 

199 try: 

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

201 if htmy_adapter is None: 

202 return { 

203 "success": False, 

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

205 } 

206 

207 components = await htmy_adapter.discover_components() 

208 

209 return { 

210 "name": "HTMY Component Catalog", 

211 "components": [ 

212 { 

213 "name": name, 

214 "type": metadata.type.value, 

215 "status": metadata.status.value, 

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

217 "description": metadata.docstring, 

218 "htmx_enabled": bool(metadata.htmx_attributes), 

219 } 

220 for name, metadata in components.items() 

221 ], 

222 "count": len(components), 

223 "component_types": { 

224 "basic": "Simple function-based components", 

225 "dataclass": "Dataclass-based components with type hints", 

226 "htmx": "HTMX-enabled interactive components", 

227 "composite": "Components composed of other components", 

228 }, 

229 } 

230 

231 except Exception as e: 

232 logger.error(f"Error getting component catalog: {e}") 

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

234 

235 

236# Configuration Resources 

237 

238 

239async def get_adapter_schemas() -> dict[str, Any]: 

240 """Get configuration schemas for all adapters. 

241 

242 Returns: 

243 Dict with adapter configuration schemas 

244 """ 

245 try: 

246 from .discovery import AdapterDiscoveryServer 

247 

248 discovery = AdapterDiscoveryServer() 

249 adapters = await discovery.discover_adapters() 

250 

251 return { 

252 "name": "Adapter Configuration Schemas", 

253 "adapters": { 

254 name: { 

255 "name": info.name, 

256 "category": info.category, 

257 "module_path": info.module_path, 

258 "settings_class": info.settings_class, 

259 "description": info.description, 

260 } 

261 for name, info in adapters.items() 

262 }, 

263 "common_settings": { 

264 "enabled": {"type": "boolean", "default": True}, 

265 "debug": {"type": "boolean", "default": False}, 

266 "cache_enabled": {"type": "boolean", "default": True}, 

267 }, 

268 } 

269 

270 except Exception as e: 

271 logger.error(f"Error getting adapter schemas: {e}") 

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

273 

274 

275async def get_settings_documentation() -> dict[str, Any]: 

276 """Get FastBlocks settings documentation. 

277 

278 Returns: 

279 Dict with settings structure and descriptions 

280 """ 

281 return { 

282 "name": "FastBlocks Settings Documentation", 

283 "settings_files": { 

284 "app.yml": { 

285 "description": "Application configuration", 

286 "required_fields": { 

287 "title": "Application title", 

288 "domain": "Application domain", 

289 }, 

290 "optional_fields": { 

291 "description": "Application description", 

292 "version": "Application version", 

293 }, 

294 }, 

295 "adapters.yml": { 

296 "description": "Adapter selection and configuration", 

297 "structure": { 

298 "routes": "Route handler adapter (default, custom)", 

299 "templates": "Template engine (jinja2, htmy)", 

300 "auth": "Authentication adapter (basic, jwt, oauth)", 

301 "sitemap": "Sitemap generator (asgi, native, cached)", 

302 }, 

303 }, 

304 "debug.yml": { 

305 "description": "Debug and development settings", 

306 "fields": { 

307 "fastblocks": "Enable FastBlocks debug mode", 

308 "production": "Production environment flag", 

309 }, 

310 }, 

311 }, 

312 "environment_variables": { 

313 "FASTBLOCKS_ENV": "Environment name (development, staging, production)", 

314 "FASTBLOCKS_DEBUG": "Override debug mode", 

315 "FASTBLOCKS_SECRET_KEY": "Secret key for cryptography", 

316 }, 

317 } 

318 

319 

320async def get_best_practices() -> dict[str, Any]: 

321 """Get FastBlocks best practices guide. 

322 

323 Returns: 

324 Dict with best practices documentation 

325 """ 

326 return { 

327 "name": "FastBlocks Best Practices", 

328 "architecture": { 

329 "separation_of_concerns": [ 

330 "Keep routes thin, move logic to services", 

331 "Use adapters for external integrations", 

332 "Extract reusable components", 

333 ], 

334 "template_organization": [ 

335 "Use variant-based organization (base, vanilla, etc.)", 

336 "Keep blocks focused and small", 

337 "Use template inheritance for layouts", 

338 ], 

339 "component_design": [ 

340 "Prefer dataclass components for type safety", 

341 "Use HTMX components for interactivity", 

342 "Document component props and behavior", 

343 ], 

344 }, 

345 "performance": { 

346 "caching": [ 

347 "Enable template caching in production", 

348 "Use Redis for distributed caching", 

349 "Cache database queries appropriately", 

350 ], 

351 "optimization": [ 

352 "Minify CSS and JavaScript", 

353 "Use async operations throughout", 

354 "Enable Brotli compression", 

355 ], 

356 }, 

357 "security": { 

358 "authentication": [ 

359 "Use secure session management", 

360 "Implement CSRF protection", 

361 "Validate all user inputs", 

362 ], 

363 "templates": [ 

364 "Auto-escape by default", 

365 "Use safe filters when needed", 

366 "Sanitize user-generated content", 

367 ], 

368 }, 

369 } 

370 

371 

372# API Resources 

373 

374 

375async def get_route_definitions() -> dict[str, Any]: 

376 """Get route definitions from FastBlocks application. 

377 

378 Returns: 

379 Dict with route information 

380 """ 

381 try: 

382 # Try to get routes from ACB registry 

383 routes_adapter = await depends.resolve("fastblocks", "routes") 

384 if routes_adapter is None: 

385 return { 

386 "success": False, 

387 "error": "Routes adapter not available", 

388 } 

389 

390 # This would need actual route introspection 

391 # For now, return basic structure 

392 return { 

393 "name": "FastBlocks Route Definitions", 

394 "routes": [ 

395 { 

396 "path": "/", 

397 "methods": ["GET"], 

398 "handler": "index", 

399 "description": "Home page", 

400 }, 

401 ], 

402 "note": "Route definitions depend on application configuration", 

403 } 

404 

405 except Exception as e: 

406 logger.error(f"Error getting route definitions: {e}") 

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

408 

409 

410async def get_htmx_patterns() -> dict[str, Any]: 

411 """Get HTMX integration patterns for FastBlocks. 

412 

413 Returns: 

414 Dict with HTMX pattern documentation 

415 """ 

416 return { 

417 "name": "FastBlocks HTMX Integration Patterns", 

418 "common_patterns": { 

419 "inline_editing": { 

420 "description": "Click to edit inline", 

421 "template_example": """<div hx-get="/edit/[[ item.id ]]" 

422 hx-trigger="click" 

423 hx-target="this" 

424 hx-swap="outerHTML"> 

425 [[ item.name ]] 

426</div>""", 

427 }, 

428 "infinite_scroll": { 

429 "description": "Load more on scroll", 

430 "template_example": """<div hx-get="/items?page=[[ page + 1 ]]" 

431 hx-trigger="revealed" 

432 hx-swap="afterend"> 

433</div>""", 

434 }, 

435 "active_search": { 

436 "description": "Search as you type", 

437 "template_example": """<input type="text" 

438 hx-get="/search" 

439 hx-trigger="keyup changed delay:500ms" 

440 hx-target="#results">""", 

441 }, 

442 "delete_confirmation": { 

443 "description": "Confirm before delete", 

444 "template_example": """<button hx-delete="/item/[[ item.id ]]" 

445 hx-confirm="Are you sure?" 

446 hx-target="closest .item" 

447 hx-swap="outerHTML swap:1s"> 

448 Delete 

449</button>""", 

450 }, 

451 }, 

452 "response_helpers": { 

453 "htmx_trigger": "Trigger client-side events", 

454 "htmx_redirect": "Client-side redirect", 

455 "htmx_refresh": "Refresh current page", 

456 "htmx_response": "Custom HTMX response", 

457 }, 

458 } 

459 

460 

461# Resource registration function 

462 

463 

464async def register_fastblocks_resources(server: Any) -> None: 

465 """Register all FastBlocks MCP resources with the server. 

466 

467 Args: 

468 server: MCP server instance from ACB 

469 """ 

470 try: 

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

472 

473 # Define resource registry 

474 resources = { 

475 # Template resources 

476 "template_syntax": get_template_syntax_reference, 

477 "template_filters": get_available_filters, 

478 "component_catalog": get_htmy_component_catalog, 

479 # Configuration resources 

480 "adapter_schemas": get_adapter_schemas, 

481 "settings_docs": get_settings_documentation, 

482 "best_practices": get_best_practices, 

483 # API resources 

484 "route_definitions": get_route_definitions, 

485 "htmx_patterns": get_htmx_patterns, 

486 } 

487 

488 # Register resources with MCP server 

489 await register_resources(server, resources) # type: ignore[misc] 

490 

491 logger.info(f"Registered {len(resources)} FastBlocks MCP resources") 

492 

493 except Exception as e: 

494 logger.error(f"Failed to register MCP resources: {e}") 

495 raise