mcpforunityserver 9.3.0b20260129104751__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.
Files changed (103) hide show
  1. cli/__init__.py +3 -0
  2. cli/commands/__init__.py +3 -0
  3. cli/commands/animation.py +84 -0
  4. cli/commands/asset.py +280 -0
  5. cli/commands/audio.py +125 -0
  6. cli/commands/batch.py +171 -0
  7. cli/commands/code.py +182 -0
  8. cli/commands/component.py +190 -0
  9. cli/commands/editor.py +447 -0
  10. cli/commands/gameobject.py +487 -0
  11. cli/commands/instance.py +93 -0
  12. cli/commands/lighting.py +123 -0
  13. cli/commands/material.py +239 -0
  14. cli/commands/prefab.py +248 -0
  15. cli/commands/scene.py +231 -0
  16. cli/commands/script.py +222 -0
  17. cli/commands/shader.py +226 -0
  18. cli/commands/texture.py +540 -0
  19. cli/commands/tool.py +58 -0
  20. cli/commands/ui.py +258 -0
  21. cli/commands/vfx.py +421 -0
  22. cli/main.py +281 -0
  23. cli/utils/__init__.py +31 -0
  24. cli/utils/config.py +58 -0
  25. cli/utils/confirmation.py +37 -0
  26. cli/utils/connection.py +258 -0
  27. cli/utils/constants.py +23 -0
  28. cli/utils/output.py +195 -0
  29. cli/utils/parsers.py +112 -0
  30. cli/utils/suggestions.py +34 -0
  31. core/__init__.py +0 -0
  32. core/config.py +52 -0
  33. core/logging_decorator.py +37 -0
  34. core/telemetry.py +551 -0
  35. core/telemetry_decorator.py +164 -0
  36. main.py +713 -0
  37. mcpforunityserver-9.3.0b20260129104751.dist-info/METADATA +216 -0
  38. mcpforunityserver-9.3.0b20260129104751.dist-info/RECORD +103 -0
  39. mcpforunityserver-9.3.0b20260129104751.dist-info/WHEEL +5 -0
  40. mcpforunityserver-9.3.0b20260129104751.dist-info/entry_points.txt +3 -0
  41. mcpforunityserver-9.3.0b20260129104751.dist-info/licenses/LICENSE +21 -0
  42. mcpforunityserver-9.3.0b20260129104751.dist-info/top_level.txt +7 -0
  43. models/__init__.py +4 -0
  44. models/models.py +56 -0
  45. models/unity_response.py +47 -0
  46. services/__init__.py +0 -0
  47. services/custom_tool_service.py +499 -0
  48. services/registry/__init__.py +22 -0
  49. services/registry/resource_registry.py +53 -0
  50. services/registry/tool_registry.py +51 -0
  51. services/resources/__init__.py +86 -0
  52. services/resources/active_tool.py +47 -0
  53. services/resources/custom_tools.py +57 -0
  54. services/resources/editor_state.py +304 -0
  55. services/resources/gameobject.py +243 -0
  56. services/resources/layers.py +29 -0
  57. services/resources/menu_items.py +34 -0
  58. services/resources/prefab.py +191 -0
  59. services/resources/prefab_stage.py +39 -0
  60. services/resources/project_info.py +39 -0
  61. services/resources/selection.py +55 -0
  62. services/resources/tags.py +30 -0
  63. services/resources/tests.py +87 -0
  64. services/resources/unity_instances.py +122 -0
  65. services/resources/windows.py +47 -0
  66. services/state/external_changes_scanner.py +245 -0
  67. services/tools/__init__.py +83 -0
  68. services/tools/batch_execute.py +93 -0
  69. services/tools/debug_request_context.py +86 -0
  70. services/tools/execute_custom_tool.py +43 -0
  71. services/tools/execute_menu_item.py +32 -0
  72. services/tools/find_gameobjects.py +110 -0
  73. services/tools/find_in_file.py +181 -0
  74. services/tools/manage_asset.py +119 -0
  75. services/tools/manage_components.py +131 -0
  76. services/tools/manage_editor.py +64 -0
  77. services/tools/manage_gameobject.py +260 -0
  78. services/tools/manage_material.py +111 -0
  79. services/tools/manage_prefabs.py +174 -0
  80. services/tools/manage_scene.py +111 -0
  81. services/tools/manage_script.py +645 -0
  82. services/tools/manage_scriptable_object.py +87 -0
  83. services/tools/manage_shader.py +71 -0
  84. services/tools/manage_texture.py +581 -0
  85. services/tools/manage_vfx.py +120 -0
  86. services/tools/preflight.py +110 -0
  87. services/tools/read_console.py +151 -0
  88. services/tools/refresh_unity.py +153 -0
  89. services/tools/run_tests.py +317 -0
  90. services/tools/script_apply_edits.py +1006 -0
  91. services/tools/set_active_instance.py +117 -0
  92. services/tools/utils.py +348 -0
  93. transport/__init__.py +0 -0
  94. transport/legacy/port_discovery.py +329 -0
  95. transport/legacy/stdio_port_registry.py +65 -0
  96. transport/legacy/unity_connection.py +888 -0
  97. transport/models.py +63 -0
  98. transport/plugin_hub.py +585 -0
  99. transport/plugin_registry.py +126 -0
  100. transport/unity_instance_middleware.py +232 -0
  101. transport/unity_transport.py +63 -0
  102. utils/focus_nudge.py +589 -0
  103. utils/module_discovery.py +55 -0
main.py ADDED
@@ -0,0 +1,713 @@
1
+ from starlette.requests import Request
2
+ from transport.unity_instance_middleware import (
3
+ UnityInstanceMiddleware,
4
+ get_unity_instance_middleware
5
+ )
6
+ from transport.legacy.unity_connection import get_unity_connection_pool, UnityConnectionPool
7
+ from services.tools import register_all_tools
8
+ from core.telemetry import record_milestone, record_telemetry, MilestoneType, RecordType, get_package_version
9
+ from services.resources import register_all_resources
10
+ from transport.plugin_registry import PluginRegistry
11
+ from transport.plugin_hub import PluginHub
12
+ from services.custom_tool_service import (
13
+ CustomToolService,
14
+ resolve_project_id_for_unity_instance,
15
+ )
16
+ from core.config import config
17
+ from starlette.routing import WebSocketRoute
18
+ from starlette.responses import JSONResponse
19
+ import argparse
20
+ import asyncio
21
+ import logging
22
+ from contextlib import asynccontextmanager
23
+ import os
24
+ import threading
25
+ import time
26
+ from typing import AsyncIterator, Any
27
+ from urllib.parse import urlparse
28
+
29
+ # Workaround for environments where tool signature evaluation runs with a globals
30
+ # dict that does not include common `typing` names (e.g. when annotations are strings
31
+ # and evaluated via `eval()` during schema generation).
32
+ # Making these names available in builtins avoids `NameError: Annotated/Literal/... is not defined`.
33
+ try: # pragma: no cover - startup safety guard
34
+ import builtins
35
+ import typing as _typing
36
+
37
+ _typing_names = (
38
+ "Annotated",
39
+ "Literal",
40
+ "Any",
41
+ "Union",
42
+ "Optional",
43
+ "Dict",
44
+ "List",
45
+ "Tuple",
46
+ "Set",
47
+ "FrozenSet",
48
+ )
49
+ for _name in _typing_names:
50
+ if not hasattr(builtins, _name) and hasattr(_typing, _name):
51
+ # type: ignore[attr-defined]
52
+ setattr(builtins, _name, getattr(_typing, _name))
53
+ except Exception:
54
+ pass
55
+
56
+ from fastmcp import FastMCP
57
+ from logging.handlers import RotatingFileHandler
58
+
59
+
60
+ class WindowsSafeRotatingFileHandler(RotatingFileHandler):
61
+ """RotatingFileHandler that gracefully handles Windows file locking during rotation."""
62
+
63
+ def doRollover(self):
64
+ """Override to catch PermissionError on Windows when log file is locked."""
65
+ try:
66
+ super().doRollover()
67
+ except PermissionError:
68
+ # On Windows, another process may have the log file open.
69
+ # Skip rotation this time - we'll try again on the next rollover.
70
+ pass
71
+
72
+
73
+ # Configure logging using settings from config
74
+ logging.basicConfig(
75
+ level=getattr(logging, config.log_level),
76
+ format=config.log_format,
77
+ stream=None, # None -> defaults to sys.stderr; avoid stdout used by MCP stdio
78
+ force=True # Ensure our handler replaces any prior stdout handlers
79
+ )
80
+ logger = logging.getLogger("mcp-for-unity-server")
81
+
82
+ # Also write logs to a rotating file so logs are available when launched via stdio
83
+ try:
84
+ _log_dir = os.path.join(os.path.expanduser(
85
+ "~/Library/Application Support/UnityMCP"), "Logs")
86
+ os.makedirs(_log_dir, exist_ok=True)
87
+ _file_path = os.path.join(_log_dir, "unity_mcp_server.log")
88
+ _fh = WindowsSafeRotatingFileHandler(
89
+ _file_path, maxBytes=512*1024, backupCount=2, encoding="utf-8")
90
+ _fh.setFormatter(logging.Formatter(config.log_format))
91
+ _fh.setLevel(getattr(logging, config.log_level))
92
+ logger.addHandler(_fh)
93
+ logger.propagate = False # Prevent double logging to root logger
94
+ # Also route telemetry logger to the same rotating file and normal level
95
+ try:
96
+ tlog = logging.getLogger("unity-mcp-telemetry")
97
+ tlog.setLevel(getattr(logging, config.log_level))
98
+ tlog.addHandler(_fh)
99
+ tlog.propagate = False # Prevent double logging for telemetry too
100
+ except Exception as exc:
101
+ # Never let logging setup break startup
102
+ logger.debug("Failed to configure telemetry logger", exc_info=exc)
103
+ except Exception as exc:
104
+ # Never let logging setup break startup
105
+ logger.debug("Failed to configure main logger file handler", exc_info=exc)
106
+ # Quieten noisy third-party loggers to avoid clutter during stdio handshake
107
+ for noisy in ("httpx", "urllib3", "mcp.server.lowlevel.server"):
108
+ try:
109
+ logging.getLogger(noisy).setLevel(
110
+ max(logging.WARNING, getattr(logging, config.log_level)))
111
+ logging.getLogger(noisy).propagate = False
112
+ except Exception:
113
+ pass
114
+
115
+ # Import telemetry only after logging is configured to ensure its logs use stderr and proper levels
116
+ # Ensure a slightly higher telemetry timeout unless explicitly overridden by env
117
+ try:
118
+
119
+ # Ensure generous timeout unless explicitly overridden by env
120
+ if not os.environ.get("UNITY_MCP_TELEMETRY_TIMEOUT"):
121
+ os.environ["UNITY_MCP_TELEMETRY_TIMEOUT"] = "5.0"
122
+ except Exception:
123
+ pass
124
+
125
+ # Global connection pool
126
+ _unity_connection_pool: UnityConnectionPool | None = None
127
+ _plugin_registry: PluginRegistry | None = None
128
+
129
+ # Cached server version (set at startup to avoid repeated I/O)
130
+ _server_version: str | None = None
131
+
132
+ # In-memory custom tool service initialized after MCP construction
133
+ custom_tool_service: CustomToolService | None = None
134
+
135
+
136
+ @asynccontextmanager
137
+ async def server_lifespan(server: FastMCP) -> AsyncIterator[dict[str, Any]]:
138
+ """Handle server startup and shutdown."""
139
+ global _unity_connection_pool, _server_version
140
+ _server_version = get_package_version()
141
+ logger.info(f"MCP for Unity Server v{_server_version} starting up")
142
+
143
+ # Register custom tool management endpoints with FastMCP
144
+ # Routes are declared globally below after FastMCP initialization
145
+
146
+ # Note: When using HTTP transport, FastMCP handles the HTTP server
147
+ # Tool registration will be handled through FastMCP endpoints
148
+ enable_http_server = os.environ.get(
149
+ "UNITY_MCP_ENABLE_HTTP_SERVER", "").lower() in ("1", "true", "yes", "on")
150
+ if enable_http_server:
151
+ http_host = os.environ.get("UNITY_MCP_HTTP_HOST", "localhost")
152
+ http_port = int(os.environ.get("UNITY_MCP_HTTP_PORT", "8080"))
153
+ logger.info(
154
+ f"HTTP tool registry will be available on http://{http_host}:{http_port}")
155
+
156
+ global _plugin_registry
157
+ if _plugin_registry is None:
158
+ _plugin_registry = PluginRegistry()
159
+ loop = asyncio.get_running_loop()
160
+ PluginHub.configure(_plugin_registry, loop)
161
+
162
+ # Record server startup telemetry
163
+ start_time = time.time()
164
+ start_clk = time.perf_counter()
165
+ # Defer initial telemetry by 1s to avoid stdio handshake interference
166
+
167
+ def _emit_startup():
168
+ try:
169
+ record_telemetry(RecordType.STARTUP, {
170
+ "server_version": _server_version,
171
+ "startup_time": start_time,
172
+ })
173
+ record_milestone(MilestoneType.FIRST_STARTUP)
174
+ except Exception:
175
+ logger.debug("Deferred startup telemetry failed", exc_info=True)
176
+ threading.Timer(1.0, _emit_startup).start()
177
+
178
+ try:
179
+ skip_connect = os.environ.get(
180
+ "UNITY_MCP_SKIP_STARTUP_CONNECT", "").lower() in ("1", "true", "yes", "on")
181
+ if skip_connect:
182
+ logger.info(
183
+ "Skipping Unity connection on startup (UNITY_MCP_SKIP_STARTUP_CONNECT=1)")
184
+ else:
185
+ # Initialize connection pool and discover instances
186
+ _unity_connection_pool = get_unity_connection_pool()
187
+ instances = _unity_connection_pool.discover_all_instances()
188
+
189
+ if instances:
190
+ logger.info(
191
+ f"Discovered {len(instances)} Unity instance(s): {[i.id for i in instances]}")
192
+
193
+ # Try to connect to default instance
194
+ try:
195
+ _unity_connection_pool.get_connection()
196
+ logger.info(
197
+ "Connected to default Unity instance on startup")
198
+
199
+ # Record successful Unity connection (deferred)
200
+ threading.Timer(1.0, lambda: record_telemetry(
201
+ RecordType.UNITY_CONNECTION,
202
+ {
203
+ "status": "connected",
204
+ "connection_time_ms": (time.perf_counter() - start_clk) * 1000,
205
+ "instance_count": len(instances)
206
+ }
207
+ )).start()
208
+ except Exception as e:
209
+ logger.warning(
210
+ f"Could not connect to default Unity instance: {e}")
211
+ else:
212
+ logger.warning("No Unity instances found on startup")
213
+
214
+ except ConnectionError as e:
215
+ logger.warning(f"Could not connect to Unity on startup: {e}")
216
+
217
+ # Record connection failure (deferred)
218
+ _err_msg = str(e)[:200]
219
+ threading.Timer(1.0, lambda: record_telemetry(
220
+ RecordType.UNITY_CONNECTION,
221
+ {
222
+ "status": "failed",
223
+ "error": _err_msg,
224
+ "connection_time_ms": (time.perf_counter() - start_clk) * 1000,
225
+ }
226
+ )).start()
227
+ except Exception as e:
228
+ logger.warning(f"Unexpected error connecting to Unity on startup: {e}")
229
+ _err_msg = str(e)[:200]
230
+ threading.Timer(1.0, lambda: record_telemetry(
231
+ RecordType.UNITY_CONNECTION,
232
+ {
233
+ "status": "failed",
234
+ "error": _err_msg,
235
+ "connection_time_ms": (time.perf_counter() - start_clk) * 1000,
236
+ }
237
+ )).start()
238
+
239
+ try:
240
+ # Yield shared state for lifespan consumers (e.g., middleware)
241
+ yield {
242
+ "pool": _unity_connection_pool,
243
+ "plugin_registry": _plugin_registry,
244
+ }
245
+ finally:
246
+ if _unity_connection_pool:
247
+ _unity_connection_pool.disconnect_all()
248
+ logger.info("MCP for Unity Server shut down")
249
+
250
+
251
+ def _build_instructions(project_scoped_tools: bool) -> str:
252
+ if project_scoped_tools:
253
+ custom_tools_note = (
254
+ "I have a dynamic tool system. Always check the mcpforunity://custom-tools resource first "
255
+ "to see what special capabilities are available for the current project."
256
+ )
257
+ else:
258
+ custom_tools_note = (
259
+ "Custom tools are registered as standard tools when Unity connects. "
260
+ "No project-scoped custom tools resource is available."
261
+ )
262
+
263
+ return f"""
264
+ This server provides tools to interact with the Unity Game Engine Editor.
265
+
266
+ {custom_tools_note}
267
+
268
+ Targeting Unity instances:
269
+ - Use the resource mcpforunity://instances to list active Unity sessions (Name@hash).
270
+ - When multiple instances are connected, call set_active_instance with the exact Name@hash before using tools/resources. The server will error if multiple are connected and no active instance is set.
271
+
272
+ Important Workflows:
273
+
274
+ Resources vs Tools:
275
+ - Use RESOURCES to read editor state (editor_state, project_info, project_tags, tests, etc)
276
+ - Use TOOLS to perform actions and mutations (manage_editor for play mode control, tag/layer management, etc)
277
+ - Always check related resources before modifying the engine state with tools
278
+
279
+ Script Management:
280
+ - After creating or modifying scripts (by your own tools or the `manage_script` tool) use `read_console` to check for compilation errors before proceeding
281
+ - Only after successful compilation can new components/types be used
282
+ - You can poll the `editor_state` resource's `isCompiling` field to check if the domain reload is complete
283
+
284
+ Scene Setup:
285
+ - Always include a Camera and main Light (Directional Light) in new scenes
286
+ - Create prefabs with `manage_asset` for reusable GameObjects
287
+ - Use `manage_scene` to load, save, and query scene information
288
+
289
+ Path Conventions:
290
+ - Unless specified otherwise, all paths are relative to the project's `Assets/` folder
291
+ - Use forward slashes (/) in paths for cross-platform compatibility
292
+
293
+ Console Monitoring:
294
+ - Check `read_console` regularly to catch errors, warnings, and compilation status
295
+ - Filter by log type (Error, Warning, Log) to focus on specific issues
296
+
297
+ Menu Items:
298
+ - Use `execute_menu_item` when you have read the menu items resource
299
+ - This lets you interact with Unity's menu system and third-party tools
300
+
301
+ Payload sizing & paging (important):
302
+ - Many Unity queries can return very large JSON. Prefer **paged + summary-first** calls.
303
+ - `manage_scene(action="get_hierarchy")`:
304
+ - Use `page_size` + `cursor` and follow `next_cursor` until null.
305
+ - `page_size` is **items per page**; recommended starting point: **50**.
306
+ - `manage_gameobject(action="get_components")`:
307
+ - Start with `include_properties=false` (metadata-only) and small `page_size` (e.g. **10-25**).
308
+ - Only request `include_properties=true` when needed; keep `page_size` small (e.g. **3-10**) to bound payloads.
309
+ - `manage_asset(action="search")`:
310
+ - Use paging (`page_size`, `page_number`) and keep `page_size` modest (e.g. **25-50**) to avoid token-heavy responses.
311
+ - Keep `generate_preview=false` unless you explicitly need thumbnails (previews may include large base64 payloads).
312
+ """
313
+
314
+
315
+ def create_mcp_server(project_scoped_tools: bool) -> FastMCP:
316
+ mcp = FastMCP(
317
+ name="mcp-for-unity-server",
318
+ lifespan=server_lifespan,
319
+ instructions=_build_instructions(project_scoped_tools),
320
+ )
321
+
322
+ global custom_tool_service
323
+ custom_tool_service = CustomToolService(
324
+ mcp, project_scoped_tools=project_scoped_tools)
325
+
326
+ @mcp.custom_route("/health", methods=["GET"])
327
+ async def health_http(_: Request) -> JSONResponse:
328
+ return JSONResponse({
329
+ "status": "healthy",
330
+ "timestamp": time.time(),
331
+ "version": _server_version or "unknown",
332
+ "message": "MCP for Unity server is running"
333
+ })
334
+
335
+ def _normalize_instance_token(instance_token: str | None) -> tuple[str | None, str | None]:
336
+ if not instance_token:
337
+ return None, None
338
+ if "@" in instance_token:
339
+ name_part, _, hash_part = instance_token.partition("@")
340
+ return (name_part or None), (hash_part or None)
341
+ return None, instance_token
342
+
343
+ @mcp.custom_route("/api/command", methods=["POST"])
344
+ async def cli_command_route(request: Request) -> JSONResponse:
345
+ """REST endpoint for CLI commands to Unity."""
346
+ try:
347
+ body = await request.json()
348
+
349
+ command_type = body.get("type")
350
+ params = body.get("params", {})
351
+ unity_instance = body.get("unity_instance")
352
+
353
+ if not command_type:
354
+ return JSONResponse({"success": False, "error": "Missing 'type' field"}, status_code=400)
355
+
356
+ # Get available sessions
357
+ sessions = await PluginHub.get_sessions()
358
+ if not sessions.sessions:
359
+ return JSONResponse({
360
+ "success": False,
361
+ "error": "No Unity instances connected. Make sure Unity is running with MCP plugin."
362
+ }, status_code=503)
363
+
364
+ # Find target session
365
+ session_id = None
366
+ session_details = None
367
+ instance_name, instance_hash = _normalize_instance_token(unity_instance)
368
+ if unity_instance:
369
+ # Try to match by hash or project name
370
+ for sid, details in sessions.sessions.items():
371
+ if details.hash == instance_hash or details.project in (instance_name, unity_instance):
372
+ session_id = sid
373
+ session_details = details
374
+ break
375
+
376
+ # If a specific unity_instance was requested but not found, return an error
377
+ if not session_id:
378
+ return JSONResponse(
379
+ {
380
+ "success": False,
381
+ "error": f"Unity instance '{unity_instance}' not found",
382
+ },
383
+ status_code=404,
384
+ )
385
+ else:
386
+ # No specific unity_instance requested: use first available session
387
+ session_id = next(iter(sessions.sessions.keys()))
388
+ session_details = sessions.sessions.get(session_id)
389
+
390
+ if command_type == "execute_custom_tool":
391
+ tool_name = None
392
+ tool_params = {}
393
+ if isinstance(params, dict):
394
+ tool_name = params.get("tool_name") or params.get("name")
395
+ tool_params = params.get("parameters") or params.get("params") or {}
396
+
397
+ if not tool_name:
398
+ return JSONResponse(
399
+ {"success": False, "error": "Missing 'tool_name' for execute_custom_tool"},
400
+ status_code=400,
401
+ )
402
+ if tool_params is None:
403
+ tool_params = {}
404
+ if not isinstance(tool_params, dict):
405
+ return JSONResponse(
406
+ {"success": False, "error": "Tool parameters must be an object/dict"},
407
+ status_code=400,
408
+ )
409
+
410
+ # Prefer a concrete hash for project-scoped tools.
411
+ unity_instance_hint = unity_instance
412
+ if session_details and session_details.hash:
413
+ unity_instance_hint = session_details.hash
414
+
415
+ project_id = resolve_project_id_for_unity_instance(
416
+ unity_instance_hint)
417
+ if not project_id:
418
+ return JSONResponse(
419
+ {"success": False, "error": "Could not resolve project id for custom tool"},
420
+ status_code=400,
421
+ )
422
+
423
+ service = CustomToolService.get_instance()
424
+ result = await service.execute_tool(
425
+ project_id, tool_name, unity_instance_hint, tool_params
426
+ )
427
+ return JSONResponse(result.model_dump())
428
+
429
+ # Send command to Unity
430
+ result = await PluginHub.send_command(session_id, command_type, params)
431
+ return JSONResponse(result)
432
+
433
+ except Exception as e:
434
+ logger.error(f"CLI command error: {e}")
435
+ return JSONResponse({"success": False, "error": str(e)}, status_code=500)
436
+
437
+ @mcp.custom_route("/api/custom-tools", methods=["GET"])
438
+ async def cli_custom_tools_route(request: Request) -> JSONResponse:
439
+ """REST endpoint to list custom tools for the active Unity project."""
440
+ try:
441
+ unity_instance = request.query_params.get("instance")
442
+ instance_name, instance_hash = _normalize_instance_token(unity_instance)
443
+
444
+ sessions = await PluginHub.get_sessions()
445
+ if not sessions.sessions:
446
+ return JSONResponse({
447
+ "success": False,
448
+ "error": "No Unity instances connected. Make sure Unity is running with MCP plugin."
449
+ }, status_code=503)
450
+
451
+ session_details = None
452
+ if unity_instance:
453
+ # Try to match by hash or project name
454
+ for _, details in sessions.sessions.items():
455
+ if details.hash == instance_hash or details.project in (instance_name, unity_instance):
456
+ session_details = details
457
+ break
458
+ if not session_details:
459
+ return JSONResponse(
460
+ {
461
+ "success": False,
462
+ "error": f"Unity instance '{unity_instance}' not found",
463
+ },
464
+ status_code=404,
465
+ )
466
+ else:
467
+ # No specific unity_instance requested: use first available session
468
+ session_details = next(iter(sessions.sessions.values()))
469
+
470
+ unity_instance_hint = unity_instance
471
+ if session_details and session_details.hash:
472
+ unity_instance_hint = session_details.hash
473
+
474
+ project_id = resolve_project_id_for_unity_instance(
475
+ unity_instance_hint)
476
+ if not project_id:
477
+ return JSONResponse(
478
+ {"success": False, "error": "Could not resolve project id for custom tools"},
479
+ status_code=400,
480
+ )
481
+
482
+ service = CustomToolService.get_instance()
483
+ tools = await service.list_registered_tools(project_id)
484
+ tools_payload = [
485
+ tool.model_dump() if hasattr(tool, "model_dump") else tool for tool in tools
486
+ ]
487
+
488
+ return JSONResponse({
489
+ "success": True,
490
+ "project_id": project_id,
491
+ "tool_count": len(tools_payload),
492
+ "tools": tools_payload,
493
+ })
494
+ except Exception as e:
495
+ logger.error(f"CLI custom tools error: {e}")
496
+ return JSONResponse({"success": False, "error": str(e)}, status_code=500)
497
+
498
+ @mcp.custom_route("/api/instances", methods=["GET"])
499
+ async def cli_instances_route(_: Request) -> JSONResponse:
500
+ """REST endpoint to list connected Unity instances."""
501
+ try:
502
+ sessions = await PluginHub.get_sessions()
503
+ instances = []
504
+ for session_id, details in sessions.sessions.items():
505
+ instances.append({
506
+ "session_id": session_id,
507
+ "project": details.project,
508
+ "hash": details.hash,
509
+ "unity_version": details.unity_version,
510
+ "connected_at": details.connected_at,
511
+ })
512
+ return JSONResponse({"success": True, "instances": instances})
513
+ except Exception as e:
514
+ return JSONResponse({"success": False, "error": str(e)}, status_code=500)
515
+
516
+ @mcp.custom_route("/plugin/sessions", methods=["GET"])
517
+ async def plugin_sessions_route(_: Request) -> JSONResponse:
518
+ data = await PluginHub.get_sessions()
519
+ return JSONResponse(data.model_dump())
520
+
521
+ # Initialize and register middleware for session-based Unity instance routing
522
+ # Using the singleton getter ensures we use the same instance everywhere
523
+ unity_middleware = get_unity_instance_middleware()
524
+ mcp.add_middleware(unity_middleware)
525
+ logger.info("Registered Unity instance middleware for session-based routing")
526
+
527
+ # Mount plugin websocket hub at /hub/plugin when HTTP transport is active
528
+ existing_routes = [
529
+ route for route in mcp._get_additional_http_routes()
530
+ if isinstance(route, WebSocketRoute) and route.path == "/hub/plugin"
531
+ ]
532
+ if not existing_routes:
533
+ mcp._additional_http_routes.append(
534
+ WebSocketRoute("/hub/plugin", PluginHub))
535
+
536
+ # Register all tools
537
+ register_all_tools(mcp, project_scoped_tools=project_scoped_tools)
538
+
539
+ # Register all resources
540
+ register_all_resources(mcp, project_scoped_tools=project_scoped_tools)
541
+
542
+ return mcp
543
+
544
+
545
+ def main():
546
+ """Entry point for uvx and console scripts."""
547
+ parser = argparse.ArgumentParser(
548
+ description="MCP for Unity Server",
549
+ formatter_class=argparse.RawDescriptionHelpFormatter,
550
+ epilog="""
551
+ Environment Variables:
552
+ UNITY_MCP_DEFAULT_INSTANCE Default Unity instance to target (project name, hash, or 'Name@hash')
553
+ UNITY_MCP_SKIP_STARTUP_CONNECT Skip initial Unity connection attempt (set to 1/true/yes/on)
554
+ UNITY_MCP_TELEMETRY_ENABLED Enable telemetry (set to 1/true/yes/on)
555
+ UNITY_MCP_TRANSPORT Transport protocol: stdio or http (default: stdio)
556
+ UNITY_MCP_HTTP_URL HTTP server URL (default: http://localhost:8080)
557
+ UNITY_MCP_HTTP_HOST HTTP server host (overrides URL host)
558
+ UNITY_MCP_HTTP_PORT HTTP server port (overrides URL port)
559
+
560
+ Examples:
561
+ # Use specific Unity project as default
562
+ python -m src.server --default-instance "MyProject"
563
+
564
+ # Start with HTTP transport
565
+ python -m src.server --transport http --http-url http://localhost:8080
566
+
567
+ # Start with stdio transport (default)
568
+ python -m src.server --transport stdio
569
+
570
+ # Use environment variable for transport
571
+ UNITY_MCP_TRANSPORT=http UNITY_MCP_HTTP_URL=http://localhost:9000 python -m src.server
572
+ """
573
+ )
574
+ parser.add_argument(
575
+ "--default-instance",
576
+ type=str,
577
+ metavar="INSTANCE",
578
+ help="Default Unity instance to target (project name, hash, or 'Name@hash'). "
579
+ "Overrides UNITY_MCP_DEFAULT_INSTANCE environment variable."
580
+ )
581
+ parser.add_argument(
582
+ "--transport",
583
+ type=str,
584
+ choices=["stdio", "http"],
585
+ default="stdio",
586
+ help="Transport protocol to use: stdio or http (default: stdio). "
587
+ "Overrides UNITY_MCP_TRANSPORT environment variable."
588
+ )
589
+ parser.add_argument(
590
+ "--http-url",
591
+ type=str,
592
+ default="http://localhost:8080",
593
+ metavar="URL",
594
+ help="HTTP server URL (default: http://localhost:8080). "
595
+ "Can also set via UNITY_MCP_HTTP_URL environment variable."
596
+ )
597
+ parser.add_argument(
598
+ "--http-host",
599
+ type=str,
600
+ default=None,
601
+ metavar="HOST",
602
+ help="HTTP server host (overrides URL host). "
603
+ "Overrides UNITY_MCP_HTTP_HOST environment variable."
604
+ )
605
+ parser.add_argument(
606
+ "--http-port",
607
+ type=int,
608
+ default=None,
609
+ metavar="PORT",
610
+ help="HTTP server port (overrides URL port). "
611
+ "Overrides UNITY_MCP_HTTP_PORT environment variable."
612
+ )
613
+ parser.add_argument(
614
+ "--unity-instance-token",
615
+ type=str,
616
+ default=None,
617
+ metavar="TOKEN",
618
+ help="Optional per-launch token set by Unity for deterministic lifecycle management. "
619
+ "Used by Unity to validate it is stopping the correct process."
620
+ )
621
+ parser.add_argument(
622
+ "--pidfile",
623
+ type=str,
624
+ default=None,
625
+ metavar="PATH",
626
+ help="Optional path where the server will write its PID on startup. "
627
+ "Used by Unity to stop the exact process it launched when running in a terminal."
628
+ )
629
+ parser.add_argument(
630
+ "--project-scoped-tools",
631
+ action="store_true",
632
+ help="Keep custom tools scoped to the active Unity project and enable the custom tools resource."
633
+ )
634
+
635
+ args = parser.parse_args()
636
+
637
+ # Set environment variables from command line args
638
+ if args.default_instance:
639
+ os.environ["UNITY_MCP_DEFAULT_INSTANCE"] = args.default_instance
640
+ logger.info(
641
+ f"Using default Unity instance from command-line: {args.default_instance}")
642
+
643
+ # Set transport mode
644
+ transport_mode = args.transport or os.environ.get(
645
+ "UNITY_MCP_TRANSPORT", "stdio")
646
+ os.environ["UNITY_MCP_TRANSPORT"] = transport_mode
647
+ logger.info(f"Transport mode: {transport_mode}")
648
+
649
+ http_url = os.environ.get("UNITY_MCP_HTTP_URL", args.http_url)
650
+ parsed_url = urlparse(http_url)
651
+
652
+ # Allow individual host/port to override URL components
653
+ http_host = args.http_host or os.environ.get(
654
+ "UNITY_MCP_HTTP_HOST") or parsed_url.hostname or "localhost"
655
+
656
+ # Safely parse optional environment port (may be None or non-numeric)
657
+ _env_port_str = os.environ.get("UNITY_MCP_HTTP_PORT")
658
+ try:
659
+ _env_port = int(_env_port_str) if _env_port_str is not None else None
660
+ except ValueError:
661
+ logger.warning(
662
+ "Invalid UNITY_MCP_HTTP_PORT value '%s', ignoring", _env_port_str)
663
+ _env_port = None
664
+
665
+ http_port = args.http_port or _env_port or parsed_url.port or 8080
666
+
667
+ os.environ["UNITY_MCP_HTTP_HOST"] = http_host
668
+ os.environ["UNITY_MCP_HTTP_PORT"] = str(http_port)
669
+
670
+ # Optional lifecycle handshake for Unity-managed terminal launches
671
+ if args.unity_instance_token:
672
+ os.environ["UNITY_MCP_INSTANCE_TOKEN"] = args.unity_instance_token
673
+ if args.pidfile:
674
+ try:
675
+ pid_dir = os.path.dirname(args.pidfile)
676
+ if pid_dir:
677
+ os.makedirs(pid_dir, exist_ok=True)
678
+ with open(args.pidfile, "w", encoding="ascii") as f:
679
+ f.write(str(os.getpid()))
680
+ except Exception as exc:
681
+ logger.warning(
682
+ "Failed to write pidfile '%s': %s", args.pidfile, exc)
683
+
684
+ if args.http_url != "http://localhost:8080":
685
+ logger.info(f"HTTP URL set to: {http_url}")
686
+ if args.http_host:
687
+ logger.info(f"HTTP host override: {http_host}")
688
+ if args.http_port:
689
+ logger.info(f"HTTP port override: {http_port}")
690
+
691
+ mcp = create_mcp_server(args.project_scoped_tools)
692
+
693
+ # Determine transport mode
694
+ if transport_mode == 'http':
695
+ # Use HTTP transport for FastMCP
696
+ transport = 'http'
697
+ # Use the parsed host and port from URL/args
698
+ http_url = os.environ.get("UNITY_MCP_HTTP_URL", args.http_url)
699
+ parsed_url = urlparse(http_url)
700
+ host = args.http_host or os.environ.get(
701
+ "UNITY_MCP_HTTP_HOST") or parsed_url.hostname or "localhost"
702
+ port = args.http_port or _env_port or parsed_url.port or 8080
703
+ logger.info(f"Starting FastMCP with HTTP transport on {host}:{port}")
704
+ mcp.run(transport=transport, host=host, port=port)
705
+ else:
706
+ # Use stdio transport for traditional MCP
707
+ logger.info("Starting FastMCP with stdio transport")
708
+ mcp.run(transport='stdio')
709
+
710
+
711
+ # Run the server
712
+ if __name__ == "__main__":
713
+ main()