CoplayDev/unity-mcp · critical · ConnectionError
Could not connect to Unity
Error message
Could not connect to Unity
What it means
Raised inside send_command (unity_connection.py:369). After capping the connect timeout to the remaining deadline (_cap_to_deadline), it calls connect(); if connect() returns False (no socket established, no exception thrown) the command cannot proceed.
Source
Thrown at Server/src/transport/legacy/unity_connection.py:369
except Exception as exc:
logger.debug(f"Preflight status check failed: {exc}")
for attempt in range(attempts + 1):
if deadline is not None and time.monotonic() >= deadline:
logger.warning(
"Command '%s' exceeded total deadline of %.1fs after %d attempt(s); giving up",
command_type, total_timeout, attempt)
raise TimeoutError(
f"Command '{command_type}' exceeded total deadline of "
f"{total_timeout:.1f}s (connection wedged or Unity unresponsive)")
try:
# Discard stale sockets left over from a previous domain reload
# so we reconnect instead of writing to a dead connection.
self._ensure_live_connection()
# Ensure connected (handshake occurs within connect())
t_conn_start = time.time()
if not self.sock and not self.connect(self._cap_to_deadline(config.connection_timeout, deadline)):
raise ConnectionError("Could not connect to Unity")
logger.info("[TIMING-STDIO] connect took %.3fs command=%s", time.time() - t_conn_start, command_type)
# Build payload
if command_type == 'ping':
payload = b'ping'
else:
payload = json.dumps({
'type': command_type,
'params': params,
}).encode('utf-8')
# Send/receive are serialized to protect the shared socket
with self._io_lock:
mode = 'framed' if self.use_framing else 'legacy'
with contextlib.suppress(Exception):
logger.debug(
f"send {len(payload)} bytes; mode={mode}; head={payload[:32].decode('utf-8', 'ignore')}")
t_send_start = time.time()View on GitHub (pinned to c21bf496bc)
Solutions
- Ensure Unity with the MCPForUnity bridge is running and has registered its port.
- Force-refresh instance discovery so a stale port is corrected.
- Raise UNITY_MCP_COMMAND_TOTAL_TIMEOUT so connect() has budget even after prior slow work.
Defensive patterns
Strategy: validation
Validate before calling
import socket
from transport.legacy.port_discovery import PortDiscovery
def bridge_listening(instance_id: str | None = None) -> bool:
port = stdio_port_registry.get_port(instance_id)
if port is None:
return False
try:
with socket.create_connection((config.unity_host, port), 1.0):
return True
except OSError:
return False Type guard
def is_connect_failed(e: BaseException) -> bool:
return (isinstance(e, ConnectionError) and str(e) == 'Could not connect to Unity') Try / catch
try:
resp = conn.send_command(cmd, params)
except ConnectionError as e:
if str(e) == 'Could not connect to Unity':
# refresh discovery in case the port is stale, then retry
stdio_port_registry.refresh()
resp = conn.send_command(cmd, params)
else:
raise Prevention
- Ensure Unity + the MCPForUnity bridge are running before issuing commands.
- Refresh port discovery when an editor restarts (its port can change).
- Keep command_total_timeout healthy so connect() has time budget.
When it happens
Trigger: send_command when the Unity bridge is not listening on the discovered port — port rediscovery returned a stale port, the deadline is already nearly exhausted (so _cap_to_deadline shrinks connect to ~0s), or connect() hit one of its own non-exception failure paths.
Common situations: Unity not running / bridge not started, discovery cache pointing at a dead port, or a long prior command consuming the deadline so this connect has no time budget left.
Related errors
- Failed to connect to Unity instance '{target.id}' on port {t
- No Unity Editor instances found. Please ensure Unity is runn
- Port must be positive.
- Port {port} is already in use.
- No available ports found in range {DefaultPort}-{DefaultPort
AI-assisted analysis of CoplayDev/unity-mcp@c21bf496bc (2026-08-13).
Data as JSON: /api/errors/e749eabdd61882f4.
Report an issue: GitHub.