CoplayDev/unity-mcp · error · JsonSerializationException

Cannot deserialize Vector3 from {token.Type}: '{token}'

Error message

Cannot deserialize Vector3 from {token.Type}: '{token}'

What it means

Thrown by Vector3Converter.ReadJson when the JSON token being deserialized is neither a JArray with count >= 3 nor a JObject. Vector3 accepts [x, y, z] array form or {"x":..,"y":..,"z":..} object form; any other JSON structure (number, string, boolean, array with < 3 elements) triggers this.

Source

Thrown at MCPForUnity/Runtime/Serialization/UnityTypeConverters.cs:32

        public override void WriteJson(JsonWriter writer, Vector3 value, JsonSerializer serializer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("x");
            writer.WriteValue(value.x);
            writer.WritePropertyName("y");
            writer.WriteValue(value.y);
            writer.WritePropertyName("z");
            writer.WriteValue(value.z);
            writer.WriteEndObject();
        }

        public override Vector3 ReadJson(JsonReader reader, Type objectType, Vector3 existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            JToken token = JToken.Load(reader);
            if (token is JArray arr && arr.Count >= 3)
                return new Vector3((float)arr[0], (float)arr[1], (float)arr[2]);
            if (token is not JObject jo)
                throw new JsonSerializationException($"Cannot deserialize Vector3 from {token.Type}: '{token}'");
            return new Vector3(
                (float)jo["x"],
                (float)jo["y"],
                (float)jo["z"]
            );
        }
    }

    public class Vector2Converter : JsonConverter<Vector2>
    {
        public override void WriteJson(JsonWriter writer, Vector2 value, JsonSerializer serializer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("x");
            writer.WriteValue(value.x);
            writer.WritePropertyName("y");
            writer.WriteValue(value.y);
            writer.WriteEndObject();

View on GitHub (pinned to c21bf496bc)

Solutions

  1. Send Vector3 as [x, y, z] array: "position": [1.0, 2.0, 3.0].
  2. Or send as object: "position": {"x": 1.0, "y": 2.0, "z": 3.0}.
  3. Ensure arrays have exactly 3 numeric elements (floats or ints).
  4. Do not pass strings, numbers, or booleans where a vector is expected.

Example fix

// before
params = {"position": "1,2,3"}
// after
params = {"position": [1.0, 2.0, 3.0]}
Defensive patterns

Strategy: type-guard

Validate before calling

def is_valid_vector3(val) -> bool:
    if isinstance(val, (list, tuple)) and len(val) >= 3:
        return all(isinstance(v, (int, float)) for v in val[:3])
    if isinstance(val, dict):
        return all(k in val for k in ('x', 'y', 'z'))
    return False

Type guard

function isVector3(val: unknown): val is number[] | {x:number;y:number;z:number} {
  if (Array.isArray(val) && val.length >= 3)
    return val.slice(0, 3).every(v => typeof v === 'number');
  if (val && typeof val === 'object' && 'x' in val && 'y' in val && 'z' in val)
    return true;
  return false;
}

Try / catch

try
{
    var vec = serializer.Deserialize<Vector3>(reader);
}
catch (JsonSerializationException ex) when (ex.Message.Contains("Cannot deserialize Vector3"))
{
    return new ErrorResponse($"Vector3 must be [x,y,z] or {{x,y,z}}. Got: {token}");
}

Prevention

When it happens

Trigger: Deserializing a JSON payload containing a Vector3 field where the value is a single number (e.g. position: 5), a string (e.g. "1,2,3"), an array with fewer than 3 elements, or a different JSON type. Happens when the source data format doesn't match the converter's expectations.

Common situations: Client sends position as a comma-separated string instead of an array/object; AI model outputs a scalar where a vector is expected; serialization library omits null/default components producing shorter arrays; mismatch between Python-side dict and expected Unity vector format.

Related errors


AI-assisted analysis of CoplayDev/unity-mcp@c21bf496bc (2026-08-13). Data as JSON: /api/errors/3f6601dfd76625e5. Report an issue: GitHub.