{"record":{"id":"cda99d517a337be8","repo":"CoplayDev/unity-mcp","slug":"invalid-framed-length-payload-len","errorCode":null,"errorMessage":"Invalid framed length: {payload_len}","messagePattern":"Invalid framed length: (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"Server/src/transport/legacy/unity_connection.py","lineNumber":198,"sourceCode":"            heartbeat_limit = getattr(config, 'max_heartbeat_frames', 16)\n            heartbeat_window = getattr(config, 'heartbeat_timeout', 2.0)\n            heartbeat_started = time.monotonic()\n            heartbeat_count = 0\n            try:\n                while True:\n                    header = self._read_exact(sock, 8)\n                    payload_len = struct.unpack('>Q', header)[0]\n                    if payload_len == 0:\n                        heartbeat_count += 1\n                        logger.debug(\n                            f\"Received heartbeat frame #{heartbeat_count}\")\n                        if heartbeat_count >= heartbeat_limit or (time.monotonic() - heartbeat_started) > heartbeat_window:\n                            raise TimeoutError(\n                                \"Unity sent heartbeat frames without payload within configured threshold\"\n                            )\n                        continue\n                    if payload_len > FRAMED_MAX:\n                        raise ValueError(\n                            f\"Invalid framed length: {payload_len}\")\n                    payload = self._read_exact(sock, payload_len)\n                    logger.debug(\n                        f\"Received framed response ({len(payload)} bytes)\")\n                    return payload\n            except socket.timeout as exc:\n                logger.warning(\"Socket timeout during framed receive\")\n                raise TimeoutError(\"Timeout receiving Unity response\") from exc\n            except TimeoutError:\n                raise\n            except Exception as exc:\n                logger.error(f\"Error during framed receive: {exc}\")\n                raise\n\n        chunks = []\n        # Respect the socket's currently configured timeout\n        try:\n            while True:","sourceCodeStart":180,"sourceCodeEnd":216,"githubUrl":"https://github.com/CoplayDev/unity-mcp/blob/c21bf496bca87d54e75bad048563c3adb1782081/Server/src/transport/legacy/unity_connection.py#L180-L216","documentation":"Raised in the framed receive loop (unity_connection.py:198) when the 8-byte big-endian length prefix decodes to a value greater than FRAMED_MAX (64 MiB). This is a defensive guard against a corrupted or misaligned stream that would otherwise trigger a huge allocation.","triggerScenarios":"receive_full_response reads a length prefix that is garbage — protocol desync, a peer writing raw plaintext onto a connection that negotiated framing, or memory/stream corruption producing an absurd length.","commonSituations":"Version/transport mismatch where one side frames and the other sends legacy plaintext, a partial read making the 8 header bytes line up wrong, or two clients stomping the same stdio port.","solutions":["Verify the Python server and MCPForUnity Unity package are on compatible versions (both must agree on framing).","Ensure only one client owns the stdio port — new stdio connections stomp old ones.","Drop the socket and reconnect to re-synchronize the stream (send_command does this on retry)."],"exampleFix":"// before — shared port, mixed traffic corrupts the framed stream\n\n// after — one owner per port; reconnect to resync\nconn.disconnect()\nconn.connect()","handlingStrategy":"try-catch","validationCode":"FRAMED_MAX = 64 * 1024 * 1024\n\ndef framed_length_plausible(length: int) -> bool:\n    return 0 <= length <= FRAMED_MAX","typeGuard":"def is_invalid_framed_length(e: BaseException) -> bool:\n    return isinstance(e, ValueError) and 'Invalid framed length' in str(e)","tryCatchPattern":"try:\n    data = conn.receive_full_response(conn.sock)\nexcept ValueError as e:\n    if 'Invalid framed length' in str(e):\n        # stream desync — drop socket, reconnect to resync\n        conn.disconnect()\n        conn.connect()\n        data = conn.receive_full_response(conn.sock)\n    else:\n        raise","preventionTips":["Run matched server + Unity package versions so framing is agreed on both sides.","Ensure a single client owns the stdio port (stdio connections stomp each other).","Reconnect after any protocol error rather than continuing on a desynced stream."],"tags":["framed","protocol","corruption","desync"],"backgroundTag":null,"analyzedSha":"c21bf496bca87d54e75bad048563c3adb1782081","analyzedAt":"2026-08-13T17:36:56.095Z","schemaVersion":2},"datasetVersion":"2026-08-13T19:17:28.613Z"}