|
| 1 | +from typing import Any, Literal |
| 2 | +from mcp.server.fastmcp import FastMCP, Context |
| 3 | + |
| 4 | +from telemetry_decorator import telemetry_tool |
| 5 | +from unity_connection import send_command_with_retry |
| 6 | + |
| 7 | + |
| 8 | +def register_manage_prefabs_tools(mcp: FastMCP) -> None: |
| 9 | + """Register prefab management tools with the MCP server.""" |
| 10 | + |
| 11 | + @mcp.tool() |
| 12 | + @telemetry_tool("manage_prefabs") |
| 13 | + def manage_prefabs( |
| 14 | + ctx: Context, |
| 15 | + action: Literal["open_stage", "close_stage", "save_open_stage", "apply_instance_overrides", "revert_instance_overrides"], |
| 16 | + path: str | None = None, |
| 17 | + mode: str | None = None, |
| 18 | + save_before_close: bool | None = None, |
| 19 | + instance_id: int | None = None, |
| 20 | + target: str | None = None, |
| 21 | + ) -> dict[str, Any]: |
| 22 | + """Bridge for prefab management commands (stage control, instance overrides). |
| 23 | +
|
| 24 | + Args: |
| 25 | + action: One of the supported prefab actions ("open_stage", "close_stage", "save_open_stage", |
| 26 | + "apply_instance_overrides", "revert_instance_overrides"). |
| 27 | + path: Prefab asset path (used by "open_stage"). |
| 28 | + mode: Optional prefab stage mode (currently only "InIsolation" is supported by the C# side). |
| 29 | + save_before_close: When true, `close_stage` will save the prefab before exiting the stage. |
| 30 | + instance_id: Prefab instance ID for apply/revert overrides. Accepts int-like values. |
| 31 | + target: Scene GameObject name/path to resolve prefab instance when `instance_id` isn't provided. |
| 32 | + Returns: |
| 33 | + Dictionary mirroring the Unity bridge response. |
| 34 | + """ |
| 35 | + try: |
| 36 | + params: dict[str, str] = {"action": action} |
| 37 | + |
| 38 | + if path: |
| 39 | + params["path"] = path |
| 40 | + if mode: |
| 41 | + params["mode"] = mode |
| 42 | + if save_before_close is not None: |
| 43 | + params["saveBeforeClose"] = bool(save_before_close) |
| 44 | + |
| 45 | + coerced_instance_id = int(instance_id) |
| 46 | + if coerced_instance_id is not None: |
| 47 | + params["instanceId"] = coerced_instance_id |
| 48 | + |
| 49 | + if target: |
| 50 | + params["target"] = target |
| 51 | + |
| 52 | + response = send_command_with_retry("manage_prefabs", params) |
| 53 | + |
| 54 | + if isinstance(response, dict) and response.get("success"): |
| 55 | + return { |
| 56 | + "success": True, |
| 57 | + "message": response.get("message", "Prefab operation successful."), |
| 58 | + "data": response.get("data"), |
| 59 | + } |
| 60 | + return response if isinstance(response, dict) else {"success": False, "message": str(response)} |
| 61 | + except Exception as exc: |
| 62 | + return {"success": False, "message": f"Python error managing prefabs: {exc}"} |
0 commit comments