{"record":{"id":"e749eabdd61882f4","repo":"CoplayDev/unity-mcp","slug":"could-not-connect-to-unity","errorCode":null,"errorMessage":"Could not connect to Unity","messagePattern":"Could not connect to Unity","errorType":"exception","errorClass":"ConnectionError","httpStatus":null,"severity":"critical","filePath":"Server/src/transport/legacy/unity_connection.py","lineNumber":369,"sourceCode":"        except Exception as exc:\n            logger.debug(f\"Preflight status check failed: {exc}\")\n\n        for attempt in range(attempts + 1):\n            if deadline is not None and time.monotonic() >= deadline:\n                logger.warning(\n                    \"Command '%s' exceeded total deadline of %.1fs after %d attempt(s); giving up\",\n                    command_type, total_timeout, attempt)\n                raise TimeoutError(\n                    f\"Command '{command_type}' exceeded total deadline of \"\n                    f\"{total_timeout:.1f}s (connection wedged or Unity unresponsive)\")\n            try:\n                # Discard stale sockets left over from a previous domain reload\n                # so we reconnect instead of writing to a dead connection.\n                self._ensure_live_connection()\n                # Ensure connected (handshake occurs within connect())\n                t_conn_start = time.time()\n                if not self.sock and not self.connect(self._cap_to_deadline(config.connection_timeout, deadline)):\n                    raise ConnectionError(\"Could not connect to Unity\")\n                logger.info(\"[TIMING-STDIO] connect took %.3fs command=%s\", time.time() - t_conn_start, command_type)\n\n                # Build payload\n                if command_type == 'ping':\n                    payload = b'ping'\n                else:\n                    payload = json.dumps({\n                        'type': command_type,\n                        'params': params,\n                    }).encode('utf-8')\n\n                # Send/receive are serialized to protect the shared socket\n                with self._io_lock:\n                    mode = 'framed' if self.use_framing else 'legacy'\n                    with contextlib.suppress(Exception):\n                        logger.debug(\n                            f\"send {len(payload)} bytes; mode={mode}; head={payload[:32].decode('utf-8', 'ignore')}\")\n                    t_send_start = time.time()","sourceCodeStart":351,"sourceCodeEnd":387,"githubUrl":"https://github.com/CoplayDev/unity-mcp/blob/c21bf496bca87d54e75bad048563c3adb1782081/Server/src/transport/legacy/unity_connection.py#L351-L387","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":null,"handlingStrategy":"validation","validationCode":"import socket\nfrom transport.legacy.port_discovery import PortDiscovery\n\ndef bridge_listening(instance_id: str | None = None) -> bool:\n    port = stdio_port_registry.get_port(instance_id)\n    if port is None:\n        return False\n    try:\n        with socket.create_connection((config.unity_host, port), 1.0):\n            return True\n    except OSError:\n        return False","typeGuard":"def is_connect_failed(e: BaseException) -> bool:\n    return (isinstance(e, ConnectionError) and str(e) == 'Could not connect to Unity')","tryCatchPattern":"try:\n    resp = conn.send_command(cmd, params)\nexcept ConnectionError as e:\n    if str(e) == 'Could not connect to Unity':\n        # refresh discovery in case the port is stale, then retry\n        stdio_port_registry.refresh()\n        resp = conn.send_command(cmd, params)\n    else:\n        raise","preventionTips":["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."],"tags":["connection","port","bridge","discovery","deadline"],"backgroundTag":null,"analyzedSha":"c21bf496bca87d54e75bad048563c3adb1782081","analyzedAt":"2026-08-13T17:36:56.095Z","schemaVersion":2},"datasetVersion":"2026-08-13T19:17:28.613Z"}