unity-ui-agent-mcp 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- unity_ui_agent_mcp/__init__.py +3 -0
- unity_ui_agent_mcp/compare.py +168 -0
- unity_ui_agent_mcp/crop.py +35 -0
- unity_ui_agent_mcp/server.py +865 -0
- unity_ui_agent_mcp/unity_client.py +89 -0
- unity_ui_agent_mcp-0.3.0.dist-info/METADATA +52 -0
- unity_ui_agent_mcp-0.3.0.dist-info/RECORD +9 -0
- unity_ui_agent_mcp-0.3.0.dist-info/WHEEL +4 -0
- unity_ui_agent_mcp-0.3.0.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Image comparison between the target mockup and a render of the UI (SSIM).
|
|
2
|
+
|
|
3
|
+
Pure functions over image bytes: no Unity and no files, so they run in CI and in tests.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import io
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
from PIL import Image
|
|
12
|
+
from skimage import measure
|
|
13
|
+
from skimage.metrics import structural_similarity
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def load_rgb(data: bytes) -> np.ndarray:
|
|
17
|
+
"""Decode PNG or JPG bytes into an RGB uint8 array of shape (height, width, 3)."""
|
|
18
|
+
with Image.open(io.BytesIO(data)) as image:
|
|
19
|
+
return np.asarray(image.convert("RGB"), dtype=np.uint8)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def pixel_diff(reference: bytes, rendered: bytes) -> float:
|
|
23
|
+
"""Mean difference per pixel channel, from 0 (identical) to 1 (every channel opposite).
|
|
24
|
+
|
|
25
|
+
Both images must have the same size, as for ssim_score.
|
|
26
|
+
"""
|
|
27
|
+
expected = load_rgb(reference)
|
|
28
|
+
actual = load_rgb(rendered)
|
|
29
|
+
if expected.shape != actual.shape:
|
|
30
|
+
raise ValueError(
|
|
31
|
+
f"Image sizes differ: reference is {expected.shape[1]}x{expected.shape[0]}, "
|
|
32
|
+
f"rendered is {actual.shape[1]}x{actual.shape[0]}. Render at the target size first."
|
|
33
|
+
)
|
|
34
|
+
difference = np.abs(expected.astype(np.int16) - actual.astype(np.int16))
|
|
35
|
+
return float(difference.mean() / 255.0)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def error_map(reference: bytes, rendered: bytes) -> np.ndarray:
|
|
39
|
+
"""Per-pixel error in 0..1: mean absolute difference over the RGB channels.
|
|
40
|
+
|
|
41
|
+
Returns a float array of shape (height, width). Both images must have the same size.
|
|
42
|
+
"""
|
|
43
|
+
expected = load_rgb(reference)
|
|
44
|
+
actual = load_rgb(rendered)
|
|
45
|
+
if expected.shape != actual.shape:
|
|
46
|
+
raise ValueError(
|
|
47
|
+
f"Image sizes differ: reference is {expected.shape[1]}x{expected.shape[0]}, "
|
|
48
|
+
f"rendered is {actual.shape[1]}x{actual.shape[0]}. Render at the target size first."
|
|
49
|
+
)
|
|
50
|
+
difference = np.abs(expected.astype(np.int16) - actual.astype(np.int16))
|
|
51
|
+
return difference.mean(axis=2) / 255.0
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def worst_regions(
|
|
55
|
+
reference: bytes, rendered: bytes, count: int = 5, threshold: float = 0.1
|
|
56
|
+
) -> list[dict[str, float | int]]:
|
|
57
|
+
"""The `count` regions with the most total error, largest first.
|
|
58
|
+
|
|
59
|
+
A region is a connected group of pixels whose error is at least `threshold` (0..1).
|
|
60
|
+
Each entry has x, y, width, height (pixels, top-left origin), `pixels` (area),
|
|
61
|
+
`mean_error` and `total_error` (sum of the per-pixel error inside the region, 0..pixels).
|
|
62
|
+
Returns an empty list when nothing reaches the threshold.
|
|
63
|
+
"""
|
|
64
|
+
if count < 1:
|
|
65
|
+
raise ValueError("count must be at least 1.")
|
|
66
|
+
if not 0.0 <= threshold <= 1.0:
|
|
67
|
+
raise ValueError("threshold must be between 0 and 1.")
|
|
68
|
+
|
|
69
|
+
error = error_map(reference, rendered)
|
|
70
|
+
mask = error >= threshold
|
|
71
|
+
labels = measure.label(mask, connectivity=2)
|
|
72
|
+
|
|
73
|
+
regions: list[dict[str, float | int]] = []
|
|
74
|
+
for region in measure.regionprops(labels, intensity_image=error):
|
|
75
|
+
min_row, min_col, max_row, max_col = region.bbox
|
|
76
|
+
values = region.image_intensity[region.image]
|
|
77
|
+
regions.append(
|
|
78
|
+
{
|
|
79
|
+
"x": int(min_col),
|
|
80
|
+
"y": int(min_row),
|
|
81
|
+
"width": int(max_col - min_col),
|
|
82
|
+
"height": int(max_row - min_row),
|
|
83
|
+
"pixels": int(region.area),
|
|
84
|
+
"mean_error": float(values.mean()),
|
|
85
|
+
"total_error": float(values.sum()),
|
|
86
|
+
}
|
|
87
|
+
)
|
|
88
|
+
regions.sort(key=lambda item: item["total_error"], reverse=True)
|
|
89
|
+
return regions[:count]
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def diff_heatmap(reference: bytes, rendered: bytes) -> bytes:
|
|
93
|
+
"""PNG heat map of the error: black where the images match, through red, to yellow where they differ most.
|
|
94
|
+
|
|
95
|
+
The colour ramp is linear in the error, so the same colour always means the same difference.
|
|
96
|
+
"""
|
|
97
|
+
error = error_map(reference, rendered)
|
|
98
|
+
red = np.clip(error * 2.0, 0.0, 1.0)
|
|
99
|
+
green = np.clip(error * 2.0 - 1.0, 0.0, 1.0)
|
|
100
|
+
rgb = np.stack([red, green, np.zeros_like(error)], axis=2)
|
|
101
|
+
buffer = io.BytesIO()
|
|
102
|
+
Image.fromarray((rgb * 255).astype(np.uint8), mode="RGB").save(buffer, format="PNG")
|
|
103
|
+
return buffer.getvalue()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def fit_to_size(data: bytes, width: int, height: int) -> bytes:
|
|
107
|
+
"""Resize an image to width x height (Lanczos) and return it as PNG bytes.
|
|
108
|
+
|
|
109
|
+
Used to bring the mockup to the size of the render, so both can be compared pixel by pixel.
|
|
110
|
+
An image that already has that size is re-encoded unchanged in content.
|
|
111
|
+
"""
|
|
112
|
+
with Image.open(io.BytesIO(data)) as image:
|
|
113
|
+
resized = image.convert("RGB").resize((width, height), Image.Resampling.LANCZOS)
|
|
114
|
+
buffer = io.BytesIO()
|
|
115
|
+
resized.save(buffer, format="PNG")
|
|
116
|
+
return buffer.getvalue()
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def align_reference(reference: bytes, rendered: bytes) -> bytes:
|
|
120
|
+
"""Return the mockup at the render's size, so the two can be compared.
|
|
121
|
+
|
|
122
|
+
The render is what the UI produces at the target resolution, so it keeps its size and
|
|
123
|
+
the mockup is scaled to match it. Returns the mockup unchanged when the sizes already match.
|
|
124
|
+
"""
|
|
125
|
+
rendered_rgb = load_rgb(rendered)
|
|
126
|
+
height, width = rendered_rgb.shape[:2]
|
|
127
|
+
reference_rgb = load_rgb(reference)
|
|
128
|
+
if reference_rgb.shape[:2] == (height, width):
|
|
129
|
+
return reference
|
|
130
|
+
return fit_to_size(reference, width, height)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
# skimage's SSIM uses 7x7 windows by default and fails on smaller images.
|
|
134
|
+
MIN_SSIM_SIDE = 7
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def ssim_score(reference: bytes, rendered: bytes) -> float:
|
|
138
|
+
"""Structural similarity between two images of the same size, from -1 to 1 (1 = identical).
|
|
139
|
+
|
|
140
|
+
The raw SSIM can be negative for images that are anti-correlated; use ssim_unit for 0..1.
|
|
141
|
+
Both images must have the same width and height; aligning them is the caller's job.
|
|
142
|
+
Raises ValueError with an actionable message when the sizes differ or an image is smaller
|
|
143
|
+
than MIN_SSIM_SIDE pixels on either side.
|
|
144
|
+
"""
|
|
145
|
+
expected = load_rgb(reference)
|
|
146
|
+
actual = load_rgb(rendered)
|
|
147
|
+
if expected.shape != actual.shape:
|
|
148
|
+
raise ValueError(
|
|
149
|
+
f"Image sizes differ: reference is {expected.shape[1]}x{expected.shape[0]}, "
|
|
150
|
+
f"rendered is {actual.shape[1]}x{actual.shape[0]}. Render at the target size first."
|
|
151
|
+
)
|
|
152
|
+
height, width = expected.shape[:2]
|
|
153
|
+
if height < MIN_SSIM_SIDE or width < MIN_SSIM_SIDE:
|
|
154
|
+
raise ValueError(
|
|
155
|
+
f"Image is {width}x{height}px; SSIM needs at least {MIN_SSIM_SIDE}x{MIN_SSIM_SIDE}px. "
|
|
156
|
+
"Capture the UI at a larger size (pass width and height to capture_game_view)."
|
|
157
|
+
)
|
|
158
|
+
score = structural_similarity(expected, actual, channel_axis=2, data_range=255)
|
|
159
|
+
return float(score)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def ssim_unit(reference: bytes, rendered: bytes) -> float:
|
|
163
|
+
"""ssim_score clamped to 0..1: 1 = identical, 0 = no structural similarity or worse.
|
|
164
|
+
|
|
165
|
+
Negative SSIM values (anti-correlated images) are reported as 0, so the result never goes
|
|
166
|
+
below zero. The raw value is still available from ssim_score.
|
|
167
|
+
"""
|
|
168
|
+
return max(0.0, min(1.0, ssim_score(reference, rendered)))
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Crop a rectangle out of the target mockup (PNG or JPG) and encode it as PNG.
|
|
2
|
+
|
|
3
|
+
Pure functions over image bytes: no Unity and no files, so they run in CI and in tests.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import io
|
|
9
|
+
|
|
10
|
+
from PIL import Image
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def crop_png(data: bytes, x: int, y: int, width: int, height: int) -> bytes:
|
|
14
|
+
"""Return the rectangle [x, y, width, height] of the image as PNG bytes, keeping alpha.
|
|
15
|
+
|
|
16
|
+
Origin is top-left, in pixels of the source image. Raises ValueError when the rectangle is
|
|
17
|
+
empty or does not fit inside the image.
|
|
18
|
+
"""
|
|
19
|
+
if width < 1 or height < 1:
|
|
20
|
+
raise ValueError(f"The crop size must be at least 1x1, got {width}x{height}.")
|
|
21
|
+
if x < 0 or y < 0:
|
|
22
|
+
raise ValueError(f"The crop origin must be inside the image, got x={x}, y={y}.")
|
|
23
|
+
|
|
24
|
+
with Image.open(io.BytesIO(data)) as image:
|
|
25
|
+
source_width, source_height = image.size
|
|
26
|
+
if x + width > source_width or y + height > source_height:
|
|
27
|
+
raise ValueError(
|
|
28
|
+
f"The crop [{x}, {y}, {width}, {height}] does not fit the mockup ({source_width}x{source_height}). "
|
|
29
|
+
"Use a region inside the image, with x + width and y + height at most the image size."
|
|
30
|
+
)
|
|
31
|
+
cropped = image.convert("RGBA").crop((x, y, x + width, y + height))
|
|
32
|
+
|
|
33
|
+
out = io.BytesIO()
|
|
34
|
+
cropped.save(out, format="PNG")
|
|
35
|
+
return out.getvalue()
|
|
@@ -0,0 +1,865 @@
|
|
|
1
|
+
"""MCP tools that build and inspect uGUI layouts in the Unity Editor.
|
|
2
|
+
|
|
3
|
+
Each tool forwards to a command handled by the Editor bridge in Editor/UiAgentBridge.cs.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import base64
|
|
9
|
+
import json
|
|
10
|
+
import re
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Annotated, Any, Literal
|
|
13
|
+
|
|
14
|
+
from mcp.server.mcpserver import Image, MCPServer
|
|
15
|
+
from mcp.server.mcpserver.exceptions import ToolError
|
|
16
|
+
from pydantic import AliasGenerator, BaseModel, ConfigDict, Field, model_validator
|
|
17
|
+
from pydantic.alias_generators import to_camel
|
|
18
|
+
|
|
19
|
+
from . import __version__
|
|
20
|
+
from .compare import align_reference, diff_heatmap, pixel_diff, ssim_unit, worst_regions
|
|
21
|
+
from .crop import crop_png
|
|
22
|
+
from .unity_client import UnityClient, UnityError
|
|
23
|
+
|
|
24
|
+
# Stop criteria of the design loop. The agent reads them in INSTRUCTIONS.
|
|
25
|
+
SIMILARITY_THRESHOLD = 0.95 # compare_to_target ssim, 0..1; 1 = identical
|
|
26
|
+
MAX_ITERATIONS = 8 # capture-and-fix rounds before the agent stops and reports to the user
|
|
27
|
+
|
|
28
|
+
INSTRUCTIONS = f"""\
|
|
29
|
+
Tools to build and inspect Unity UI (uGUI) in the open Unity Editor.
|
|
30
|
+
|
|
31
|
+
Design loop: fix the target, build, compare, correct. Repeat until the UI resembles the mockup.
|
|
32
|
+
1. Fix the target: set_target_design with the absolute path of the mockup. The Canvas Scalers
|
|
33
|
+
adopt the mockup's resolution, and every later capture uses that size.
|
|
34
|
+
2. Build: unity_status to confirm the Editor is connected, get_hierarchy to see what already
|
|
35
|
+
exists, then build_ui_tree with the whole screen as one tree (containers with anchor presets,
|
|
36
|
+
then their content). Use create_ui_element for single additions. Prefer anchor presets and
|
|
37
|
+
layout groups over absolute positions so the UI adapts to other screen sizes.
|
|
38
|
+
3. Compare: compare_to_target with the same mockup path. It returns ssim (1 = identical) and
|
|
39
|
+
pixel_diff (0 = identical).
|
|
40
|
+
Stop when ssim >= {SIMILARITY_THRESHOLD} (the UI resembles the mockup), or when you have
|
|
41
|
+
made {MAX_ITERATIONS} correction rounds without reaching it. In the second case, stop and
|
|
42
|
+
report the last ssim and what is still different; do not keep trying.
|
|
43
|
+
4. Correct: diff_to_target lists the five regions with the most error and a heat map. Fix the
|
|
44
|
+
first region with update_ui_element, then go back to step 3. Use capture_game_view with
|
|
45
|
+
max_side and region to look at one part of a large screen without the whole image.
|
|
46
|
+
5. read_console after each round to catch compiler and runtime errors.
|
|
47
|
+
|
|
48
|
+
Coordinates follow Unity's RectTransform: anchoredPosition is relative to the anchors and the
|
|
49
|
+
pivot, sizes are in reference-resolution pixels of the Canvas Scaler, and +y points up.
|
|
50
|
+
Every change is registered with Undo, so the user can revert it with Ctrl+Z.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
ElementType = Literal[
|
|
54
|
+
"panel", "image", "text", "button", "empty",
|
|
55
|
+
"toggle", "slider", "inputfield", "dropdown", "scrollrect",
|
|
56
|
+
]
|
|
57
|
+
TextEngine = Literal["auto", "tmp", "legacy"]
|
|
58
|
+
AnchorPreset = Literal[
|
|
59
|
+
"center", "top", "bottom", "left", "right",
|
|
60
|
+
"top-left", "top-right", "bottom-left", "bottom-right",
|
|
61
|
+
"stretch", "stretch-top", "stretch-bottom", "stretch-left", "stretch-right",
|
|
62
|
+
"stretch-horizontal", "stretch-vertical",
|
|
63
|
+
]
|
|
64
|
+
Vec2 = Annotated[list[float], Field(min_length=2, max_length=2, description="[x, y]")]
|
|
65
|
+
Vec4 = Annotated[list[float], Field(min_length=4, max_length=4, description="[left, bottom, right, top]")]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class EffectOptions(BaseModel):
|
|
69
|
+
"""Options of an outline or shadow: the bridge gets them in camelCase."""
|
|
70
|
+
|
|
71
|
+
model_config = ConfigDict(
|
|
72
|
+
alias_generator=AliasGenerator(serialization_alias=to_camel),
|
|
73
|
+
extra="forbid",
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
color: str | None = Field(default=None, description="#RRGGBB or #RRGGBBAA. Default black.")
|
|
77
|
+
distance: Vec2 | None = Field(default=None, description="[x, y] offset in pixels. Shadow default [1, -1].")
|
|
78
|
+
use_graphic_alpha: bool | None = Field(default=None, description="Use the graphic's alpha for the effect. Default true.")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
Effect = EffectOptions | Literal[False]
|
|
82
|
+
|
|
83
|
+
ChildAlignment = Literal[
|
|
84
|
+
"upper-left", "upper-center", "upper-right",
|
|
85
|
+
"middle-left", "middle-center", "middle-right",
|
|
86
|
+
"lower-left", "lower-center", "lower-right",
|
|
87
|
+
]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class LayoutOptions(BaseModel):
|
|
91
|
+
"""A layout group (vertical, horizontal or grid) or a ContentSizeFitter (sizeFit): camelCase for the bridge."""
|
|
92
|
+
|
|
93
|
+
model_config = ConfigDict(
|
|
94
|
+
alias_generator=AliasGenerator(serialization_alias=to_camel),
|
|
95
|
+
extra="forbid",
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
type: Literal["vertical", "horizontal", "grid", "none"] | None = Field(default=None, description="Group type: vertical, horizontal, grid, or none to remove the group. Omit it to keep the object's current group: the other keys then change that group, and without a group only size_fit applies. Group keys on an object with no group are an error.")
|
|
99
|
+
spacing: float | None = Field(default=None, ge=0, description="Gap between children in pixels, for every group type (grid uses it on both axes). 0 or more.")
|
|
100
|
+
padding: Annotated[list[float], Field(min_length=4, max_length=4)] | None = Field(default=None, description="[left, right, top, bottom] in pixels.")
|
|
101
|
+
size_fit: Literal["none", "horizontal", "vertical", "both"] | None = Field(default=None, description="Grow the object with its children (ContentSizeFitter). Ignored on a scroll rect's Content.")
|
|
102
|
+
child_alignment: ChildAlignment | None = Field(default=None, description="Where children sit inside the group.")
|
|
103
|
+
child_force_expand_width: bool | None = Field(default=None, description="vertical/horizontal: children take the extra width.")
|
|
104
|
+
child_force_expand_height: bool | None = Field(default=None, description="vertical/horizontal: children take the extra height.")
|
|
105
|
+
child_control_width: bool | None = Field(default=None, description="vertical/horizontal: the group sets each child's width.")
|
|
106
|
+
child_control_height: bool | None = Field(default=None, description="vertical/horizontal: the group sets each child's height.")
|
|
107
|
+
cell_size: Vec2 | None = Field(default=None, description="grid only: [width, height] of each cell, both positive.")
|
|
108
|
+
columns: int | None = Field(default=None, ge=1, description="grid only: fixed number of columns.")
|
|
109
|
+
|
|
110
|
+
@model_validator(mode="after")
|
|
111
|
+
def _check_cell_size(self) -> LayoutOptions:
|
|
112
|
+
if self.cell_size is not None and (self.cell_size[0] <= 0 or self.cell_size[1] <= 0):
|
|
113
|
+
raise ValueError("cell_size must be two positive numbers.")
|
|
114
|
+
return self
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class LayoutElementOptions(BaseModel):
|
|
118
|
+
"""A LayoutElement on one element: sizes in pixels (0 or more) and the ignoreLayout flag."""
|
|
119
|
+
|
|
120
|
+
model_config = ConfigDict(
|
|
121
|
+
alias_generator=AliasGenerator(serialization_alias=to_camel),
|
|
122
|
+
extra="forbid",
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
min_width: float | None = Field(default=None, ge=0, description="Smallest width the layout gives the element.")
|
|
126
|
+
min_height: float | None = Field(default=None, ge=0, description="Smallest height the layout gives the element.")
|
|
127
|
+
preferred_width: float | None = Field(default=None, ge=0, description="Width the layout tries to give the element.")
|
|
128
|
+
preferred_height: float | None = Field(default=None, ge=0, description="Height the layout tries to give the element.")
|
|
129
|
+
flexible_width: float | None = Field(default=None, ge=0, description="Share of spare width the element takes.")
|
|
130
|
+
flexible_height: float | None = Field(default=None, ge=0, description="Share of spare height the element takes.")
|
|
131
|
+
ignore_layout: bool | None = Field(default=None, description="The parent layout group ignores this element.")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
AspectMode = Literal["none", "width-controls-height", "height-controls-width", "fit-in-parent", "envelope-parent"]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class AspectRatioOptions(BaseModel):
|
|
138
|
+
"""An AspectRatioFitter on one element: a mode and a width/height ratio above 0."""
|
|
139
|
+
|
|
140
|
+
model_config = ConfigDict(
|
|
141
|
+
alias_generator=AliasGenerator(serialization_alias=to_camel),
|
|
142
|
+
extra="forbid",
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
mode: AspectMode = Field(default="none", description="How the ratio is kept inside the parent.")
|
|
146
|
+
ratio: float | None = Field(default=None, gt=0, description="Width divided by height, above 0.")
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class UiNode(BaseModel):
|
|
150
|
+
"""One element of a build_ui_tree spec: the create_ui_element properties plus children."""
|
|
151
|
+
|
|
152
|
+
# Inputs and the schema stay snake_case like the other tools; the bridge receives camelCase.
|
|
153
|
+
model_config = ConfigDict(
|
|
154
|
+
alias_generator=AliasGenerator(serialization_alias=to_camel),
|
|
155
|
+
extra="forbid",
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
type: ElementType = Field(default="empty", description="panel/image = Image, text = Text, button = Image + Button + Text label, empty = RectTransform only, toggle, slider, inputfield, dropdown, scrollrect = interactive controls.")
|
|
159
|
+
name: str | None = Field(default=None, description="Descriptive, unique among siblings, e.g. 'PlayButton'.")
|
|
160
|
+
anchor_preset: AnchorPreset | None = None
|
|
161
|
+
anchored_position: Vec2 | None = None
|
|
162
|
+
size_delta: Vec2 | None = None
|
|
163
|
+
anchor_min: Vec2 | None = None
|
|
164
|
+
anchor_max: Vec2 | None = None
|
|
165
|
+
pivot: Vec2 | None = None
|
|
166
|
+
offset_min: Vec2 | None = None
|
|
167
|
+
offset_max: Vec2 | None = None
|
|
168
|
+
color: str | None = Field(default=None, description="#RRGGBB or #RRGGBBAA.")
|
|
169
|
+
sprite: str | None = Field(default=None, description="Sprite asset path, e.g. 'Assets/UI/button.png'.")
|
|
170
|
+
text: str | None = None
|
|
171
|
+
font_size: int | None = None
|
|
172
|
+
text_color: str | None = None
|
|
173
|
+
alignment: str | None = None
|
|
174
|
+
font_style: str | None = None
|
|
175
|
+
text_engine: TextEngine | None = Field(default=None, description="Only when creating a text element: tmp (TextMeshPro), legacy (uGUI Text) or auto (TMP if installed). Default auto.")
|
|
176
|
+
font: str | None = Field(default=None, description="Text font: a .ttf/.otf in Assets/ for legacy Text, or the '<name> SDF.asset' made by import_font for tmp.")
|
|
177
|
+
corner_radius: int | None = Field(default=None, ge=0, description="Rounded corners in pixels for panel, image or button. Not together with sprite.")
|
|
178
|
+
outline: Effect | None = Field(default=None, description='Outline {"color": "#000000", "distance": [2, -2]}, or false to remove it.')
|
|
179
|
+
shadow: Effect | None = Field(default=None, description='Shadow {"color": "#00000080", "distance": [2, -2]}, or false to remove it.')
|
|
180
|
+
preserve_aspect: bool | None = Field(default=None, description="Keep the sprite's proportions when the rect has another shape (images only).")
|
|
181
|
+
layout: LayoutOptions | None = Field(default=None, description="Layout group or sizeFit: type vertical/horizontal/grid/none, spacing, padding, size_fit, child_alignment, cell_size, columns.")
|
|
182
|
+
layout_element: LayoutElementOptions | Literal[False] | None = Field(default=None, description='LayoutElement on this element, e.g. {"min_width": 100, "flexible_width": 1}, or false to remove it.')
|
|
183
|
+
aspect_ratio_fitter: AspectRatioOptions | Literal[False] | None = Field(default=None, description='AspectRatioFitter, e.g. {"mode": "envelope-parent", "ratio": 1.5}, or false to remove it.')
|
|
184
|
+
rect_mask_2d: bool | None = Field(default=None, serialization_alias="rectMask2D", description="true adds a RectMask2D that clips children to this rect; false removes it.")
|
|
185
|
+
is_on: bool | None = Field(default=None, description="toggle only: initial on/off state.")
|
|
186
|
+
min_value: float | None = Field(default=None, description="slider only: minimum value.")
|
|
187
|
+
max_value: float | None = Field(default=None, description="slider only: maximum value.")
|
|
188
|
+
value: float | None = Field(default=None, description="slider only: initial value.")
|
|
189
|
+
whole_numbers: bool | None = Field(default=None, description="slider only: snap to whole numbers.")
|
|
190
|
+
placeholder: str | None = Field(default=None, description="inputfield only: hint shown while empty.")
|
|
191
|
+
character_limit: int | None = Field(default=None, ge=0, description="inputfield only: maximum characters, 0 for no limit.")
|
|
192
|
+
options: list[str] | None = Field(default=None, description="dropdown only: the option labels, in order.")
|
|
193
|
+
selected_index: int | None = Field(default=None, ge=0, description="dropdown only: index of the initially selected option.")
|
|
194
|
+
horizontal: bool | None = Field(default=None, description="scrollrect only: scroll horizontally.")
|
|
195
|
+
vertical: bool | None = Field(default=None, description="scrollrect only: scroll vertically.")
|
|
196
|
+
children: list[UiNode] = Field(default_factory=list, description="Content of a scrollrect goes here; for other types, child elements.")
|
|
197
|
+
|
|
198
|
+
@model_validator(mode="after")
|
|
199
|
+
def _check_control(self) -> UiNode:
|
|
200
|
+
_check_legacy_text_engine(self.type, self.text_engine)
|
|
201
|
+
return self
|
|
202
|
+
|
|
203
|
+
def to_bridge(self) -> dict[str, Any]:
|
|
204
|
+
return self.model_dump(by_alias=True, exclude_none=True)
|
|
205
|
+
|
|
206
|
+
server = MCPServer(
|
|
207
|
+
name="unity-ui-agent",
|
|
208
|
+
title="Unity UI Agent",
|
|
209
|
+
version=__version__,
|
|
210
|
+
instructions=INSTRUCTIONS,
|
|
211
|
+
)
|
|
212
|
+
unity = UnityClient()
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
async def _call(command: str, params: dict[str, Any] | None = None) -> Any:
|
|
216
|
+
try:
|
|
217
|
+
return await unity.call(command, params)
|
|
218
|
+
except UnityError as exc:
|
|
219
|
+
raise ToolError(str(exc)) from exc
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
LEGACY_TEXT_ONLY_TYPES = ("inputfield", "dropdown")
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _check_legacy_text_engine(element_type: str | None, text_engine: str | None) -> None:
|
|
226
|
+
"""Input fields and dropdowns use legacy Text; the bridge only accepts text_engine legacy or auto for them."""
|
|
227
|
+
if element_type in LEGACY_TEXT_ONLY_TYPES and text_engine == "tmp":
|
|
228
|
+
raise ValueError(f"type '{element_type}' supports text_engine 'legacy' or 'auto', not 'tmp'.")
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _ui_params(
|
|
232
|
+
*,
|
|
233
|
+
anchor_preset: str | None = None,
|
|
234
|
+
is_on: bool | None = None,
|
|
235
|
+
min_value: float | None = None,
|
|
236
|
+
max_value: float | None = None,
|
|
237
|
+
value: float | None = None,
|
|
238
|
+
whole_numbers: bool | None = None,
|
|
239
|
+
placeholder: str | None = None,
|
|
240
|
+
character_limit: int | None = None,
|
|
241
|
+
options: list[str] | None = None,
|
|
242
|
+
selected_index: int | None = None,
|
|
243
|
+
horizontal: bool | None = None,
|
|
244
|
+
vertical: bool | None = None,
|
|
245
|
+
anchored_position: list[float] | None = None,
|
|
246
|
+
size_delta: list[float] | None = None,
|
|
247
|
+
anchor_min: list[float] | None = None,
|
|
248
|
+
anchor_max: list[float] | None = None,
|
|
249
|
+
pivot: list[float] | None = None,
|
|
250
|
+
offset_min: list[float] | None = None,
|
|
251
|
+
offset_max: list[float] | None = None,
|
|
252
|
+
color: str | None = None,
|
|
253
|
+
sprite: str | None = None,
|
|
254
|
+
text: str | None = None,
|
|
255
|
+
font_size: int | None = None,
|
|
256
|
+
text_color: str | None = None,
|
|
257
|
+
alignment: str | None = None,
|
|
258
|
+
font_style: str | None = None,
|
|
259
|
+
layout: LayoutOptions | dict[str, Any] | None = None,
|
|
260
|
+
layout_element: LayoutElementOptions | Literal[False] | None = None,
|
|
261
|
+
aspect_ratio_fitter: AspectRatioOptions | Literal[False] | None = None,
|
|
262
|
+
rect_mask_2d: bool | None = None,
|
|
263
|
+
text_engine: str | None = None,
|
|
264
|
+
font: str | None = None,
|
|
265
|
+
corner_radius: int | None = None,
|
|
266
|
+
outline: EffectOptions | Literal[False] | None = None,
|
|
267
|
+
shadow: EffectOptions | Literal[False] | None = None,
|
|
268
|
+
preserve_aspect: bool | None = None,
|
|
269
|
+
) -> dict[str, Any]:
|
|
270
|
+
"""Map snake_case tool arguments to the camelCase names used by the Unity bridge."""
|
|
271
|
+
values = {
|
|
272
|
+
"anchorPreset": anchor_preset,
|
|
273
|
+
"anchoredPosition": anchored_position,
|
|
274
|
+
"sizeDelta": size_delta,
|
|
275
|
+
"anchorMin": anchor_min,
|
|
276
|
+
"anchorMax": anchor_max,
|
|
277
|
+
"pivot": pivot,
|
|
278
|
+
"offsetMin": offset_min,
|
|
279
|
+
"offsetMax": offset_max,
|
|
280
|
+
"color": color,
|
|
281
|
+
"sprite": sprite,
|
|
282
|
+
"text": text,
|
|
283
|
+
"fontSize": font_size,
|
|
284
|
+
"textColor": text_color,
|
|
285
|
+
"alignment": alignment,
|
|
286
|
+
"fontStyle": font_style,
|
|
287
|
+
"layout": _layout_params(layout),
|
|
288
|
+
"layoutElement": _component_params(layout_element),
|
|
289
|
+
"aspectRatioFitter": _component_params(aspect_ratio_fitter),
|
|
290
|
+
"rectMask2D": rect_mask_2d,
|
|
291
|
+
"textEngine": text_engine,
|
|
292
|
+
"font": font,
|
|
293
|
+
"cornerRadius": corner_radius,
|
|
294
|
+
"outline": _effect_params(outline),
|
|
295
|
+
"shadow": _effect_params(shadow),
|
|
296
|
+
"preserveAspect": preserve_aspect,
|
|
297
|
+
"isOn": is_on,
|
|
298
|
+
"minValue": min_value,
|
|
299
|
+
"maxValue": max_value,
|
|
300
|
+
"value": value,
|
|
301
|
+
"wholeNumbers": whole_numbers,
|
|
302
|
+
"placeholder": placeholder,
|
|
303
|
+
"characterLimit": character_limit,
|
|
304
|
+
"options": options,
|
|
305
|
+
"selectedIndex": selected_index,
|
|
306
|
+
"horizontal": horizontal,
|
|
307
|
+
"vertical": vertical,
|
|
308
|
+
}
|
|
309
|
+
return {key: item for key, item in values.items() if item is not None}
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _component_params(value: BaseModel | bool | None) -> dict[str, Any] | bool | None:
|
|
313
|
+
"""A per-element component in camelCase (only the options that were set), or False/None as given."""
|
|
314
|
+
if isinstance(value, BaseModel):
|
|
315
|
+
return value.model_dump(by_alias=True, exclude_none=True)
|
|
316
|
+
return value
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _layout_params(layout: LayoutOptions | dict[str, Any] | None) -> dict[str, Any] | None:
|
|
320
|
+
"""A layout in camelCase for the bridge: only the options that were set."""
|
|
321
|
+
if isinstance(layout, LayoutOptions):
|
|
322
|
+
return layout.model_dump(by_alias=True, exclude_none=True)
|
|
323
|
+
return layout
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _effect_params(effect: EffectOptions | Literal[False] | None) -> dict[str, Any] | bool | None:
|
|
327
|
+
"""An outline/shadow object in camelCase, or False to remove it, or None when unset."""
|
|
328
|
+
if isinstance(effect, EffectOptions):
|
|
329
|
+
return effect.model_dump(by_alias=True, exclude_none=True)
|
|
330
|
+
return effect
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
@server.tool()
|
|
334
|
+
async def unity_status() -> dict[str, Any]:
|
|
335
|
+
"""Check the connection to the Unity Editor: version, project, Play Mode and open prefab."""
|
|
336
|
+
return await _call("ping")
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
@server.tool()
|
|
340
|
+
async def get_hierarchy(
|
|
341
|
+
root: Annotated[str | None, Field(description="Path to start from, e.g. 'Canvas/MainMenu'. Omit for the whole scene (or the open prefab).")] = None,
|
|
342
|
+
max_depth: Annotated[int, Field(ge=0, le=32, description="How many levels of children to include.")] = 8,
|
|
343
|
+
include_inactive: Annotated[bool, Field(description="Include disabled GameObjects.")] = True,
|
|
344
|
+
) -> dict[str, Any]:
|
|
345
|
+
"""Return the scene hierarchy with UI details: paths, RectTransforms, colours, texts and components."""
|
|
346
|
+
return await _call(
|
|
347
|
+
"get_hierarchy",
|
|
348
|
+
{"root": root, "maxDepth": max_depth, "includeInactive": include_inactive},
|
|
349
|
+
)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
@server.tool()
|
|
353
|
+
async def create_ui_element(
|
|
354
|
+
type: Annotated[ElementType, Field(description="panel/image = Image, text = Text, button = Image + Button + Text label, empty = RectTransform only.")],
|
|
355
|
+
name: Annotated[str | None, Field(description="GameObject name. Use descriptive names such as 'PlayButton'.")] = None,
|
|
356
|
+
parent: Annotated[str | None, Field(description="Parent path. Omit to use the root Canvas (created with a Canvas Scaler and EventSystem if missing).")] = None,
|
|
357
|
+
anchor_preset: Annotated[AnchorPreset | None, Field(description="Sets anchors and pivot together.")] = None,
|
|
358
|
+
anchored_position: Vec2 | None = None,
|
|
359
|
+
size_delta: Annotated[Vec2 | None, Field(description="Width and height for non-stretched axes; for stretched axes it is the amount added to the parent size.")] = None,
|
|
360
|
+
anchor_min: Vec2 | None = None,
|
|
361
|
+
anchor_max: Vec2 | None = None,
|
|
362
|
+
pivot: Vec2 | None = None,
|
|
363
|
+
offset_min: Annotated[Vec2 | None, Field(description="Left/bottom margins when stretched.")] = None,
|
|
364
|
+
offset_max: Annotated[Vec2 | None, Field(description="Right/top margins when stretched (usually negative).")] = None,
|
|
365
|
+
color: Annotated[str | None, Field(description="#RRGGBB or #RRGGBBAA for the Image (or Text).")] = None,
|
|
366
|
+
sprite: Annotated[str | None, Field(description="Sprite asset path, e.g. 'Assets/UI/button.png'.")] = None,
|
|
367
|
+
text: str | None = None,
|
|
368
|
+
font_size: int | None = None,
|
|
369
|
+
text_color: Annotated[str | None, Field(description="#RRGGBB or #RRGGBBAA.")] = None,
|
|
370
|
+
alignment: Annotated[str | None, Field(description="upper-left, middle-center, lower-right, ...")] = None,
|
|
371
|
+
font_style: Annotated[str | None, Field(description="normal, bold, italic or bold-and-italic.")] = None,
|
|
372
|
+
layout: Annotated[LayoutOptions | None, Field(description='Layout group or sizeFit, e.g. {"type": "vertical", "spacing": 24, "padding": [40, 40, 40, 40], "child_alignment": "upper-center"}.')] = None,
|
|
373
|
+
reference_resolution: Annotated[Vec2 | None, Field(description="Canvas Scaler reference resolution if a Canvas has to be created. Default [1080, 1920].")] = None,
|
|
374
|
+
text_engine: Annotated[TextEngine | None, Field(description="Text elements only, at creation: tmp (TextMeshPro), legacy (uGUI Text) or auto (TMP if installed). Default auto.")] = None,
|
|
375
|
+
font: Annotated[str | None, Field(description="Text only. A .ttf/.otf in Assets/ for legacy Text, or the '<name> SDF.asset' made by import_font for tmp.")] = None,
|
|
376
|
+
corner_radius: Annotated[int | None, Field(ge=0, description="Rounded corners in pixels for panel, image or button. Not together with sprite.")] = None,
|
|
377
|
+
outline: Annotated[EffectOptions | Literal[False] | None, Field(description='Outline {"color": "#000000", "distance": [2, -2]}, or false to remove it.')] = None,
|
|
378
|
+
shadow: Annotated[EffectOptions | Literal[False] | None, Field(description='Shadow {"color": "#00000080", "distance": [2, -2]}, or false to remove it.')] = None,
|
|
379
|
+
preserve_aspect: Annotated[bool | None, Field(description="Keep the sprite's proportions when the rect has another shape (images only).")] = None,
|
|
380
|
+
is_on: Annotated[bool | None, Field(description="toggle only: initial on/off state.")] = None,
|
|
381
|
+
min_value: Annotated[float | None, Field(description="slider only: minimum value.")] = None,
|
|
382
|
+
max_value: Annotated[float | None, Field(description="slider only: maximum value.")] = None,
|
|
383
|
+
value: Annotated[float | None, Field(description="slider only: initial value.")] = None,
|
|
384
|
+
whole_numbers: Annotated[bool | None, Field(description="slider only: snap to whole numbers.")] = None,
|
|
385
|
+
placeholder: Annotated[str | None, Field(description="inputfield only: hint shown while empty.")] = None,
|
|
386
|
+
character_limit: Annotated[int | None, Field(ge=0, description="inputfield only: maximum characters, 0 for no limit.")] = None,
|
|
387
|
+
options: Annotated[list[str] | None, Field(description="dropdown only: the option labels, in order.")] = None,
|
|
388
|
+
selected_index: Annotated[int | None, Field(ge=0, description="dropdown only: index of the initially selected option.")] = None,
|
|
389
|
+
horizontal: Annotated[bool | None, Field(description="scrollrect only: scroll horizontally.")] = None,
|
|
390
|
+
vertical: Annotated[bool | None, Field(description="scrollrect only: scroll vertically.")] = None,
|
|
391
|
+
layout_element: Annotated[LayoutElementOptions | Literal[False] | None, Field(description='LayoutElement, e.g. {"min_width": 100, "flexible_width": 1}, or false to remove it.')] = None,
|
|
392
|
+
aspect_ratio_fitter: Annotated[AspectRatioOptions | Literal[False] | None, Field(description='AspectRatioFitter, e.g. {"mode": "envelope-parent", "ratio": 1.5}, or false to remove it.')] = None,
|
|
393
|
+
rect_mask_2d: Annotated[bool | None, Field(description="true adds a RectMask2D that clips children to this element; false removes it.")] = None,
|
|
394
|
+
) -> dict[str, Any]:
|
|
395
|
+
"""Create a uGUI element and return its path and RectTransform.
|
|
396
|
+
|
|
397
|
+
Types: panel, image, text, button, empty (container), and the interactive controls toggle,
|
|
398
|
+
slider, inputfield, dropdown and scrollrect. A scrollrect's content goes in its Content child,
|
|
399
|
+
created by the Editor. For text, font_size, font_style, alignment and text_color apply to
|
|
400
|
+
TextMeshPro or legacy Text. Import a font with import_font first to get a TMP Font Asset.
|
|
401
|
+
An inputfield or a dropdown supports text_engine legacy or auto only.
|
|
402
|
+
"""
|
|
403
|
+
try:
|
|
404
|
+
_check_legacy_text_engine(type, text_engine)
|
|
405
|
+
except ValueError as exc:
|
|
406
|
+
raise ToolError(str(exc)) from exc
|
|
407
|
+
params = {"type": type, "name": name, "parent": parent, "referenceResolution": reference_resolution}
|
|
408
|
+
params = {key: value for key, value in params.items() if value is not None}
|
|
409
|
+
params.update(
|
|
410
|
+
_ui_params(
|
|
411
|
+
anchor_preset=anchor_preset, anchored_position=anchored_position, size_delta=size_delta,
|
|
412
|
+
anchor_min=anchor_min, anchor_max=anchor_max, pivot=pivot,
|
|
413
|
+
offset_min=offset_min, offset_max=offset_max, color=color, sprite=sprite,
|
|
414
|
+
text=text, font_size=font_size, text_color=text_color, alignment=alignment,
|
|
415
|
+
font_style=font_style, layout=layout, text_engine=text_engine, font=font,
|
|
416
|
+
corner_radius=corner_radius, outline=outline, shadow=shadow, preserve_aspect=preserve_aspect,
|
|
417
|
+
is_on=is_on, min_value=min_value, max_value=max_value, value=value,
|
|
418
|
+
whole_numbers=whole_numbers, placeholder=placeholder, character_limit=character_limit,
|
|
419
|
+
options=options, selected_index=selected_index, horizontal=horizontal, vertical=vertical,
|
|
420
|
+
layout_element=layout_element, aspect_ratio_fitter=aspect_ratio_fitter, rect_mask_2d=rect_mask_2d,
|
|
421
|
+
)
|
|
422
|
+
)
|
|
423
|
+
return await _call("create_ui_element", params)
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
@server.tool()
|
|
427
|
+
async def build_ui_tree(
|
|
428
|
+
root: Annotated[UiNode, Field(description="The element to create, with its descendants in 'children'.")],
|
|
429
|
+
parent: Annotated[str | None, Field(description="Parent path. Omit to use the root Canvas (created if missing) or, in Prefab Mode, the prefab root.")] = None,
|
|
430
|
+
reference_resolution: Annotated[Vec2 | None, Field(description="Canvas Scaler reference resolution if a Canvas has to be created. Default [1080, 1920].")] = None,
|
|
431
|
+
) -> dict[str, Any]:
|
|
432
|
+
"""Create a whole UI hierarchy in one call (up to 500 elements) as a single Undo step.
|
|
433
|
+
|
|
434
|
+
Prefer this over many create_ui_element calls when building a screen from a design. If any
|
|
435
|
+
element fails, nothing is created and the error names the failing node. Returns the paths
|
|
436
|
+
of all created elements, for later update_ui_element calls. Interactive controls: toggle
|
|
437
|
+
(is_on), slider (min_value, max_value, value, whole_numbers), inputfield (text, placeholder,
|
|
438
|
+
character_limit), dropdown (options, selected_index) and scrollrect (horizontal, vertical; its
|
|
439
|
+
children go into the Content).
|
|
440
|
+
"""
|
|
441
|
+
params: dict[str, Any] = {"root": root.to_bridge()}
|
|
442
|
+
if parent is not None:
|
|
443
|
+
params["parent"] = parent
|
|
444
|
+
if reference_resolution is not None:
|
|
445
|
+
params["referenceResolution"] = reference_resolution
|
|
446
|
+
return await _call("build_ui_tree", params)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
@server.tool()
|
|
450
|
+
async def update_ui_element(
|
|
451
|
+
path: Annotated[str, Field(description="Path of the GameObject to change, e.g. 'Canvas/MainMenu/PlayButton'.")],
|
|
452
|
+
new_name: str | None = None,
|
|
453
|
+
new_parent: Annotated[str | None, Field(description="Move the element under this parent path.")] = None,
|
|
454
|
+
active: bool | None = None,
|
|
455
|
+
sibling_index: Annotated[int | None, Field(description="Order among siblings; later siblings draw on top.")] = None,
|
|
456
|
+
anchor_preset: AnchorPreset | None = None,
|
|
457
|
+
anchored_position: Vec2 | None = None,
|
|
458
|
+
size_delta: Vec2 | None = None,
|
|
459
|
+
anchor_min: Vec2 | None = None,
|
|
460
|
+
anchor_max: Vec2 | None = None,
|
|
461
|
+
pivot: Vec2 | None = None,
|
|
462
|
+
offset_min: Vec2 | None = None,
|
|
463
|
+
offset_max: Vec2 | None = None,
|
|
464
|
+
color: str | None = None,
|
|
465
|
+
sprite: str | None = None,
|
|
466
|
+
text: str | None = None,
|
|
467
|
+
font_size: int | None = None,
|
|
468
|
+
text_color: str | None = None,
|
|
469
|
+
alignment: str | None = None,
|
|
470
|
+
font_style: str | None = None,
|
|
471
|
+
layout: Annotated[LayoutOptions | None, Field(description='Add or replace a layout group, or set size_fit; {"type": "none"} removes the group.')] = None,
|
|
472
|
+
font: Annotated[str | None, Field(description="Text only. A .ttf/.otf in Assets/ for legacy Text, or the '<name> SDF.asset' made by import_font for tmp.")] = None,
|
|
473
|
+
corner_radius: Annotated[int | None, Field(ge=0, description="Rounded corners in pixels for panel, image or button. Not together with sprite.")] = None,
|
|
474
|
+
outline: Annotated[EffectOptions | Literal[False] | None, Field(description='Outline {"color": "#000000", "distance": [2, -2]}, or false to remove it.')] = None,
|
|
475
|
+
shadow: Annotated[EffectOptions | Literal[False] | None, Field(description='Shadow {"color": "#00000080", "distance": [2, -2]}, or false to remove it.')] = None,
|
|
476
|
+
preserve_aspect: Annotated[bool | None, Field(description="Keep the sprite's proportions when the rect has another shape (images only).")] = None,
|
|
477
|
+
is_on: Annotated[bool | None, Field(description="toggle only: on/off state.")] = None,
|
|
478
|
+
min_value: Annotated[float | None, Field(description="slider only: minimum value.")] = None,
|
|
479
|
+
max_value: Annotated[float | None, Field(description="slider only: maximum value.")] = None,
|
|
480
|
+
value: Annotated[float | None, Field(description="slider only: current value.")] = None,
|
|
481
|
+
whole_numbers: Annotated[bool | None, Field(description="slider only: snap to whole numbers.")] = None,
|
|
482
|
+
placeholder: Annotated[str | None, Field(description="inputfield only: hint shown while empty.")] = None,
|
|
483
|
+
character_limit: Annotated[int | None, Field(ge=0, description="inputfield only: maximum characters, 0 for no limit.")] = None,
|
|
484
|
+
options: Annotated[list[str] | None, Field(description="dropdown only: replaces the option labels.")] = None,
|
|
485
|
+
selected_index: Annotated[int | None, Field(ge=0, description="dropdown only: index of the selected option.")] = None,
|
|
486
|
+
horizontal: Annotated[bool | None, Field(description="scrollrect only: scroll horizontally.")] = None,
|
|
487
|
+
vertical: Annotated[bool | None, Field(description="scrollrect only: scroll vertically.")] = None,
|
|
488
|
+
layout_element: Annotated[LayoutElementOptions | Literal[False] | None, Field(description='LayoutElement, e.g. {"min_width": 100, "flexible_width": 1}, or false to remove it.')] = None,
|
|
489
|
+
aspect_ratio_fitter: Annotated[AspectRatioOptions | Literal[False] | None, Field(description='AspectRatioFitter, e.g. {"mode": "envelope-parent", "ratio": 1.5}, or false to remove it.')] = None,
|
|
490
|
+
rect_mask_2d: Annotated[bool | None, Field(description="true adds a RectMask2D that clips children to this element; false removes it.")] = None,
|
|
491
|
+
) -> dict[str, Any]:
|
|
492
|
+
"""Change an existing element: RectTransform, colour, sprite, text, layout group, name, parent, active state
|
|
493
|
+
or the state of an interactive control (toggle on/off, slider value, input field placeholder and limit,
|
|
494
|
+
dropdown options and selection, scroll rect axes)."""
|
|
495
|
+
params = {
|
|
496
|
+
"path": path,
|
|
497
|
+
"name": new_name,
|
|
498
|
+
"parent": new_parent,
|
|
499
|
+
"active": active,
|
|
500
|
+
"siblingIndex": sibling_index,
|
|
501
|
+
}
|
|
502
|
+
params = {key: value for key, value in params.items() if value is not None}
|
|
503
|
+
params.update(
|
|
504
|
+
_ui_params(
|
|
505
|
+
anchor_preset=anchor_preset, anchored_position=anchored_position, size_delta=size_delta,
|
|
506
|
+
anchor_min=anchor_min, anchor_max=anchor_max, pivot=pivot,
|
|
507
|
+
offset_min=offset_min, offset_max=offset_max, color=color, sprite=sprite,
|
|
508
|
+
text=text, font_size=font_size, text_color=text_color, alignment=alignment,
|
|
509
|
+
font_style=font_style, layout=layout, font=font,
|
|
510
|
+
corner_radius=corner_radius, outline=outline, shadow=shadow, preserve_aspect=preserve_aspect,
|
|
511
|
+
is_on=is_on, min_value=min_value, max_value=max_value, value=value,
|
|
512
|
+
whole_numbers=whole_numbers, placeholder=placeholder, character_limit=character_limit,
|
|
513
|
+
options=options, selected_index=selected_index, horizontal=horizontal, vertical=vertical,
|
|
514
|
+
layout_element=layout_element, aspect_ratio_fitter=aspect_ratio_fitter, rect_mask_2d=rect_mask_2d,
|
|
515
|
+
)
|
|
516
|
+
)
|
|
517
|
+
return await _call("update_ui_element", params)
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
@server.tool()
|
|
521
|
+
async def delete_object(
|
|
522
|
+
path: Annotated[str, Field(description="Path of the GameObject to delete (with its children).")],
|
|
523
|
+
) -> dict[str, Any]:
|
|
524
|
+
"""Delete a GameObject. The user can restore it with Undo."""
|
|
525
|
+
return await _call("delete_object", {"path": path})
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
@server.tool()
|
|
529
|
+
async def set_component_property(
|
|
530
|
+
path: Annotated[str, Field(description="Path of the GameObject that holds the component, e.g. 'Canvas/MainMenu/PlayButton'.")],
|
|
531
|
+
component: Annotated[str, Field(description="Component type name, such as 'Image', 'Button' or 'Text'.")],
|
|
532
|
+
property: Annotated[str, Field(description="Unity serialized field name, such as 'm_Color', 'm_Interactable' or 'm_FontData.m_FontSize' (nested fields use dots).")],
|
|
533
|
+
value: Annotated[Any, Field(description="The new value as JSON: a number, bool, string, enum name or index, hex colour '#RRGGBB', [x, y], [x, y, z], [x, y, z, w], [x, y, width, height], an asset path under Assets/ for an object reference, or null to clear a reference.")],
|
|
534
|
+
) -> dict[str, Any]:
|
|
535
|
+
"""Set one serialized field of a component on a GameObject, in a single Undo step.
|
|
536
|
+
|
|
537
|
+
Use it for properties that have no dedicated tool, for example an Image's raycast target or a
|
|
538
|
+
Text's font size. The value is checked against the field type first; a wrong type changes nothing
|
|
539
|
+
and the error names the expected type. Returns the path, component and property that were set.
|
|
540
|
+
"""
|
|
541
|
+
# value stays in the request even when it is null: a null clears an object reference.
|
|
542
|
+
return await _call(
|
|
543
|
+
"set_component_property",
|
|
544
|
+
{"path": path, "component": component, "property": property, "value": value},
|
|
545
|
+
)
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
@server.tool()
|
|
549
|
+
async def save_as_prefab(
|
|
550
|
+
path: Annotated[str, Field(description="Path of the scene object to save as a prefab, e.g. 'Canvas/MainMenu'.")],
|
|
551
|
+
prefab_path: Annotated[str, Field(description="Project path of the new prefab, e.g. 'Assets/UI/MainMenu.prefab'. Its folder must already exist.")],
|
|
552
|
+
overwrite: Annotated[bool, Field(description="Replace a prefab that already exists at prefab_path.")] = False,
|
|
553
|
+
) -> dict[str, Any]:
|
|
554
|
+
"""Save a scene object as a prefab asset. The scene object stays as it is and is not linked to the prefab.
|
|
555
|
+
|
|
556
|
+
Returns the prefab path, the source path, how many children it has, and sceneObjectLinked=false.
|
|
557
|
+
Not undoable. Refuses while a prefab is open in Prefab Mode.
|
|
558
|
+
"""
|
|
559
|
+
return await _call(
|
|
560
|
+
"save_as_prefab",
|
|
561
|
+
{"path": path, "prefabPath": prefab_path, "overwrite": overwrite},
|
|
562
|
+
)
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
@server.tool()
|
|
566
|
+
async def save_scene(
|
|
567
|
+
path: Annotated[str | None, Field(description="Project path to save the active scene to, e.g. 'Assets/Scenes/Main.unity'. Omit to save the scene in place; a scene that was never saved needs a path.")] = None,
|
|
568
|
+
overwrite: Annotated[bool, Field(description="Replace a scene that already exists at path.")] = False,
|
|
569
|
+
) -> dict[str, Any]:
|
|
570
|
+
"""Save the active scene, or save it to a new path. Refuses while a prefab is open in Prefab Mode.
|
|
571
|
+
|
|
572
|
+
Returns the scene path and dirty (true if it still has unsaved changes).
|
|
573
|
+
"""
|
|
574
|
+
params: dict[str, Any] = {"overwrite": overwrite}
|
|
575
|
+
if path is not None:
|
|
576
|
+
params["path"] = path
|
|
577
|
+
return await _call("save_scene", params)
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
@server.tool()
|
|
581
|
+
async def set_target_design(
|
|
582
|
+
path: Annotated[str, Field(description="Path of the mockup image to reproduce (PNG or JPG), e.g. 'Assets/Design/menu.png'.")],
|
|
583
|
+
) -> dict[str, Any]:
|
|
584
|
+
"""Set the mockup the UI must match and its resolution. The Canvas Scalers are fitted to that size.
|
|
585
|
+
|
|
586
|
+
Returns the stored path, width, height and how many canvases were adjusted.
|
|
587
|
+
"""
|
|
588
|
+
return await _call("set_target_design", {"path": path})
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
@server.tool()
|
|
592
|
+
async def import_font(
|
|
593
|
+
path: Annotated[str, Field(description="Font file inside the project's Assets folder, .ttf or .otf, e.g. 'Assets/Fonts/Inter.ttf'. Copy the file into Assets first.")],
|
|
594
|
+
tmp_font_asset: Annotated[bool, Field(description="Also generate a TextMeshPro Font Asset next to the font (needed for textEngine tmp).")] = True,
|
|
595
|
+
replace: Annotated[bool, Field(description="Overwrite an existing TMP Font Asset generated for this font.")] = False,
|
|
596
|
+
) -> dict[str, Any]:
|
|
597
|
+
"""Import a font into the project and, by default, generate its TextMeshPro Font Asset.
|
|
598
|
+
|
|
599
|
+
Returns the font path, the TMP Font Asset path (null if not generated) and an optional note,
|
|
600
|
+
for example when TextMeshPro is not installed.
|
|
601
|
+
"""
|
|
602
|
+
return await _call("import_font", {"path": path, "tmpFontAsset": tmp_font_asset, "replace": replace})
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
@server.tool()
|
|
606
|
+
async def import_sprite(
|
|
607
|
+
path: Annotated[str, Field(description="PNG file inside the project's Assets folder, e.g. 'Assets/UI/panel.png'. Copy the file into Assets first.")],
|
|
608
|
+
border: Annotated[
|
|
609
|
+
Vec4 | None,
|
|
610
|
+
Field(description="Nine-slice borders in pixels: [left, bottom, right, top]. Omit to keep the sprite's current borders."),
|
|
611
|
+
] = None,
|
|
612
|
+
pixels_per_unit: Annotated[int, Field(ge=1, description="Sprite Pixels Per Unit.")] = 100,
|
|
613
|
+
) -> dict[str, Any]:
|
|
614
|
+
"""Import a PNG as a Sprite (Single mode), optionally as a nine-slice with the given borders.
|
|
615
|
+
|
|
616
|
+
Returns the sprite path, the borders applied, whether it is sliced (any border set), its
|
|
617
|
+
pixels per unit and its size in pixels. Use the path as the sprite argument of
|
|
618
|
+
create_ui_element or update_ui_element.
|
|
619
|
+
"""
|
|
620
|
+
params: dict[str, Any] = {"path": path, "pixelsPerUnit": pixels_per_unit}
|
|
621
|
+
if border is not None:
|
|
622
|
+
params["border"] = border
|
|
623
|
+
return await _call("import_sprite", params)
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
@server.tool()
|
|
627
|
+
async def compare_to_target(
|
|
628
|
+
reference_path: Annotated[str, Field(description="Absolute path of the mockup on disk (PNG or JPG), the same image given to set_target_design.")],
|
|
629
|
+
) -> dict[str, Any]:
|
|
630
|
+
"""Capture the UI at the target size and compare it with the mockup.
|
|
631
|
+
|
|
632
|
+
Returns ssim (structural similarity, 1 = identical, clamped to 0..1) and pixel_diff
|
|
633
|
+
(mean difference per channel, 0 = identical, 1 = opposite). The mockup is scaled to the
|
|
634
|
+
capture size when they differ. Use it after each change to see how close the UI is.
|
|
635
|
+
"""
|
|
636
|
+
reference, rendered, captured = await _capture_against_mockup(reference_path)
|
|
637
|
+
try:
|
|
638
|
+
ssim = ssim_unit(reference, rendered)
|
|
639
|
+
diff = pixel_diff(reference, rendered)
|
|
640
|
+
except ValueError as exc:
|
|
641
|
+
raise ToolError(str(exc)) from exc
|
|
642
|
+
return {
|
|
643
|
+
"ssim": ssim,
|
|
644
|
+
"pixel_diff": max(0.0, min(1.0, diff)),
|
|
645
|
+
"width": captured["width"],
|
|
646
|
+
"height": captured["height"],
|
|
647
|
+
"file": captured["file"],
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
@server.tool(structured_output=False)
|
|
652
|
+
async def diff_to_target(
|
|
653
|
+
reference_path: Annotated[str, Field(description="Absolute path of the mockup on disk (PNG or JPG), the same image given to set_target_design.")],
|
|
654
|
+
) -> list[Any]:
|
|
655
|
+
"""Capture the UI at the target size and show where it differs from the mockup.
|
|
656
|
+
|
|
657
|
+
Returns the five worst regions as JSON (x, y, width, height in pixels, plus pixels,
|
|
658
|
+
mean_error and total_error, each error 0..1) and a heat map image: black where the UI matches
|
|
659
|
+
the mockup, red to yellow where it differs most. Fix the regions listed first.
|
|
660
|
+
"""
|
|
661
|
+
reference, rendered, captured = await _capture_against_mockup(reference_path)
|
|
662
|
+
try:
|
|
663
|
+
heatmap = diff_heatmap(reference, rendered)
|
|
664
|
+
regions = worst_regions(reference, rendered, count=5)
|
|
665
|
+
except ValueError as exc:
|
|
666
|
+
raise ToolError(str(exc)) from exc
|
|
667
|
+
summary = json.dumps(
|
|
668
|
+
{
|
|
669
|
+
"width": captured["width"],
|
|
670
|
+
"height": captured["height"],
|
|
671
|
+
"file": captured["file"],
|
|
672
|
+
"regions": regions,
|
|
673
|
+
}
|
|
674
|
+
)
|
|
675
|
+
return [summary, Image(data=heatmap, format="png")]
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
async def _capture_against_mockup(reference_path: str) -> tuple[bytes, bytes, dict[str, Any]]:
|
|
679
|
+
"""Read the mockup, capture the UI and scale the mockup to the capture size.
|
|
680
|
+
|
|
681
|
+
Returns (reference PNG, rendered PNG, the capture_game_view result).
|
|
682
|
+
"""
|
|
683
|
+
try:
|
|
684
|
+
mockup = Path(reference_path).read_bytes()
|
|
685
|
+
except OSError as exc:
|
|
686
|
+
raise ToolError(f"Cannot read the mockup at '{reference_path}': {exc}. Pass an absolute path to the PNG or JPG.") from exc
|
|
687
|
+
|
|
688
|
+
captured = await _call("capture_game_view", {})
|
|
689
|
+
rendered = base64.b64decode(captured["pngBase64"])
|
|
690
|
+
return align_reference(mockup, rendered), rendered, captured
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
class RegionBox(BaseModel):
|
|
694
|
+
"""A crop rectangle in pixels, origin top-left."""
|
|
695
|
+
|
|
696
|
+
model_config = ConfigDict(extra="forbid")
|
|
697
|
+
|
|
698
|
+
x: int = Field(ge=0)
|
|
699
|
+
y: int = Field(ge=0)
|
|
700
|
+
width: int = Field(ge=1)
|
|
701
|
+
height: int = Field(ge=1)
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
CropRegion = Annotated[list[int], Field(min_length=4, max_length=4)] | RegionBox
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def _region_list(region: list[int] | RegionBox) -> list[int]:
|
|
708
|
+
"""The bridge takes [x, y, width, height]; accept the object form too."""
|
|
709
|
+
if isinstance(region, RegionBox):
|
|
710
|
+
return [region.x, region.y, region.width, region.height]
|
|
711
|
+
if isinstance(region, dict):
|
|
712
|
+
region = RegionBox.model_validate(region)
|
|
713
|
+
return [region.x, region.y, region.width, region.height]
|
|
714
|
+
x, y, width, height = region
|
|
715
|
+
return [x, y, width, height]
|
|
716
|
+
|
|
717
|
+
|
|
718
|
+
@server.tool()
|
|
719
|
+
async def crop_from_target(
|
|
720
|
+
reference_path: Annotated[str, Field(description="Absolute path of the mockup on disk (PNG or JPG), the same image given to set_target_design.")],
|
|
721
|
+
region: Annotated[CropRegion, Field(description="Rectangle to cut out, [x, y, width, height] or {x, y, width, height}, in pixels of the mockup, origin top-left.")],
|
|
722
|
+
output_path: Annotated[str, Field(description="Absolute path of the PNG to write inside the Unity project's Assets folder, e.g. 'D:/Game/Assets/UI/Crops/icon.png'. Its folder must exist.")],
|
|
723
|
+
pixels_per_unit: Annotated[int, Field(ge=1, description="Sprite Pixels Per Unit of the imported sprite.")] = 100,
|
|
724
|
+
border: Annotated[Vec4 | None, Field(description="Nine-slice borders in pixels: [left, bottom, right, top]. Omit for a plain sprite.")] = None,
|
|
725
|
+
) -> dict[str, Any]:
|
|
726
|
+
"""Cut a rectangle out of the mockup, save it under Assets/ and import it as a Sprite.
|
|
727
|
+
|
|
728
|
+
The region is in mockup pixels, not in the Unity capture. The file must be inside an
|
|
729
|
+
Assets folder; the Unity path (Assets/...) is derived from it and imported with import_sprite.
|
|
730
|
+
Returns the written file, its size, the Unity asset path and the import result. Use the
|
|
731
|
+
returned sprite path as the sprite argument of create_ui_element or build_ui_tree.
|
|
732
|
+
"""
|
|
733
|
+
asset_path = _assets_path_of(output_path)
|
|
734
|
+
try:
|
|
735
|
+
data = Path(reference_path).read_bytes()
|
|
736
|
+
except OSError as exc:
|
|
737
|
+
raise ToolError(f"Cannot read the mockup at '{reference_path}': {exc}. Pass an absolute path to the PNG or JPG.") from exc
|
|
738
|
+
|
|
739
|
+
x, y, width, height = _region_list(region)
|
|
740
|
+
try:
|
|
741
|
+
png = crop_png(data, x, y, width, height)
|
|
742
|
+
except ValueError as exc:
|
|
743
|
+
raise ToolError(str(exc)) from exc
|
|
744
|
+
|
|
745
|
+
try:
|
|
746
|
+
Path(output_path).write_bytes(png)
|
|
747
|
+
except OSError as exc:
|
|
748
|
+
raise ToolError(f"Cannot write the crop to '{output_path}': {exc}.") from exc
|
|
749
|
+
|
|
750
|
+
params: dict[str, Any] = {"path": asset_path, "pixelsPerUnit": pixels_per_unit}
|
|
751
|
+
if border is not None:
|
|
752
|
+
params["border"] = border
|
|
753
|
+
sprite = await _call("import_sprite", params)
|
|
754
|
+
return {"file": output_path, "assetPath": asset_path, "x": x, "y": y, "width": width, "height": height, "sprite": sprite}
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
def _assets_path_of(output_path: str) -> str:
|
|
758
|
+
"""Turn '.../MyGame/Assets/UI/icon.png' into 'Assets/UI/icon.png'. Raises ToolError otherwise."""
|
|
759
|
+
parts = [part for part in re.split(r"[\\/]+", output_path) if part]
|
|
760
|
+
if not parts or not parts[-1].lower().endswith(".png") or "Assets" not in parts[:-1]:
|
|
761
|
+
raise ToolError(
|
|
762
|
+
f"output_path '{output_path}' must be a .png inside the project's Assets folder, "
|
|
763
|
+
"e.g. 'D:/Game/Assets/UI/Crops/icon.png'."
|
|
764
|
+
)
|
|
765
|
+
index = len(parts) - 1 - parts[::-1].index("Assets")
|
|
766
|
+
return "/".join(["Assets", *parts[index + 1:]])
|
|
767
|
+
|
|
768
|
+
|
|
769
|
+
# structured_output=False: the result mixes text and an image, which has no JSON schema.
|
|
770
|
+
@server.tool(structured_output=False)
|
|
771
|
+
async def capture_game_view(
|
|
772
|
+
width: Annotated[int | None, Field(ge=16, le=4096, description="Defaults to the Canvas Scaler reference width.")] = None,
|
|
773
|
+
height: Annotated[int | None, Field(ge=16, le=4096, description="Defaults to the Canvas Scaler reference height.")] = None,
|
|
774
|
+
background: Annotated[str | None, Field(description="Colour behind the UI when the scene has no main camera, e.g. '#202020'.")] = None,
|
|
775
|
+
max_side: Annotated[int | None, Field(ge=16, le=4096, description="Shrink the longer side to this many pixels, keeping the aspect ratio. Use it to save tokens on large captures.")] = None,
|
|
776
|
+
region: Annotated[CropRegion | None, Field(description="Crop the capture to [x, y, width, height] or {x, y, width, height} in pixels of the (possibly shrunk) capture, origin top-left.")] = None,
|
|
777
|
+
) -> list[Any]:
|
|
778
|
+
"""Render the UI to a PNG (works in Edit Mode) so you can compare it with the target design.
|
|
779
|
+
|
|
780
|
+
Use max_side and region to look at a part of a large screen without sending the whole image.
|
|
781
|
+
The summary reports the size of the source render and of the returned image.
|
|
782
|
+
"""
|
|
783
|
+
params: dict[str, Any] = {"width": width, "height": height, "background": background, "maxSide": max_side}
|
|
784
|
+
if region is not None:
|
|
785
|
+
params["region"] = _region_list(region)
|
|
786
|
+
result = await _call("capture_game_view", {k: v for k, v in params.items() if v is not None})
|
|
787
|
+
png = base64.b64decode(result["pngBase64"])
|
|
788
|
+
summary = (
|
|
789
|
+
f"Captured {result['width']}x{result['height']} "
|
|
790
|
+
f"(source {result['sourceWidth']}x{result['sourceHeight']}); saved to {result['file']}"
|
|
791
|
+
)
|
|
792
|
+
return [summary, Image(data=png, format="png")]
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
SideSize = Annotated[int, Field(ge=16, le=4096)]
|
|
796
|
+
ResolutionPair = tuple[SideSize, SideSize]
|
|
797
|
+
Resolutions = Annotated[
|
|
798
|
+
list[ResolutionPair],
|
|
799
|
+
Field(min_length=1, max_length=8, description="1 to 8 [width, height] pairs, e.g. [[1920, 1080], [1280, 720]]. Each side 16 to 4096 pixels."),
|
|
800
|
+
]
|
|
801
|
+
|
|
802
|
+
|
|
803
|
+
@server.tool()
|
|
804
|
+
async def check_layout(
|
|
805
|
+
resolutions: Resolutions,
|
|
806
|
+
return_images: Annotated[bool, Field(description="Attach the PNG of each resolution. Off by default because the captures are large.")] = False,
|
|
807
|
+
) -> Any:
|
|
808
|
+
"""Check the UI at several screen sizes and report, per size, the elements that overlap a sibling,
|
|
809
|
+
extend past the screen edge ("outOfBounds") or lie fully off screen ("offScreen").
|
|
810
|
+
|
|
811
|
+
Read-only: it does not change the scene. Each entry also gives the file of the saved capture.
|
|
812
|
+
The "other" field of an overlap issue names the element it overlaps.
|
|
813
|
+
"""
|
|
814
|
+
params: dict[str, Any] = {"resolutions": [[w, h] for w, h in resolutions]}
|
|
815
|
+
checked = await _call("check_layout", params)
|
|
816
|
+
captured = await _call("capture_game_view", params)
|
|
817
|
+
checks = checked.get("checks", [])
|
|
818
|
+
captures = captured.get("captures", [])
|
|
819
|
+
if len(checks) != len(resolutions) or len(captures) != len(resolutions):
|
|
820
|
+
raise ToolError(
|
|
821
|
+
f"Expected {len(resolutions)} results, got {len(checks)} layout checks and {len(captures)} captures."
|
|
822
|
+
)
|
|
823
|
+
|
|
824
|
+
entries: list[dict[str, Any]] = []
|
|
825
|
+
images: list[Image] = []
|
|
826
|
+
for check, capture in zip(checks, captures, strict=True):
|
|
827
|
+
if (check["width"], check["height"]) != (capture["width"], capture["height"]):
|
|
828
|
+
raise ToolError("check_layout and capture_game_view disagree on a size; the scene may have changed between the two calls.")
|
|
829
|
+
entries.append(
|
|
830
|
+
{
|
|
831
|
+
"width": check["width"],
|
|
832
|
+
"height": check["height"],
|
|
833
|
+
"file": capture["file"],
|
|
834
|
+
"elements": check["elements"],
|
|
835
|
+
"issues": check["issues"],
|
|
836
|
+
}
|
|
837
|
+
)
|
|
838
|
+
if return_images:
|
|
839
|
+
images.append(Image(data=base64.b64decode(capture["pngBase64"]), format="png"))
|
|
840
|
+
|
|
841
|
+
report = {"resolutions": entries}
|
|
842
|
+
if return_images:
|
|
843
|
+
return [report, *images]
|
|
844
|
+
return report
|
|
845
|
+
|
|
846
|
+
|
|
847
|
+
@server.tool()
|
|
848
|
+
async def read_console(
|
|
849
|
+
count: Annotated[int, Field(ge=1, le=300)] = 50,
|
|
850
|
+
types: Annotated[list[Literal["error", "warning", "log"]] | None, Field(description="Filter by type; omit for all.")] = None,
|
|
851
|
+
clear: Annotated[bool, Field(description="Clear the buffer after reading.")] = False,
|
|
852
|
+
) -> dict[str, Any]:
|
|
853
|
+
"""Read recent Unity Console messages, including compiler errors."""
|
|
854
|
+
params: dict[str, Any] = {"count": count, "clear": clear}
|
|
855
|
+
if types:
|
|
856
|
+
params["types"] = types
|
|
857
|
+
return await _call("read_console", params)
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
def main() -> None:
|
|
861
|
+
server.run()
|
|
862
|
+
|
|
863
|
+
|
|
864
|
+
if __name__ == "__main__":
|
|
865
|
+
main()
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""HTTP client for the Unity Editor bridge (Editor/UiAgentBridge.cs)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import time
|
|
9
|
+
import urllib.error
|
|
10
|
+
import urllib.request
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
DEFAULT_PORT = 6400
|
|
14
|
+
|
|
15
|
+
# Unity stops the bridge during every domain reload (script compilation, entering Play Mode).
|
|
16
|
+
# Retrying for a short while hides that from the agent.
|
|
17
|
+
RETRY_SECONDS = 20.0
|
|
18
|
+
RETRY_INTERVAL = 0.5
|
|
19
|
+
REQUEST_TIMEOUT = 40.0
|
|
20
|
+
|
|
21
|
+
_RELOAD_HINT = "bridge stopped"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _never_reached_unity(exc: BaseException) -> bool:
|
|
25
|
+
"""True when the connection was refused, so the command certainly did not run.
|
|
26
|
+
|
|
27
|
+
That is what happens while Unity reloads the domain and the bridge is stopped, and it is
|
|
28
|
+
the only network failure that is safe to retry.
|
|
29
|
+
"""
|
|
30
|
+
reason = exc.reason if isinstance(exc, urllib.error.URLError) else exc
|
|
31
|
+
return isinstance(reason, ConnectionRefusedError)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class UnityError(Exception):
|
|
35
|
+
"""Raised when Unity is unreachable or a command fails inside the Editor."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class UnityClient:
|
|
39
|
+
def __init__(self, port: int | None = None, host: str = "127.0.0.1") -> None:
|
|
40
|
+
port = port or int(os.environ.get("UNITY_UI_AGENT_PORT", DEFAULT_PORT))
|
|
41
|
+
self.base_url = f"http://{host}:{port}"
|
|
42
|
+
|
|
43
|
+
async def call(self, command: str, params: dict[str, Any] | None = None) -> Any:
|
|
44
|
+
"""Run a command in the Editor and return its result, retrying while Unity reloads."""
|
|
45
|
+
return await asyncio.to_thread(self._call_with_retry, command, params or {})
|
|
46
|
+
|
|
47
|
+
def _call_with_retry(self, command: str, params: dict[str, Any]) -> Any:
|
|
48
|
+
deadline = time.monotonic() + RETRY_SECONDS
|
|
49
|
+
last_error = ""
|
|
50
|
+
|
|
51
|
+
while True:
|
|
52
|
+
try:
|
|
53
|
+
response = self._post(command, params)
|
|
54
|
+
except (urllib.error.URLError, ConnectionError, TimeoutError) as exc:
|
|
55
|
+
if not _never_reached_unity(exc):
|
|
56
|
+
# The request may already have run in the Editor (for example a timeout
|
|
57
|
+
# while waiting for the reply). Retrying could apply it twice.
|
|
58
|
+
raise UnityError(
|
|
59
|
+
f"The request to Unity failed after it was sent ({exc}); it may or may "
|
|
60
|
+
"not have been applied. Use get_hierarchy to check before retrying."
|
|
61
|
+
) from exc
|
|
62
|
+
last_error = (
|
|
63
|
+
f"Cannot reach the Unity Editor at {self.base_url} ({exc}). "
|
|
64
|
+
"Check that Unity is open with the Unity UI Agent package installed "
|
|
65
|
+
"(Window > UI Agent (MCP) shows the status)."
|
|
66
|
+
)
|
|
67
|
+
else:
|
|
68
|
+
if response.get("ok"):
|
|
69
|
+
return response.get("result")
|
|
70
|
+
|
|
71
|
+
error = str(response.get("error", "Unknown error"))
|
|
72
|
+
if _RELOAD_HINT not in error.lower():
|
|
73
|
+
raise UnityError(error)
|
|
74
|
+
last_error = error
|
|
75
|
+
|
|
76
|
+
if time.monotonic() >= deadline:
|
|
77
|
+
raise UnityError(last_error)
|
|
78
|
+
time.sleep(RETRY_INTERVAL)
|
|
79
|
+
|
|
80
|
+
def _post(self, command: str, params: dict[str, Any]) -> dict[str, Any]:
|
|
81
|
+
body = json.dumps({"command": command, "params": params}).encode("utf-8")
|
|
82
|
+
request = urllib.request.Request(
|
|
83
|
+
f"{self.base_url}/command",
|
|
84
|
+
data=body,
|
|
85
|
+
headers={"Content-Type": "application/json"},
|
|
86
|
+
method="POST",
|
|
87
|
+
)
|
|
88
|
+
with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT) as response:
|
|
89
|
+
return json.loads(response.read().decode("utf-8"))
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: unity-ui-agent-mcp
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: MCP server that lets AI agents build and inspect uGUI layouts in the Unity Editor.
|
|
5
|
+
Project-URL: Homepage, https://github.com/maguera93/unity-ui-agent-mcp
|
|
6
|
+
Project-URL: Repository, https://github.com/maguera93/unity-ui-agent-mcp
|
|
7
|
+
Project-URL: Issues, https://github.com/maguera93/unity-ui-agent-mcp/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/maguera93/unity-ui-agent-mcp/blob/master/CHANGELOG.md
|
|
9
|
+
Author-email: Marc Agüera Garcia <magueracoras@gmail.com>
|
|
10
|
+
License: MIT
|
|
11
|
+
Keywords: ai-agent,claude,mcp,ugui,ui,unity
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Topic :: Software Development :: Code Generators
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Requires-Dist: mcp<3,>=2.0
|
|
26
|
+
Requires-Dist: numpy>=2.2.6
|
|
27
|
+
Requires-Dist: pillow>=12.3.0
|
|
28
|
+
Requires-Dist: pydantic>=2
|
|
29
|
+
Requires-Dist: scikit-image>=0.25.2
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
# unity-ui-agent-mcp (Python MCP server)
|
|
33
|
+
|
|
34
|
+
MCP server that lets AI agents such as Claude Code build, inspect and visually check uGUI layouts in the Unity Editor. It talks to the Unity Editor bridge (the `com.marcaguera.unity-ui-agent` package) over HTTP on `127.0.0.1:6400`.
|
|
35
|
+
|
|
36
|
+
Requires [uv](https://docs.astral.sh/uv/) and the Unity package from the repository: https://github.com/maguera93/unity-ui-agent-mcp
|
|
37
|
+
|
|
38
|
+
## Run
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
uvx unity-ui-agent-mcp
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Register it in Claude Code:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
claude mcp add unity-ui-agent -- uvx unity-ui-agent-mcp
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Set `UNITY_UI_AGENT_PORT` if the Unity bridge does not use the default port 6400.
|
|
51
|
+
|
|
52
|
+
The full setup, the tool list and the design loop are in the [repository README](https://github.com/maguera93/unity-ui-agent-mcp#readme).
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
unity_ui_agent_mcp/__init__.py,sha256=IhouJJvkos9CkCzcb-E9dXSny3kIoAQpqV3QjXhoAKg,112
|
|
2
|
+
unity_ui_agent_mcp/compare.py,sha256=549xE1LdcIcN7nchL48sCiDyojaUg3kUrwnukt7cBrI,6969
|
|
3
|
+
unity_ui_agent_mcp/crop.py,sha256=bvZJfseMkxKAb4rYly5kxdsVaNmGfPPiFyDrcYWa_9w,1384
|
|
4
|
+
unity_ui_agent_mcp/server.py,sha256=OSz8QHJTGrvnvJ32DOay2iydG7aGf7jLerpneUciIAM,48342
|
|
5
|
+
unity_ui_agent_mcp/unity_client.py,sha256=CZJynLeOh2-YpbJOE6FPCfqzrjfmx_GZ3KQy66DKGrU,3570
|
|
6
|
+
unity_ui_agent_mcp-0.3.0.dist-info/METADATA,sha256=St3rRksyY807khjt4vfvPWgTiPwX11dcArGR1MRFb8k,2161
|
|
7
|
+
unity_ui_agent_mcp-0.3.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
unity_ui_agent_mcp-0.3.0.dist-info/entry_points.txt,sha256=oijJ84aXvCQCuHLgsW1QJznNtlxYnKb15VRACUi03uw,70
|
|
9
|
+
unity_ui_agent_mcp-0.3.0.dist-info/RECORD,,
|