CoplayDev/unity-mcp · error · Exception
Connection closed before receiving data
Error message
Connection closed before receiving data
What it means
Raised in the legacy (non-framing) receive loop (unity_connection.py:220): the very first sock.recv() returned empty (TCP EOF) and no chunks had been collected yet, so the peer closed before sending any data.
Source
Thrown at Server/src/transport/legacy/unity_connection.py:220
f"Received framed response ({len(payload)} bytes)")
return payload
except socket.timeout as exc:
logger.warning("Socket timeout during framed receive")
raise TimeoutError("Timeout receiving Unity response") from exc
except TimeoutError:
raise
except Exception as exc:
logger.error(f"Error during framed receive: {exc}")
raise
chunks = []
# Respect the socket's currently configured timeout
try:
while True:
chunk = sock.recv(buffer_size)
if not chunk:
if not chunks:
raise Exception(
"Connection closed before receiving data")
break
chunks.append(chunk)
# Process the data received so far
data = b''.join(chunks)
decoded_data = data.decode('utf-8')
# Check if we've received a complete response
try:
# Special case for ping-pong
if decoded_data.strip().startswith('{"status":"success","result":{"message":"pong"'):
logger.debug("Received ping response")
return data
# Handle escaped quotes in the content
if '"content":' in decoded_data:
# Find the content field and its valueView on GitHub (pinned to c21bf496bc)
Solutions
- Ensure Unity and the MCPForUnity bridge are still running and responsive.
- Prefer framing mode (default) where possible — it is more robust to mid-stream drops.
- Let send_command retry after reconnecting.
Defensive patterns
Strategy: retry
Validate before calling
# Check the bridge is registered before relying on a legacy connection
from pathlib import Path
def bridge_registered() -> bool:
return bool(list(Path.home().joinpath('.unity-mcp').glob('unity-mcp-status-*.json'))) Type guard
def is_legacy_eof(e: BaseException) -> bool:
return (isinstance(e, Exception)
and 'Connection closed before receiving data' in str(e)) Try / catch
try:
resp = conn.send_command(cmd, params)
except Exception as e:
if 'Connection closed before receiving data' in str(e):
conn.disconnect()
resp = conn.send_command(cmd, params)
else:
raise Prevention
- Prefer framing mode (default) over legacy for robustness.
- Keep Unity running for the full command duration.
- Reconnect after EOF rather than reusing the closed socket.
When it happens
Trigger: receive_full_response in legacy mode (config.require_framing=False) when Unity closes the socket before writing a response — domain reload, editor quit, or connecting to a port whose listener immediately drops the connection.
Common situations: Same as the framed EOF (error 182) but in legacy interop mode; also seen when the port is held by a process that accepts then closes.
Understand the failure class
- Connection failures: ECONNREFUSED, ECONNRESET, and friends — why connections get refused, reset, or dropped.
Related errors
- Connection closed before reading expected bytes
- Cannot connect to Unity MCP server at {cfg.host}:{cfg.port}.
- Timeout receiving Unity response
- Could not connect to Unity
- Failed to connect to Unity instance '{target.id}' on port {t
AI-assisted analysis of CoplayDev/unity-mcp@c21bf496bc (2026-08-13).
Data as JSON: /api/errors/3a9d5c62bc38f4a9.
Report an issue: GitHub.