Coverage for fastblocks / mcp / server.py: 37%

78 statements  

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

1"""FastBlocks MCP (Model Context Protocol) server implementation. 

2 

3Provides IDE/AI assistant integration for FastBlocks capabilities including: 

4- Template management and validation 

5- Component creation and discovery 

6- Adapter configuration and health checks 

7""" 

8 

9import logging 

10from contextlib import suppress 

11from typing import Any 

12 

13logger = logging.getLogger(__name__) 

14 

15 

16class FastBlocksMCPServer: 

17 """FastBlocks MCP protocol server using Oneiric infrastructure.""" 

18 

19 def __init__(self, name: str = "fastblocks", version: str = "0.16.0"): 

20 """Initialize FastBlocks MCP server. 

21 

22 Args: 

23 name: Server name for MCP protocol 

24 version: FastBlocks version 

25 """ 

26 self.name = name 

27 self.version = version 

28 self._server: Any | None = None 

29 self._initialized = False 

30 

31 async def initialize(self) -> None: 

32 """Initialize MCP server with Oneiric integration.""" 

33 if self._initialized: 

34 return 

35 

36 try: 

37 # Import Oneiric MCP utilities 

38 from mcp_common.cli import MCPServerCLIFactory 

39 

40 # Create server using Oneiric infrastructure 

41 # Oneiric provides the MCP server with rate limiting already configured 

42 self._server = MCPServerCLIFactory.create_server() 

43 

44 # Register FastBlocks tools and resources 

45 await self._register_tools() 

46 await self._register_resources() 

47 

48 self._initialized = True 

49 logger.info( 

50 f"FastBlocks MCP server initialized: {self.name} v{self.version} " 

51 f"(using Oneiric infrastructure with rate limiting: 15 req/sec, burst 40)" 

52 ) 

53 

54 except ImportError: 

55 logger.debug( 

56 "Oneiric MCP dependencies not available - graceful degradation" 

57 ) 

58 except Exception as e: 

59 logger.error(f"Failed to initialize MCP server: {e}") 

60 

61 async def _register_tools(self) -> None: 

62 """Register FastBlocks MCP tools. 

63 

64 Tools will be implemented in tools.py and registered here. 

65 """ 

66 with suppress(Exception): 

67 from .tools import register_fastblocks_tools 

68 

69 await register_fastblocks_tools(self._server) 

70 logger.debug("FastBlocks MCP tools registered") 

71 

72 async def _register_resources(self) -> None: 

73 """Register FastBlocks MCP resources. 

74 

75 Resources will be implemented in resources.py and registered here. 

76 """ 

77 with suppress(Exception): 

78 from .resources import register_fastblocks_resources 

79 

80 await register_fastblocks_resources(self._server) 

81 logger.debug("FastBlocks MCP resources registered") 

82 

83 async def start(self) -> None: 

84 """Start the MCP server.""" 

85 if not self._initialized: 

86 await self.initialize() 

87 

88 if self._server is None: 

89 logger.warning("MCP server not available - skipping start") 

90 return 

91 

92 try: 

93 logger.info("Starting FastBlocks MCP server...") 

94 await self._server.run() 

95 except Exception as e: 

96 logger.error(f"MCP server error: {e}") 

97 raise 

98 

99 async def stop(self) -> None: 

100 """Stop the MCP server gracefully.""" 

101 if self._server is None: 

102 return 

103 

104 try: 

105 logger.info("Stopping FastBlocks MCP server...") 

106 # Server shutdown will be handled by Oneiric 

107 await self._server.stop() 

108 except Exception as e: 

109 logger.error(f"Error stopping MCP server: {e}") 

110 

111 

112async def create_fastblocks_mcp_server() -> FastBlocksMCPServer: 

113 """Create and initialize FastBlocks MCP server. 

114 

115 Returns: 

116 Initialized FastBlocksMCPServer instance 

117 

118 Example: 

119 >>> server = await create_fastblocks_mcp_server() 

120 >>> await server.start() 

121 """ 

122 server = FastBlocksMCPServer() 

123 await server.initialize() 

124 return server 

125 

126 

127# Export ASGI app for uvicorn (standardized startup pattern) 

128# Note: Since Oneiric's MCP server returns an ASGI app asynchronously, 

129# we need to provide a synchronous http_app export for uvicorn 

130def _get_http_app() -> Any: 

131 """Get the ASGI app for uvicorn. 

132 

133 This creates a server instance synchronously and extracts the http_app. 

134 """ 

135 import asyncio 

136 from contextlib import suppress 

137 

138 try: 

139 from mcp_common.cli import MCPServerCLIFactory 

140 

141 # Create the MCP server (Oneiric returns ASGI app) 

142 mcp_instance = MCPServerCLIFactory.create_server() 

143 

144 # Register tools synchronously 

145 with suppress(Exception): 

146 from .tools import register_fastblocks_tools 

147 

148 # Tools registration needs to be sync for uvicorn startup 

149 loop = asyncio.new_event_loop() 

150 asyncio.set_event_loop(loop) 

151 loop.run_until_complete(register_fastblocks_tools(mcp_instance)) 

152 loop.close() 

153 

154 return mcp_instance.http_app 

155 

156 except Exception as e: 

157 logger.error(f"Failed to create http_app: {e}") 

158 return None 

159 

160 

161# Lazy initialization of http_app to avoid import-time side effects 

162# (Causing pytest collection errors when http_app is created on module import) 

163_http_app_cache: Any = None 

164 

165 

166def get_http_app() -> Any: 

167 """Get the ASGI app for uvicorn (lazy initialization). 

168 

169 Returns: 

170 ASGI app instance or None if initialization fails 

171 

172 This function defers http_app creation until explicitly called, 

173 preventing import-time side effects that cause test collection errors. 

174 """ 

175 global _http_app_cache 

176 if _http_app_cache is None: 

177 _http_app_cache = _get_http_app() 

178 return _http_app_cache 

179 

180 

181# For backward compatibility with code that might import http_app directly 

182# This is now None at import time and only created when explicitly requested 

183http_app = None