Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ public class IsolatedLightConfig
+ "activated for the render (their OnEnable callbacks may fire — restored in finally, but "
+ "side effects like audio/network/animation events are not undoable). When isolated=false, "
+ "the existing scene state is rendered as-is without activating inactive objects. Supports "
+ "custom multi-light setups via JSON. Returns a base64-encoded PNG.\n\n" +
+ "custom multi-light setups via JSON. Returns the rendered PNG image.\n\n" +
"## Camera views\n\n" +
"`Front` (-Z), `Back` (+Z), `Left` (-X), `Right` (+X), `Top` (+Y), `Bottom` (-Y). " +
"`Composite` produces a single 2x2 image (Front, Right, Back, Top) where each sub-view uses the requested " +
Expand All @@ -134,7 +134,7 @@ public class IsolatedLightConfig
+ "activated for the render (their OnEnable callbacks may fire — restored in finally, but "
+ "side effects like audio/network/animation events are not undoable). When isolated=false, "
+ "the existing scene state is rendered as-is without activating inactive objects. Supports "
+ "custom multi-light setups via JSON. Returns a base64-encoded PNG." + SavePathNote)]
+ "custom multi-light setups via JSON. Returns the rendered PNG image." + SavePathNote)]
public ResponseCallTool ScreenshotIsolated
(
[Description("Reference to the target GameObject (by instanceId, path, or name).")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -301,8 +301,14 @@ private static string TypeText(Type type)
case ResponseCallTool response:
if (response.StructuredContent == null) return null;
var node = response.StructuredContent is JsonObject o && o.Count == 1 && o.ContainsKey("result") ? o["result"] : response.StructuredContent;
var json = response.StructuredContent.ToJsonString();
response.StructuredContent = null;
response.Content = new List<ContentBlock> { Text(_compact.Render(node)) };
// The rendered data replaces only the JSON copy of that data; every other block the tool returned (an
// image, audio, a resource, a caption) still reaches the agent, as it does without the binding.
var content = new List<ContentBlock> { Text(_compact.Render(node)) };
if (response.Content != null)
content.AddRange(response.Content.Where(c => !IsDataJson(c, json)));
response.Content = content;
return response;
case string s:
return ResponseCallTool.Success(s);
Expand Down Expand Up @@ -343,6 +349,11 @@ internal string Show(QueryResult r)
return AgentFormat.Render(r, OutputFormat.Table);
}

/// <summary>The text block McpPlugin adds next to structured content (its JSON, for clients without structured content).</summary>
private static bool IsDataJson(ContentBlock block, string json) =>
block.Type == com.IvanMurzak.McpPlugin.Common.Consts.ContentType.Text
&& (block.MimeType == com.IvanMurzak.McpPlugin.Common.Consts.MimeType.TextJson || block.Text == json);

private static ContentBlock Text(string text) => new ContentBlock { Type = com.IvanMurzak.McpPlugin.Common.Consts.ContentType.Text, Text = text };

/// <summary>csharp-exec's result: "System.Int32: 42"; nested fields / properties as compact text.</summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using System.Text.Json.Nodes;
using System.Threading;
using com.IvanMurzak.McpPlugin;
using com.IvanMurzak.McpPlugin.Common;
using com.IvanMurzak.McpPlugin.Common.Model;
using com.IvanMurzak.Unity.MCP.Editor.Rql.ToolFormat;
using com.IvanMurzak.Unity.MCP.Editor.Tests.Utils;
Expand All @@ -26,11 +27,21 @@ namespace com.IvanMurzak.Unity.MCP.Editor.Tests
/// </summary>
public class RunToolRqlResultTests
{
private static (ResponseCallTool result, string text, JsonNode? data) Run(string method)
/// <summary>A tool over a static method of <paramref name="type"/>, under the RQL data layer.</summary>
private static RunTool RqlTool(System.Type type, string method)
{
UnityMcpPluginEditor.InitSingletonIfNeeded();
var runTool = RunTool.CreateFromStaticMethod(UnityMcpPluginEditor.Instance.Reflector!, null, "rql-result", typeof(TestReturnTypeMethods).GetMethod(method)!);
var runTool = RunTool.CreateFromStaticMethod(UnityMcpPluginEditor.Instance.Reflector!, null, "rql-result", type.GetMethod(method)!);
runTool.Binding = RqlToolBinding.Instance;
return runTool;
}

private static ResponseCallTool Call(System.Type type, string method) =>
RqlTool(type, method).Run("request", CancellationToken.None).Result;

private static (ResponseCallTool result, string text, JsonNode? data) Run(string method)
{
var runTool = RqlTool(typeof(TestReturnTypeMethods), method);
var result = runTool.Run("request", CancellationToken.None).Result;
Assert.AreEqual(ResponseStatus.Success, result.Status, result.GetMessage());
Assert.IsNull(result.StructuredContent, "RQL results are text, not structured content");
Expand All @@ -53,10 +64,7 @@ public void ScalarsAndUnityStructsAreTheirRqlText(string method, string expected
[Test]
public void NullIsSuccessWithoutAValue()
{
UnityMcpPluginEditor.InitSingletonIfNeeded();
var runTool = RunTool.CreateFromStaticMethod(UnityMcpPluginEditor.Instance.Reflector!, null, "rql-result", typeof(TestReturnTypeMethods).GetMethod(nameof(TestReturnTypeMethods.ReturnNull))!);
runTool.Binding = RqlToolBinding.Instance;
Assert.AreEqual(ResponseStatus.Success, runTool.Run("request", CancellationToken.None).Result.Status);
Assert.AreEqual(ResponseStatus.Success, Call(typeof(TestReturnTypeMethods), nameof(TestReturnTypeMethods.ReturnNull)).Status);
}

[Test]
Expand Down Expand Up @@ -113,5 +121,48 @@ public void DictionariesOfObjectsAreWrittenOut()
[Test]
public void AResponseCallToolPassesThrough() =>
Assert.AreEqual("Custom Response", Run(nameof(TestReturnTypeMethods.ReturnResponseCallTool)).text);

// A tool that returns data, a caption and an image: the data becomes RQL text, and the caption and the image still
// reach the agent, as they do without the binding.
[Test]
public void AnImageNextToStructuredContentIsKept()
{
var result = Call(typeof(ImageResultMethods), nameof(ImageResultMethods.ImageWithData));
Assert.AreEqual(ResponseStatus.Success, result.Status, result.GetMessage());
Assert.IsNull(result.StructuredContent, "RQL results are text, not structured content");
CollectionAssert.AreEqual(ImageResultMethods.Png, ToolResults.PngImage(result));
var texts = result.Content.Where(c => c.Type == Consts.ContentType.Text).Select(c => c.Text!).ToList();
Assert.AreEqual(2, texts.Count, "the data as RQL text, then the caption: " + string.Join(" / ", texts));
StringAssert.IsMatch(@"width\W+4\b", texts[0]);
StringAssert.IsMatch(@"height\W+5\b", texts[0]);
StringAssert.DoesNotContain("{\"", texts[0], "RQL text, not the JSON of the data");
Assert.AreEqual(ImageResultMethods.Caption, texts[1]);
}

[Test]
public void AnImageWithoutStructuredContentPassesUnchanged()
{
var result = Call(typeof(ImageResultMethods), nameof(ImageResultMethods.ImageOnly));
Assert.AreEqual(ResponseStatus.Success, result.Status, result.GetMessage());
Assert.AreEqual(2, result.Content.Count, result.GetMessage());
Assert.AreEqual(Consts.ContentType.Text, result.Content[0].Type);
Assert.AreEqual(ImageResultMethods.Caption, result.Content[0].Text);
CollectionAssert.AreEqual(ImageResultMethods.Png, ToolResults.PngImage(result));
}

public static class ImageResultMethods
{
public const string Caption = "a test image";
public static readonly byte[] Png = ScreenshotSavePathTests.TinyPng;

public static ResponseCallTool ImageOnly() => ResponseCallTool.Image(Png, Consts.MimeType.ImagePng, Caption);

public static ResponseCallTool ImageWithData()
{
var response = ImageOnly();
response.StructuredContent = new JsonObject { ["result"] = new JsonObject { ["width"] = 4, ["height"] = 5 } };
return response;
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
┌──────────────────────────────────────────────────────────────────┐
│ Author: Ivan Murzak (https://github.com/IvanMurzak) │
│ Repository: GitHub (https://github.com/IvanMurzak/Unity-MCP) │
│ Copyright (c) 2026 Ivan Murzak │
│ Licensed under the Apache License, Version 2.0. │
│ See the LICENSE file in the project root for more information. │
└──────────────────────────────────────────────────────────────────┘
*/

#nullable enable
using System.Linq;
using com.IvanMurzak.McpPlugin;
using com.IvanMurzak.McpPlugin.Common.Model;
using com.IvanMurzak.Unity.MCP.Editor.API;
using com.IvanMurzak.Unity.MCP.Editor.Rql.ToolFormat;
using com.IvanMurzak.Unity.MCP.Editor.Tests.Utils;
using NUnit.Framework;
using UnityEngine;

namespace com.IvanMurzak.Unity.MCP.Editor.Tests
{
/// <summary>
/// What the agent receives from a screenshot tool called through the tool manager, in each data layer: an MCP
/// <c>image</c> content block with a PNG, not text. Both layers run in every suite run (the binding is switched here),
/// so the RQL layer cannot drop the image without the Json layer noticing, or the reverse.
/// </summary>
[RequiresGraphicsDevice]
public class ScreenshotImageResultTests : BaseTest
{
const string Target = "ImageResultCube";

IToolBinding? _savedBinding;

static IToolManager Tools => UnityMcpPluginEditor.Instance.Tools!;

[SetUp]
public void CreateScene()
{
UnityMcpPluginEditor.InitSingletonIfNeeded();
_savedBinding = Tools.ToolBinding;

var camera = new GameObject("ImageResultCamera").AddComponent<Camera>();
camera.transform.position = new Vector3(0, 0, -5);
var light = new GameObject("ImageResultLight").AddComponent<Light>();
light.type = LightType.Directional;
GameObject.CreatePrimitive(PrimitiveType.Cube).name = Target;
}

[TearDown]
public void RestoreBinding() => Tools.ToolBinding = _savedBinding;

[TestCase("Json")]
[TestCase("Rql")]
public void ScreenshotCamera_ReturnsAPngImageBlock(string layer) =>
AssertPngImage(Call(layer, Tool_Screenshot.ScreenshotCameraToolId, @"{ ""width"": 64, ""height"": 48 }"));

[TestCase("Json")]
[TestCase("Rql")]
public void ScreenshotIsolated_ReturnsAPngImageBlock(string layer)
{
// A GameObjectRef in each layer's own argument format: JSON in the Json layer, RQL text in the RQL one.
var target = layer == "Rql"
? $@"""unity.find(\""{Target}\"")"""
: $@"{{ ""name"": ""{Target}"" }}";
AssertPngImage(Call(layer, Tool_Screenshot.ScreenshotIsolatedToolId, $@"{{ ""gameObjectRef"": {target}, ""resolution"": 64 }}"));
}

ResponseCallTool Call(string layer, string tool, string json)
{
// Apply prebuilds the RQL signatures on this (main) thread, as the plugin does, before the binding is installed.
RqlToolBinding.Apply(Tools, layer == "Rql" ? ToolPresentationFormat.Rql : ToolPresentationFormat.Json, RqlToolBinding.Instance.Escaping);
return RunTool(tool, json).Value!;
}

static void AssertPngImage(ResponseCallTool result) =>
CollectionAssert.AreEqual(new byte[] { 0x89, 0x50, 0x4E, 0x47 }, ToolResults.PngImage(result).Take(4).ToArray(), "the image data is a PNG");
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,10 @@ public void OldNameRunsTheSameCodeHidden()
#pragma warning restore CS0618
Assert.AreEqual(Tool_Script.CSharpExecToolId, UnityMcpPlugin.CurrentToolName(oldName));
Assert.IsFalse(Plugin.IsToolVisible(oldName));
// The MCP server's tools/list leaves out every tool the plugin lists with Visible = false.
var listed = Plugin.RunListTool(new RequestListTool()).Result.Value!;
Assert.IsFalse(listed.Single(t => t.Name == oldName).Visible, "script-execute is not in an MCP client's tools/list");
Assert.AreEqual(Plugin.IsToolVisible(Tool_Script.CSharpExecToolId), listed.Single(t => t.Name == Tool_Script.CSharpExecToolId).Visible);

var (r, text) = Call(oldName, new { csharpCode = "6 * 7" });
Assert.AreEqual(ResponseStatus.Success, r.Status, text);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using com.IvanMurzak.McpPlugin;
using com.IvanMurzak.McpPlugin.Common;
using com.IvanMurzak.McpPlugin.Common.Model;
using com.IvanMurzak.Unity.MCP.Editor.Rql.ToolFormat;
using NUnit.Framework;

namespace com.IvanMurzak.Unity.MCP.Editor.Tests.Utils
{
Expand All @@ -29,6 +31,15 @@ public static class ToolResults
{
public static bool IsRql => ToolDataLayerSetUp.Binding is RqlToolBinding;

/// <summary>The PNG of the response's one image content block (MIME image/png), as the agent receives it.</summary>
public static byte[] PngImage(ResponseCallTool response)
{
var image = response.Content.SingleOrDefault(c => c.Type == Consts.ContentType.Image);
Assert.IsNotNull(image, "an image content block reaches the agent; got: " + string.Join(", ", response.Content.Select(c => c.Type)));
Assert.AreEqual(Consts.MimeType.ImagePng, image!.MimeType);
return System.Convert.FromBase64String(image.Data ?? "");
}

/// <summary>The value wrapped as ReflectorNet's {"result": value} JSON text, for tests that parse that shape.</summary>
public static string ResultJson(ResponseCallTool response) => new JsonObject { ["result"] = Data(response)?.DeepClone() }.ToJsonString();

Expand Down
Loading
Loading