-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy patheditor.py
More file actions
559 lines (481 loc) · 15.6 KB
/
Copy patheditor.py
File metadata and controls
559 lines (481 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
"""Editor CLI commands."""
import math
import sys
from typing import Any, Optional
import click
from cli.utils.config import get_config
from cli.utils.output import format_output, print_error, print_success, print_info
from cli.utils.connection import run_command, run_list_custom_tools, handle_unity_errors, UnityConnectionError
from cli.utils.suggestions import suggest_matches, format_suggestions
from cli.utils.parsers import parse_json_dict_or_exit
@click.group()
def editor():
"""Editor operations - play mode, console, tags, layers."""
pass
@editor.command("wait-compile")
@click.option(
"--timeout", "-t",
type=float,
default=30.0,
help="Max seconds to wait (default: 30, clamped to 1-120)."
)
@handle_unity_errors
def wait_compile(timeout: float):
"""Wait for Unity script compilation to finish.
Polls editor state until compilation and domain reload are complete.
Useful after modifying scripts to ensure changes are compiled before
entering play mode or performing other actions. Timeout values are
clamped to the inclusive range 1-120 seconds.
\b
Examples:
unity-mcp editor wait-compile
unity-mcp editor wait-compile --timeout 60
"""
config = get_config()
effective_timeout = max(1.0, min(timeout, 120.0))
# Ensure the transport timeout outlasts the compilation wait (add a small buffer).
transport_timeout = math.ceil(effective_timeout) + 10
result = run_command(
"manage_editor",
{"action": "wait_for_compilation", "timeout": effective_timeout},
config,
timeout=transport_timeout,
)
click.echo(format_output(result, config.format))
if result.get("success"):
waited = result.get("data", {}).get("waited_seconds", 0)
print_success(f"Compilation complete (waited {waited}s)")
else:
print_error(result.get("message", "Compilation wait timed out"))
sys.exit(1)
@editor.command("play")
@handle_unity_errors
def play():
"""Enter play mode."""
config = get_config()
result = run_command("manage_editor", {"action": "play"}, config)
click.echo(format_output(result, config.format))
if result.get("success"):
print_success("Entered play mode")
@editor.command("pause")
@handle_unity_errors
def pause():
"""Pause play mode."""
config = get_config()
result = run_command("manage_editor", {"action": "pause"}, config)
click.echo(format_output(result, config.format))
if result.get("success"):
print_success("Paused play mode")
@editor.command("stop")
@handle_unity_errors
def stop():
"""Stop play mode."""
config = get_config()
result = run_command("manage_editor", {"action": "stop"}, config)
click.echo(format_output(result, config.format))
if result.get("success"):
print_success("Stopped play mode")
@editor.command("console")
@click.option(
"--type", "-t",
"log_types",
multiple=True,
type=click.Choice(["error", "warning", "log", "all"]),
default=["error", "warning", "log"],
help="Message types to retrieve."
)
@click.option(
"--count", "-n",
default=10,
type=int,
help="Number of messages to retrieve."
)
@click.option(
"--filter", "-f",
"filter_text",
default=None,
help="Filter messages containing this text."
)
@click.option(
"--stacktrace", "-s",
is_flag=True,
help="Include stack traces."
)
@click.option(
"--clear",
is_flag=True,
help="Clear the console instead of reading."
)
@handle_unity_errors
def console(log_types: tuple, count: int, filter_text: Optional[str], stacktrace: bool, clear: bool):
"""Read or clear the Unity console.
\b
Examples:
unity-mcp editor console
unity-mcp editor console --type error --count 20
unity-mcp editor console --filter "NullReference" --stacktrace
unity-mcp editor console --clear
"""
config = get_config()
if clear:
result = run_command("read_console", {"action": "clear"}, config)
click.echo(format_output(result, config.format))
if result.get("success"):
print_success("Console cleared")
return
params: dict[str, Any] = {
"action": "get",
"types": list(log_types),
"count": count,
"include_stacktrace": stacktrace,
}
if filter_text:
params["filter_text"] = filter_text
result = run_command("read_console", params, config)
click.echo(format_output(result, config.format))
@editor.command("add-tag")
@click.argument("tag_name")
@handle_unity_errors
def add_tag(tag_name: str):
"""Add a new tag.
\b
Examples:
unity-mcp editor add-tag "Enemy"
unity-mcp editor add-tag "Collectible"
"""
config = get_config()
result = run_command(
"manage_editor", {"action": "add_tag", "tagName": tag_name}, config)
click.echo(format_output(result, config.format))
if result.get("success"):
print_success(f"Added tag: {tag_name}")
@editor.command("remove-tag")
@click.argument("tag_name")
@handle_unity_errors
def remove_tag(tag_name: str):
"""Remove a tag.
\b
Examples:
unity-mcp editor remove-tag "OldTag"
"""
config = get_config()
result = run_command(
"manage_editor", {"action": "remove_tag", "tagName": tag_name}, config)
click.echo(format_output(result, config.format))
if result.get("success"):
print_success(f"Removed tag: {tag_name}")
@editor.command("add-layer")
@click.argument("layer_name")
@handle_unity_errors
def add_layer(layer_name: str):
"""Add a new layer.
\b
Examples:
unity-mcp editor add-layer "Interactable"
"""
config = get_config()
result = run_command(
"manage_editor", {"action": "add_layer", "layerName": layer_name}, config)
click.echo(format_output(result, config.format))
if result.get("success"):
print_success(f"Added layer: {layer_name}")
@editor.command("remove-layer")
@click.argument("layer_name")
@handle_unity_errors
def remove_layer(layer_name: str):
"""Remove a layer.
\b
Examples:
unity-mcp editor remove-layer "OldLayer"
"""
config = get_config()
result = run_command(
"manage_editor", {"action": "remove_layer", "layerName": layer_name}, config)
click.echo(format_output(result, config.format))
if result.get("success"):
print_success(f"Removed layer: {layer_name}")
@editor.command("tool")
@click.argument("tool_name")
@handle_unity_errors
def set_tool(tool_name: str):
"""Set the active editor tool.
\b
Examples:
unity-mcp editor tool "Move"
unity-mcp editor tool "Rotate"
unity-mcp editor tool "Scale"
"""
config = get_config()
result = run_command(
"manage_editor", {"action": "set_active_tool", "toolName": tool_name}, config)
click.echo(format_output(result, config.format))
if result.get("success"):
print_success(f"Set active tool: {tool_name}")
@editor.command("deploy")
@handle_unity_errors
def deploy():
"""Deploy MCPForUnity package from configured source.
Copies the configured MCPForUnity source folder into the project's
installed package location. The source path must be set in the
MCP for Unity Advanced Settings first. Triggers recompilation.
\b
Examples:
unity-mcp editor deploy
"""
config = get_config()
result = run_command("manage_editor", {"action": "deploy_package"}, config)
click.echo(format_output(result, config.format))
if result.get("success"):
print_success("Package deployed")
@editor.command("restore")
@handle_unity_errors
def restore():
"""Restore MCPForUnity package from last backup.
Reverts the last deployment by restoring from backup.
\b
Examples:
unity-mcp editor restore
"""
config = get_config()
result = run_command("manage_editor", {"action": "restore_package"}, config)
click.echo(format_output(result, config.format))
if result.get("success"):
print_success("Package restored from backup")
@editor.command("undo")
@handle_unity_errors
def undo():
"""Undo the last editor action.
\b
Examples:
unity-mcp editor undo
"""
config = get_config()
result = run_command("manage_editor", {"action": "undo"}, config)
click.echo(format_output(result, config.format))
if result.get("success"):
print_success("Undo performed")
@editor.command("redo")
@handle_unity_errors
def redo():
"""Redo the last undone action.
\b
Examples:
unity-mcp editor redo
"""
config = get_config()
result = run_command("manage_editor", {"action": "redo"}, config)
click.echo(format_output(result, config.format))
if result.get("success"):
print_success("Redo performed")
@editor.command("menu")
@click.argument("menu_path")
@handle_unity_errors
def execute_menu(menu_path: str):
"""Execute a menu item.
\b
Examples:
unity-mcp editor menu "File/Save"
unity-mcp editor menu "Edit/Undo"
unity-mcp editor menu "GameObject/Create Empty"
"""
config = get_config()
result = run_command("execute_menu_item", {"menu_path": menu_path}, config)
click.echo(format_output(result, config.format))
if result.get("success"):
print_success(f"Executed: {menu_path}")
@editor.command("tests")
@click.option(
"--mode", "-m",
type=click.Choice(["EditMode", "PlayMode"]),
default="EditMode",
help="Test mode to run."
)
@click.option(
"--async", "async_mode",
is_flag=True,
help="Run asynchronously and return job ID for polling."
)
@click.option(
"--wait", "-w",
type=int,
default=None,
help="Wait up to N seconds for completion (default: no wait)."
)
@click.option(
"--details",
is_flag=True,
help="Include detailed results for all tests."
)
@click.option(
"--failed-only",
is_flag=True,
help="Include details for failed/skipped tests only."
)
@handle_unity_errors
def run_tests(mode: str, async_mode: bool, wait: Optional[int], details: bool, failed_only: bool):
"""Run Unity tests.
\b
Examples:
unity-mcp editor tests
unity-mcp editor tests --mode PlayMode
unity-mcp editor tests --async
unity-mcp editor tests --wait 60 --failed-only
"""
config = get_config()
params: dict[str, Any] = {"mode": mode}
if wait is not None:
params["wait_timeout"] = wait
if details:
params["include_details"] = True
if failed_only:
params["include_failed_tests"] = True
result = run_command("run_tests", params, config)
# For async mode, just show job ID
if async_mode and result.get("success"):
job_id = result.get("data", {}).get("job_id")
if job_id:
click.echo(f"Test job started: {job_id}")
print_info("Poll with: unity-mcp editor poll-test " + job_id)
return
click.echo(format_output(result, config.format))
@editor.command("poll-test")
@click.argument("job_id")
@click.option(
"--wait", "-w",
type=int,
default=30,
help="Wait up to N seconds for completion (default: 30)."
)
@click.option(
"--details",
is_flag=True,
help="Include detailed results for all tests."
)
@click.option(
"--failed-only",
is_flag=True,
help="Include details for failed/skipped tests only."
)
@handle_unity_errors
def poll_test(job_id: str, wait: int, details: bool, failed_only: bool):
"""Poll an async test job for status/results.
\b
Examples:
unity-mcp editor poll-test abc123
unity-mcp editor poll-test abc123 --wait 60
unity-mcp editor poll-test abc123 --failed-only
"""
config = get_config()
params: dict[str, Any] = {"job_id": job_id}
if wait:
params["wait_timeout"] = wait
if details:
params["include_details"] = True
if failed_only:
params["include_failed_tests"] = True
result = run_command("get_test_job", params, config)
click.echo(format_output(result, config.format))
if isinstance(result, dict) and result.get("success"):
data = result.get("data", {})
status = data.get("status", "unknown")
if status == "succeeded":
print_success("Tests completed successfully")
elif status == "failed":
summary = data.get("result", {}).get("summary", {})
failed = summary.get("failed", 0)
print_error(f"Tests failed: {failed} failures")
elif status == "running":
progress = data.get("progress", {})
completed = progress.get("completed", 0)
total = progress.get("total", 0)
print_info(f"Tests running: {completed}/{total}")
@editor.command("refresh")
@click.option(
"--mode",
type=click.Choice(["if_dirty", "force"]),
default="if_dirty",
help="Refresh mode."
)
@click.option(
"--scope",
type=click.Choice(["assets", "scripts", "all"]),
default="all",
help="What to refresh."
)
@click.option(
"--compile",
is_flag=True,
help="Request script compilation."
)
@click.option(
"--no-wait",
is_flag=True,
help="Don't wait for refresh to complete."
)
@handle_unity_errors
def refresh(mode: str, scope: str, compile: bool, no_wait: bool):
"""Force Unity to refresh assets/scripts.
\b
Examples:
unity-mcp editor refresh
unity-mcp editor refresh --mode force
unity-mcp editor refresh --compile
unity-mcp editor refresh --scope scripts --compile
"""
config = get_config()
params: dict[str, Any] = {
"mode": mode,
"scope": scope,
"wait_for_ready": not no_wait,
}
if compile:
params["compile"] = "request"
click.echo("Refreshing Unity...")
result = run_command("refresh_unity", params, config)
click.echo(format_output(result, config.format))
if result.get("success"):
print_success("Unity refreshed")
@editor.command("custom-tool")
@click.argument("tool_name")
@click.option(
"--params", "-p",
default="{}",
help="Tool parameters as JSON."
)
@handle_unity_errors
def custom_tool(tool_name: str, params: str):
"""Execute a custom Unity tool.
Custom tools are registered by Unity projects via the MCP plugin.
\b
Examples:
unity-mcp editor custom-tool "MyCustomTool"
unity-mcp editor custom-tool "BuildPipeline" --params '{"target": "Android"}'
"""
config = get_config()
params_dict = parse_json_dict_or_exit(params, "params")
result = run_command("execute_custom_tool", {
"tool_name": tool_name,
"parameters": params_dict,
}, config)
click.echo(format_output(result, config.format))
if result.get("success"):
print_success(f"Executed custom tool: {tool_name}")
else:
message = (result.get("message") or result.get("error") or "").lower()
if "not found" in message and "tool" in message:
try:
tools_result = run_list_custom_tools(config)
tools = tools_result.get("tools")
if tools is None:
data = tools_result.get("data", {})
tools = data.get("tools") if isinstance(data, dict) else None
names = [
t.get("name") for t in tools if isinstance(t, dict) and t.get("name")
] if isinstance(tools, list) else []
matches = suggest_matches(tool_name, names)
suggestion = format_suggestions(matches)
if suggestion:
print_info(suggestion)
print_info(f'Example: unity-mcp editor custom-tool "{matches[0]}"')
except UnityConnectionError:
pass