Skip to content

fix: When setting Color/Rect properties using manage_components, both array and object formats are supported#1035

Open
Misaka-Mikoto-Tech wants to merge 7 commits intoCoplayDev:betafrom
Misaka-Mikoto-Tech:CodexCompatible
Open

fix: When setting Color/Rect properties using manage_components, both array and object formats are supported#1035
Misaka-Mikoto-Tech wants to merge 7 commits intoCoplayDev:betafrom
Misaka-Mikoto-Tech:CodexCompatible

Conversation

@Misaka-Mikoto-Tech
Copy link
Copy Markdown

@Misaka-Mikoto-Tech Misaka-Mikoto-Tech commented Apr 4, 2026

Description

When setting Color/Rect properties using manage_components, both array and object formats are supported.

Type of Change

Save your change type

  • Bug fix (non-breaking change that fixes an issue)

Changes Made

Updated the ### Colors section of SKILL.md to clarify that when manipulating Color/Rect-type attributes via manage_components, an object format is required rather than an array.

Testing/Screenshots/Recordings

Before
image
image
After
image
image

Documentation Updates

  • I have added/removed/modified tools or resources
  • If yes, I have updated all documentation files using:
    • The LLM prompt at tools/UPDATE_DOCS_PROMPT.md (recommended)
    • Manual updates following the guide at tools/UPDATE_DOCS.md

Related Issues

Additional Notes

Summary by Sourcery

Normalize and validate JSON string property values passed to manage_components and document the expected formats for Unity struct-like properties.

Bug Fixes:

  • Ensure manage_components parses JSON string values into their structured forms before sending them to Unity, avoiding invalid or unintended payload shapes for Unity properties.

Documentation:

  • Clarify SKILL.md guidance on using JSON string values with manage_components, including recommending object format for Color and Rect and documenting accepted formats for Vector and Quaternion types.

Tests:

  • Add integration tests verifying that manage_components correctly parses JSON string values for Vector, Quaternion, Color, and Rect-style properties and forwards the expected structured payloads.

Summary by CodeRabbit

  • New Features

    • Property operations now support array-format inputs for Unity struct types (Color, Rect)
    • Improved value normalization for JSON-based property assignments
  • Improvements

    • Enhanced type conversion with sensible defaults (Color alpha defaults to 1.0 when unspecified)
    • Better error handling for property type conversions

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai bot commented Apr 4, 2026

Reviewer's Guide

Updates manage_components value handling to parse JSON string payloads for Unity struct-like properties and documents the expected object vs array formats in SKILL.md, with new integration tests covering Color/Rect and related Unity struct cases.

Sequence diagram for manage_components value normalization and forwarding

sequenceDiagram
    actor MCPClient
    participant Server as ServerTools
    participant Manage as manage_components
    participant Parser as parse_json_payload
    participant Unity as UnityEngine

    MCPClient->>Server: Request manage_components
    Server->>Manage: manage_components(action, target, component_type, property, value)

    Manage->>Manage: validate action/target/component_type/property
    Manage->>Manage: validate props (props_error)
    alt props_error exists
        Manage-->>Server: {success: False, message: props_error}
        Server-->>MCPClient: Error response
    else no props_error
        Manage->>Manage: check value is "[object Object]" or "undefined"
        alt invalid sentinel string
            Manage-->>Server: {success: False, message: invalid input}
            Server-->>MCPClient: Error response
        else valid value
            Manage->>Parser: parse_json_payload(value)
            Parser-->>Manage: normalized_value (object/array/native)
            Manage->>Unity: call tool with normalized_value
            Unity-->>Manage: execution result
            Manage-->>Server: {success: True/False, message, data}
            Server-->>MCPClient: Final response
        end
    end
Loading

File-Level Changes

Change Details Files
Normalize string-valued property payloads in manage_components by JSON-parsing them before sending to Unity.
  • Extend value validation comment to cover normalization as well as validation.
  • Reject placeholder string values like "[object Object]" and "undefined" with a clear error message.
  • Invoke a new parse_json_payload helper on the incoming value so JSON string payloads are converted to native types prior to command dispatch.
Server/src/services/tools/manage_components.py
Add integration coverage to ensure JSON string payloads for Unity struct-like properties are parsed and forwarded in the correct shape.
  • Add an async test verifying a Color-style JSON object string is parsed into a dict before being sent.
  • Add a parametrized async test verifying JSON-string single values for Vector3 (array/object), Quaternion, Color, and Rect preserve their intended Unity struct shapes.
  • Use a fake async_send_command_with_retry to capture and assert on the outgoing params, including property name and normalized value.
Server/tests/integration/test_manage_components.py
Clarify documentation for Color/Rect and other struct-like properties when using manage_components, emphasizing JSON object formats for Color/Rect.
  • Document that some MCP clients send complex property values as JSON strings and that the server now parses these before forwarding to Unity.
  • Describe which Unity structs accept array or object forms versus those that should use object form (Color/Rect).
  • Add concrete manage_components examples for Vector3 position, Vector3 localScale, Color color, and Rect pixelRect using array and object JSON payloads, highlighting the preferred object form for Color/Rect.
unity-mcp-skill/SKILL.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 4, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The PR enables JSON array parsing for property values in the MCP server's manage_components tool, and updates Unity's Color and Rect type converters to accept JSON arrays as input alongside objects, with corresponding integration and unit tests to validate the new behavior.

Changes

Cohort / File(s) Summary
Server-side JSON parsing
Server/src/services/tools/manage_components.py
Applied parse_json_payload(value) after invalid-input checks to normalize/decode value parameters before constructing Unity request payloads for set_property operations.
Server-side integration tests
Server/tests/integration/test_manage_components.py
Added three new async tests to validate JSON-string value handling for set_property: parametrized tests for array (parsed as list) and object (parsed as dict) inputs, plus a test confirming plain strings remain unchanged.
Unity type converters
MCPForUnity/Runtime/Serialization/UnityTypeConverters.cs
Enhanced ColorConverter.ReadJson and RectConverter.ReadJson to parse JSON arrays directly (in addition to objects); Color now supports 3–4 element arrays with alpha defaulting to 1f, and Rect supports 4-element arrays, both with improved error messages.
Unity converter tests
TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/PropertyConversion_UnityStructArraySupport_Tests.cs, ...Tests.cs.meta
Added new EditMode test class with three test cases verifying PropertyConversion.ConvertToType correctly handles JArray-parsed inputs for Color (with/without alpha) and Rect struct conversions; includes associated Unity metadata file.

Sequence Diagram(s)

sequenceDiagram
    actor Client
    participant Server as MCP Server<br/>(manage_components)
    participant Converter as PropertyConversion<br/>UnityTypeConverters
    participant Unity as Unity Engine

    Client->>Server: set_property value="[1.0, 2.0, 3.0]"<br/>(JSON array string)
    Server->>Server: parse_json_payload(value)<br/>→ [1.0, 2.0, 3.0]
    Server->>Unity: Send params with<br/>parsed list value
    Unity->>Converter: ReadJson with JArray
    Converter->>Converter: Extract r, g, b<br/>(alpha defaults to 1f)
    Converter->>Unity: Return Color(r, g, b, 1f)
    
    Client->>Server: set_property value="Player One"<br/>(plain string)
    Server->>Server: parse_json_payload(value)<br/>→ "Player One" (unchanged)
    Server->>Unity: Send params with<br/>string value
    Unity->>Converter: ReadJson with JValue string
    Converter->>Unity: Return string as-is
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • dsarno
  • msanatan

Poem

🐰 Arrays hop into structs, so neat—
parse_json_payload makes values complete!
Color and Rect now dance in array form,
Converting with grace, the new JSON norm. ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 46.15% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: enabling both array and object format support for Color/Rect properties in manage_components, which aligns with the core implementation changes across the codebase.
Description check ✅ Passed The PR description addresses all major template sections with clear information about changes, type, testing, and documentation updates.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've left some high level feedback:

  • The description says Color/Rect must use the object format, but SKILL.md language only says to "prefer" object form; consider tightening the docs to clearly reflect whether array input is still supported or now rejected.
  • The unconditional call to parse_json_payload on any string value may change behavior for plain string properties; ensure parse_json_payload is conservative (e.g., only parses when the string is valid JSON for a structured type) so simple string values are not unintentionally transformed.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The description says Color/Rect must use the object format, but SKILL.md language only says to "prefer" object form; consider tightening the docs to clearly reflect whether array input is still supported or now rejected.
- The unconditional call to parse_json_payload on any string value may change behavior for plain string properties; ensure parse_json_payload is conservative (e.g., only parses when the string is valid JSON for a structured type) so simple string values are not unintentionally transformed.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
Server/tests/integration/test_manage_components.py (1)

193-261: Minor: Test uses mismatched component types for some properties.

The parametrized test uses component_type="Transform" for all cases, but color belongs to renderers/lights and pixelRect belongs to cameras. While this doesn't affect the test's purpose (verifying JSON parsing on the Python side), it may cause confusion or fail if the mock is ever replaced with a real Unity call.

Consider using appropriate component types for realism:

Suggested improvement
 `@pytest.mark.parametrize`(
-    ("property_name", "raw_value", "expected_value"),
+    ("component_type", "property_name", "raw_value", "expected_value"),
     [
         (
+            "Transform",
             "position",
             "[1.0, 2.0, 3.0]",
             [1.0, 2.0, 3.0],
         ),
         (
+            "Transform",
             "localScale",
             '{"x": 2.0, "y": 3.0, "z": 4.0}',
             {"x": 2.0, "y": 3.0, "z": 4.0},
         ),
         (
+            "Transform",
             "rotation",
             '{"x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0}',
             {"x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0},
         ),
         (
+            "Light",
             "color",
             '{"r": 1.0, "g": 1.0, "b": 0.0, "a": 1.0}',
             {"r": 1.0, "g": 1.0, "b": 0.0, "a": 1.0},
         ),
         (
+            "Camera",
             "pixelRect",
             '{"x": 10.0, "y": 20.0, "width": 1920.0, "height": 1080.0}',
             {"x": 10.0, "y": 20.0, "width": 1920.0, "height": 1080.0},
         ),
     ],
 )
 async def test_manage_components_set_property_single_json_value_for_unity_structs(
     monkeypatch,
+    component_type,
     property_name,
     raw_value,
     expected_value,
 ):
     # ... update component_type=component_type in the call
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Server/tests/integration/test_manage_components.py` around lines 193 - 261,
The test test_manage_components_set_property_single_json_value_for_unity_structs
uses component_type="Transform" for all parameterized cases which is misleading
(color and pixelRect belong to different components); update the
manage_components invocation in that test to pass realistic component_type
values per case (e.g., use a renderer or Light for "color" and a Camera for
"pixelRect") so the parameterization matches actual Unity component semantics
while keeping the same assertions; locate the call to
manage_comp_mod.manage_components in the test and change the component_type
argument based on the property_name parameter.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@Server/tests/integration/test_manage_components.py`:
- Around line 193-261: The test
test_manage_components_set_property_single_json_value_for_unity_structs uses
component_type="Transform" for all parameterized cases which is misleading
(color and pixelRect belong to different components); update the
manage_components invocation in that test to pass realistic component_type
values per case (e.g., use a renderer or Light for "color" and a Camera for
"pixelRect") so the parameterization matches actual Unity component semantics
while keeping the same assertions; locate the call to
manage_comp_mod.manage_components in the test and change the component_type
argument based on the property_name parameter.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: bb527c16-6a31-494b-aa13-c107dc496c75

📥 Commits

Reviewing files that changed from the base of the PR and between 1f0ef2c and 1c12c45.

📒 Files selected for processing (3)
  • Server/src/services/tools/manage_components.py
  • Server/tests/integration/test_manage_components.py
  • unity-mcp-skill/SKILL.md

@Misaka-Mikoto-Tech Misaka-Mikoto-Tech changed the title use the object format When setting Color/Rect properties via manage_components [Bug fix]Use the object format When setting Color/Rect properties via manage_components Apr 4, 2026
@Misaka-Mikoto-Tech Misaka-Mikoto-Tech changed the title [Bug fix]Use the object format When setting Color/Rect properties via manage_components fix: Use the object format When setting Color/Rect properties via manage_components Apr 4, 2026
@Misaka-Mikoto-Tech
Copy link
Copy Markdown
Author

Misaka-Mikoto-Tech commented Apr 4, 2026

I checked both points and agree the docs should be more explicit.

I’ve updated SKILL.md so the wording is tighter on the manage_components path:

Vector2 / Vector3 / Vector4 / Quaternion: array or object forms are acceptable
Color / Rect: use object form matching Unity field names
So the documentation now reflects the actual reliable payload shape instead of only saying “prefer”.

On parse_json_payload: the current implementation is intentionally conservative. It only attempts parsing for strings that already look like structured/scalar JSON ({...}, [...], true, false, null, numeric literals), and otherwise returns the original string unchanged. That means ordinary plain string properties are preserved as strings, while JSON-stringified structured values from MCP clients can still be recovered before reaching Unity.

I also added regression coverage around the manage_components JSON-string path for representative Unity struct types so this behavior is easier to verify going forward.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
Server/tests/integration/test_manage_components.py (1)

223-291: Add the missing object-form Vector3 case to match the stated contract.

Line 263 says Vector3 accepts array or object JSON, but only array form is currently tested.

Suggested test matrix update
 `@pytest.mark.parametrize`(
     ("property_name", "raw_value", "expected_value"),
     [
         (
             "position",
             "[1.0, 2.0, 3.0]",
             [1.0, 2.0, 3.0],
         ),
+        (
+            "position",
+            '{"x": 1.0, "y": 2.0, "z": 3.0}',
+            {"x": 1.0, "y": 2.0, "z": 3.0},
+        ),
         (
             "localScale",
             '{"x": 2.0, "y": 3.0, "z": 4.0}',
             {"x": 2.0, "y": 3.0, "z": 4.0},
         ),
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Server/tests/integration/test_manage_components.py` around lines 223 - 291,
The test test_manage_components_set_property_single_json_value_for_unity_structs
is missing the object-form Vector3 case: add another parameter tuple for
("position", '{"x": 1.0, "y": 2.0, "z": 3.0}', [1.0, 2.0, 3.0]) to the
parametrize list so manage_components is validated for both array and object
JSON forms for Vector3; update the param list in the test function to include
this new case (refer to the test name
test_manage_components_set_property_single_json_value_for_unity_structs and the
"position" property).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@Server/tests/integration/test_manage_components.py`:
- Around line 223-291: The test
test_manage_components_set_property_single_json_value_for_unity_structs is
missing the object-form Vector3 case: add another parameter tuple for
("position", '{"x": 1.0, "y": 2.0, "z": 3.0}', [1.0, 2.0, 3.0]) to the
parametrize list so manage_components is validated for both array and object
JSON forms for Vector3; update the param list in the test function to include
this new case (refer to the test name
test_manage_components_set_property_single_json_value_for_unity_structs and the
"position" property).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b2396ce5-0b64-43c9-bc12-8da748b97cc1

📥 Commits

Reviewing files that changed from the base of the PR and between 172c8fc and 0a76f83.

📒 Files selected for processing (1)
  • Server/tests/integration/test_manage_components.py

1. Remove the code examples for Color/Rect formatting in `skill.md`
2. Unity supports both array and object formats when parsing these two types.
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
MCPForUnity/Runtime/Serialization/UnityTypeConverters.cs (1)

116-131: Consider defensive checks for non-numeric array elements.

The direct (float)arr[n] casts will throw InvalidCastException if the JSON array contains non-numeric values (e.g., [1.0, "red", 0.5]). While the current exception is informative enough for debugging, catching and re-throwing as JsonSerializationException with a clearer message would provide better diagnostics consistent with the error at line 124.

This is a minor robustness concern since malformed input is already an error path.

♻️ Optional: wrap casts for clearer error messaging
         public override Color ReadJson(JsonReader reader, Type objectType, Color existingValue, bool hasExistingValue, JsonSerializer serializer)
         {
             JToken token = JToken.Load(reader);
             if (token is JArray arr && arr.Count >= 3)
             {
-                float alpha = arr.Count >= 4 ? (float)arr[3] : 1f;
-                return new Color((float)arr[0], (float)arr[1], (float)arr[2], alpha);
+                try
+                {
+                    float alpha = arr.Count >= 4 ? (float)arr[3] : 1f;
+                    return new Color((float)arr[0], (float)arr[1], (float)arr[2], alpha);
+                }
+                catch (Exception ex) when (ex is InvalidCastException or FormatException)
+                {
+                    throw new JsonSerializationException($"Cannot deserialize Color: array elements must be numeric. Array: '{token}'", ex);
+                }
             }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@MCPForUnity/Runtime/Serialization/UnityTypeConverters.cs` around lines 116 -
131, The Color deserialization currently casts JArray elements directly (e.g.,
(float)arr[0]) which can throw InvalidCastException for non-numeric JSON; update
the UnityTypeConverters Color deserialization block to validate/convert each
array element safely: for arr[0..2] (and optional arr[3]) check token.Type (or
use TryGetValue/Convert.ToSingle with try/catch) and if conversion fails throw a
JsonSerializationException that includes the offending token and a clear
message; ensure the same defensive conversion is applied to the JObject path
(jo["r"], jo["g"], jo["b"], jo["a"]) so all numeric parsing errors surface as
JsonSerializationException with contextual info.
TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/PropertyConversion_UnityStructArraySupport_Tests.cs (1)

12-46: Consider adding negative test cases for robustness.

The current tests cover happy paths. Adding tests for error conditions would strengthen coverage and document expected failure behavior:

🧪 Suggested error case tests
[Test]
public void ConvertToType_ColorArrayTooFewElements_Throws()
{
    Assert.Throws<Newtonsoft.Json.JsonSerializationException>(() =>
        PropertyConversion.ConvertToType(
            JArray.Parse("[1.0, 0.5]"),  // Only 2 elements
            typeof(Color)
        )
    );
}

[Test]
public void ConvertToType_RectArrayTooFewElements_Throws()
{
    Assert.Throws<Newtonsoft.Json.JsonSerializationException>(() =>
        PropertyConversion.ConvertToType(
            JArray.Parse("[10.0, 20.0, 30.0]"),  // Only 3 elements
            typeof(Rect)
        )
    );
}

[Test]
public void ConvertToType_ColorObject_StillWorks()
{
    // Verify backward compatibility with object format
    var result = (Color)PropertyConversion.ConvertToType(
        JObject.Parse("{\"r\": 1.0, \"g\": 0.5, \"b\": 0.25, \"a\": 0.75}"),
        typeof(Color)
    );

    Assert.AreEqual(new Color(1.0f, 0.5f, 0.25f, 0.75f), result);
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/PropertyConversion_UnityStructArraySupport_Tests.cs`
around lines 12 - 46, Add negative and compatibility tests for
PropertyConversion.ConvertToType: add a test named
ConvertToType_ColorArrayTooFewElements_Throws that calls
PropertyConversion.ConvertToType with JArray.Parse("[1.0, 0.5]") and asserts it
throws Newtonsoft.Json.JsonSerializationException; add
ConvertToType_RectArrayTooFewElements_Throws that calls
PropertyConversion.ConvertToType with JArray.Parse("[10.0, 20.0, 30.0]") and
asserts the same exception for type Rect; and add
ConvertToType_ColorObject_StillWorks that passes a JObject with r/g/b/a keys to
PropertyConversion.ConvertToType and asserts it returns the expected Color—place
these tests in PropertyConversion_UnityStructArraySupport_Tests alongside the
existing tests to cover failure and object-format compatibility.
Server/tests/integration/test_manage_components.py (1)

215-247: Consider adding edge case tests for scalar JSON strings.

The test correctly verifies plain strings pass through unchanged. However, based on the parse_json_payload implementation in Server/src/services/tools/utils.py (lines 29-62), strings like "true", "false", "null", and numeric strings like "42" will be coerced to their JSON primitive types.

Consider adding test cases to document this behavior and guard against regressions:

🧪 Suggested additional test cases
`@pytest.mark.asyncio`
`@pytest.mark.parametrize`(
    ("raw_value", "expected_value", "expected_type"),
    [
        ("true", True, bool),
        ("false", False, bool),
        ("null", None, type(None)),
        ("42", 42, int),
        ("3.14", 3.14, float),
    ],
)
async def test_manage_components_set_property_scalar_json_coercion(
    monkeypatch,
    raw_value,
    expected_value,
    expected_type,
):
    """Test scalar JSON strings are coerced to native Python types.
    
    This documents intentional behavior: strings that look like JSON scalars
    are parsed. If a literal string "true" is needed, upstream must quote it.
    """
    captured = {}

    async def fake_send(cmd, params, **kwargs):
        captured["params"] = params
        return {"success": True, "data": {"instanceID": 12345}}

    monkeypatch.setattr(
        manage_comp_mod,
        "async_send_command_with_retry",
        fake_send,
    )

    resp = await manage_comp_mod.manage_components(
        ctx=DummyContext(),
        action="set_property",
        target="TestObject",
        component_type="TestComponent",
        property="scalarProp",
        value=raw_value,
    )

    assert resp.get("success") is True
    assert captured["params"]["value"] == expected_value
    if expected_value is not None:
        assert isinstance(captured["params"]["value"], expected_type)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Server/tests/integration/test_manage_components.py` around lines 215 - 247,
Add parametric tests alongside
test_manage_components_set_property_single_plain_string_value_stays_string to
cover scalar JSON-string coercion by parse_json_payload: create a parametrize
test (e.g., test_manage_components_set_property_scalar_json_coercion) that
monkeypatches manage_components' async_send_command_with_retry (same fake_send
pattern), calls manage_components with value set to raw_value values
"true","false","null","42","3.14", and asserts resp success plus that
captured["params"]["value"] equals the expected_value and has the expected_type
where applicable; this ensures parse_json_payload's behavior (function
parse_json_payload) is documented and guarded against regressions.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@MCPForUnity/Runtime/Serialization/UnityTypeConverters.cs`:
- Around line 116-131: The Color deserialization currently casts JArray elements
directly (e.g., (float)arr[0]) which can throw InvalidCastException for
non-numeric JSON; update the UnityTypeConverters Color deserialization block to
validate/convert each array element safely: for arr[0..2] (and optional arr[3])
check token.Type (or use TryGetValue/Convert.ToSingle with try/catch) and if
conversion fails throw a JsonSerializationException that includes the offending
token and a clear message; ensure the same defensive conversion is applied to
the JObject path (jo["r"], jo["g"], jo["b"], jo["a"]) so all numeric parsing
errors surface as JsonSerializationException with contextual info.

In `@Server/tests/integration/test_manage_components.py`:
- Around line 215-247: Add parametric tests alongside
test_manage_components_set_property_single_plain_string_value_stays_string to
cover scalar JSON-string coercion by parse_json_payload: create a parametrize
test (e.g., test_manage_components_set_property_scalar_json_coercion) that
monkeypatches manage_components' async_send_command_with_retry (same fake_send
pattern), calls manage_components with value set to raw_value values
"true","false","null","42","3.14", and asserts resp success plus that
captured["params"]["value"] equals the expected_value and has the expected_type
where applicable; this ensures parse_json_payload's behavior (function
parse_json_payload) is documented and guarded against regressions.

In
`@TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/PropertyConversion_UnityStructArraySupport_Tests.cs`:
- Around line 12-46: Add negative and compatibility tests for
PropertyConversion.ConvertToType: add a test named
ConvertToType_ColorArrayTooFewElements_Throws that calls
PropertyConversion.ConvertToType with JArray.Parse("[1.0, 0.5]") and asserts it
throws Newtonsoft.Json.JsonSerializationException; add
ConvertToType_RectArrayTooFewElements_Throws that calls
PropertyConversion.ConvertToType with JArray.Parse("[10.0, 20.0, 30.0]") and
asserts the same exception for type Rect; and add
ConvertToType_ColorObject_StillWorks that passes a JObject with r/g/b/a keys to
PropertyConversion.ConvertToType and asserts it returns the expected Color—place
these tests in PropertyConversion_UnityStructArraySupport_Tests alongside the
existing tests to cover failure and object-format compatibility.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 45460602-1d40-4da7-bd6d-4837efe738d7

📥 Commits

Reviewing files that changed from the base of the PR and between 8175e85 and 26ac184.

📒 Files selected for processing (4)
  • MCPForUnity/Runtime/Serialization/UnityTypeConverters.cs
  • Server/tests/integration/test_manage_components.py
  • TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/PropertyConversion_UnityStructArraySupport_Tests.cs
  • TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/PropertyConversion_UnityStructArraySupport_Tests.cs.meta
✅ Files skipped from review due to trivial changes (1)
  • TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/PropertyConversion_UnityStructArraySupport_Tests.cs.meta

@Misaka-Mikoto-Tech
Copy link
Copy Markdown
Author

I used Codex to initiate multiple sessions; the AI ​​sometimes passes Color values ​​as arrays and other times as objects. Therefore, supporting both formats within the current codebase ensures greater stability.

@Misaka-Mikoto-Tech Misaka-Mikoto-Tech changed the title fix: Use the object format When setting Color/Rect properties via manage_components fix: When setting Color/Rect properties using manage_components, both array and object formats are supported Apr 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant