|
| 1 | +"""Factory for creating MCP runtime instances.""" |
| 2 | + |
| 3 | +import json |
| 4 | +import logging |
| 5 | +import os |
| 6 | +import uuid |
| 7 | +from typing import Any |
| 8 | + |
| 9 | +from uipath.runtime import ( |
| 10 | + UiPathRuntimeContext, |
| 11 | + UiPathRuntimeProtocol, |
| 12 | +) |
| 13 | +from uipath.runtime.errors import UiPathErrorCategory |
| 14 | + |
| 15 | +from uipath_mcp._cli._runtime._exception import McpErrorCode, UiPathMcpRuntimeError |
| 16 | +from uipath_mcp._cli._runtime._runtime import UiPathMcpRuntime |
| 17 | +from uipath_mcp._cli._utils._config import McpConfig |
| 18 | + |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | + |
| 22 | +class UiPathMcpRuntimeFactory: |
| 23 | + """Factory for creating MCP runtimes from mcp.json configuration.""" |
| 24 | + |
| 25 | + def __init__( |
| 26 | + self, |
| 27 | + context: UiPathRuntimeContext, |
| 28 | + ): |
| 29 | + """Initialize the factory. |
| 30 | +
|
| 31 | + Args: |
| 32 | + context: UiPathRuntimeContext to use for runtime creation. |
| 33 | + """ |
| 34 | + self.context = context |
| 35 | + self._mcp_config: McpConfig | None = None |
| 36 | + self._server_id: str | None = None |
| 37 | + self._server_slug: str | None = None |
| 38 | + |
| 39 | + # Load fps context from uipath.json if available |
| 40 | + self._load_fps_context() |
| 41 | + |
| 42 | + def _load_fps_context(self) -> None: |
| 43 | + """ |
| 44 | + Load fps context from uipath.json for server registration. |
| 45 | + """ |
| 46 | + config_path = self.context.config_path or "uipath.json" |
| 47 | + if os.path.exists(config_path): |
| 48 | + try: |
| 49 | + with open(config_path, "r") as f: |
| 50 | + config: dict[str, Any] = json.load(f) |
| 51 | + |
| 52 | + config_runtime = config.get("runtime", {}) |
| 53 | + if "fpsContext" in config_runtime: |
| 54 | + fps_context = config_runtime["fpsContext"] |
| 55 | + self._server_id = fps_context.get("Id") |
| 56 | + self._server_slug = fps_context.get("Slug") |
| 57 | + except Exception as e: |
| 58 | + logger.warning(f"Failed to load fps context: {e}") |
| 59 | + |
| 60 | + def _load_mcp_config(self) -> McpConfig: |
| 61 | + """Load mcp.json configuration.""" |
| 62 | + if self._mcp_config is None: |
| 63 | + self._mcp_config = McpConfig() |
| 64 | + return self._mcp_config |
| 65 | + |
| 66 | + def discover_entrypoints(self) -> list[str]: |
| 67 | + """Discover all MCP server entrypoints. |
| 68 | +
|
| 69 | + Returns: |
| 70 | + List of server names that can be used as entrypoints. |
| 71 | + """ |
| 72 | + mcp_config = self._load_mcp_config() |
| 73 | + if not mcp_config.exists: |
| 74 | + return [] |
| 75 | + return mcp_config.get_server_names() |
| 76 | + |
| 77 | + async def discover_runtimes(self) -> list[UiPathRuntimeProtocol]: |
| 78 | + """Discover runtime instances for all entrypoints. |
| 79 | + This is not running as part of a job, but is intended for the dev machine. |
| 80 | +
|
| 81 | + Returns: |
| 82 | + List of UiPathMcpRuntime instances, one per entrypoint. |
| 83 | + """ |
| 84 | + entrypoints = self.discover_entrypoints() |
| 85 | + runtimes: list[UiPathRuntimeProtocol] = [] |
| 86 | + |
| 87 | + for entrypoint in entrypoints: |
| 88 | + runtime = await self.new_runtime(entrypoint, entrypoint) |
| 89 | + runtimes.append(runtime) |
| 90 | + |
| 91 | + return runtimes |
| 92 | + |
| 93 | + async def new_runtime( |
| 94 | + self, entrypoint: str, runtime_id: str |
| 95 | + ) -> UiPathRuntimeProtocol: |
| 96 | + """Create a new MCP runtime instance. |
| 97 | +
|
| 98 | + Args: |
| 99 | + entrypoint: Server name from mcp.json. |
| 100 | + runtime_id: Unique identifier for the runtime instance. |
| 101 | +
|
| 102 | + Returns: |
| 103 | + Configured UiPathMcpRuntime instance. |
| 104 | +
|
| 105 | + Raises: |
| 106 | + UiPathMcpRuntimeError: If configuration is invalid or server not found. |
| 107 | + """ |
| 108 | + mcp_config = self._load_mcp_config() |
| 109 | + |
| 110 | + if not mcp_config.exists: |
| 111 | + raise UiPathMcpRuntimeError( |
| 112 | + McpErrorCode.CONFIGURATION_ERROR, |
| 113 | + "Invalid configuration", |
| 114 | + "mcp.json not found", |
| 115 | + UiPathErrorCategory.DEPLOYMENT, |
| 116 | + ) |
| 117 | + |
| 118 | + server = mcp_config.get_server(entrypoint) |
| 119 | + if not server: |
| 120 | + available = ", ".join(mcp_config.get_server_names()) |
| 121 | + raise UiPathMcpRuntimeError( |
| 122 | + McpErrorCode.SERVER_NOT_FOUND, |
| 123 | + "MCP server not found", |
| 124 | + f"Server '{entrypoint}' not found. Available: {available}", |
| 125 | + UiPathErrorCategory.DEPLOYMENT, |
| 126 | + ) |
| 127 | + |
| 128 | + # Validate runtime_id is a valid UUID, generate new one if not |
| 129 | + try: |
| 130 | + uuid.UUID(runtime_id) |
| 131 | + except ValueError: |
| 132 | + runtime_id = str(uuid.uuid4()) |
| 133 | + |
| 134 | + return UiPathMcpRuntime( |
| 135 | + server=server, |
| 136 | + runtime_id=runtime_id, |
| 137 | + entrypoint=entrypoint, |
| 138 | + folder_key=self.context.folder_key, |
| 139 | + server_id=self._server_id, |
| 140 | + server_slug=self._server_slug, |
| 141 | + ) |
| 142 | + |
| 143 | + async def dispose(self) -> None: |
| 144 | + """Cleanup factory resources.""" |
| 145 | + self._mcp_config = None |
0 commit comments