Adding Custom Tools to MCP for Unity
MCP for Unity makes it easy to extend your AI assistant with custom capabilities. Using C# attributes and reflection, the system automatically discovers and registers your tools—no manual configuration needed.
This guide will walk you through creating your own tools, from simple synchronous operations to complex long-running tasks that survive Unity's domain reloads.
Project-specific startup instructions
To supplement the built-in MCP guidance without adding a tool, pass an explicit file when launching the Python server:
mcp-for-unity --instructions-file "C:/Projects/MyProject/mcp-instructions.txt"
Relative paths resolve from the server's working directory. The regular file must contain nonblank UTF-8 text, contain no NUL characters, and be at most 32,768 bytes. Its contents are sent to connected MCP clients in a labeled appendix after the built-in instructions, so use project guidance suitable for those clients. The file is read once at startup; restart the server after editing it. Invalid requested files prevent startup.
This option does not discover or watch files. It does not change tool availability, authorization, consent, transport enforcement, or the client's own instruction hierarchy. Omitting the option preserves the default instructions. It does not register dynamic MCP prompts.
Quick Start Guide
Let's get you up and running with your first custom tool.
Step 1: Create Your Tool Handler
First, create a C# file in any Editor/ folder within your Unity project. The Editor folder is crucial—we scan Editor assemblies for tools, so placing your code elsewhere means it won't be discovered.
Each tool is a static class with two key ingredients:
- The
[McpForUnityTool]attribute that tells the system "Hey, I'm a tool!" - A
HandleCommand(JObject)method that does the actual work
You can also define a nested Parameters class with [ToolParameter] attributes. This gives your AI assistant helpful descriptions and lets it know which parameters are required.
using Newtonsoft.Json.Linq;
using MCPForUnity.Editor.Helpers;
using MCPForUnity.Editor.Tools;
namespace MyProject.Editor.CustomTools
{
[McpForUnityTool("my_custom_tool")]
public static class MyCustomTool
{
public class Parameters
{
[ToolParameter("Value to process")]
public string param1 { get; set; }
[ToolParameter("Optional integer payload", Required = false)]
public int? param2 { get; set; }
}
public static object HandleCommand(JObject @params)
{
var parameters = PropertyConversion.ConvertTo<Parameters>(@params);
if (string.IsNullOrEmpty(parameters.param1))
{
return new ErrorResponse("param1 is required");
}
DoSomethingAmazing(parameters.param1, parameters.param2);
return new SuccessResponse("Custom tool executed successfully!", new
{
parameters.param1,
parameters.param2
});
}
private static void DoSomethingAmazing(string param1, int? param2)
{
// Your implementation
}
}
}
Validate typed values
Use PropertyConversion.ConvertTo<T>(token) for typed objects, arrays and nested properties, or token.ReadScalar<T>() for a scalar. These readers reject boolean/number substitutions, fractional integers, overflow and nonfinite ordinary numbers. ReadScalar<int?>() and ReadScalar<bool?>() preserve missing/null optional values; use ?? to supply a default. Handle validation exceptions with your normal error response before applying changes.
The server validates declared custom-tool scalar parameters for both global tools and execute_custom_tool. Descriptor defaults are strings: integer defaults must represent integers and boolean defaults must be "true" or "false". Malformed descriptors are reported without dropping other valid tools. Parameter dictionaries with no declared schema remain the handler's responsibility, including calls through batch_execute.
Step 2: Refresh Your MCP Client
Once you've created your tool, you'll need to let your AI assistant know about it. While the MCP server can dynamically register new tools, not all clients pick up these changes automatically.
The easiest approach: Disconnect and reconnect to the MCP server in your client. This forces a fresh tool discovery.
If that doesn't work: Some clients (like Windsurf) may need you to remove and reconfigure the MCP for Unity server entirely. It's a bit more work, but it guarantees your new tools will appear.
Step 3: List and Call Your Tool from the CLI
If you want to use the CLI directly, list custom tools for the active Unity project:
unity-mcp tool list
unity-mcp custom_tool list
Then call your tool by name:
unity-mcp editor custom-tool "my_custom_tool"
unity-mcp editor custom-tool "my_custom_tool" --params '{"param1":"value"}'
Complete Example: Screenshot Tool
C# Handler (Assets/Editor/ScreenShots/CaptureScreenshotTool.cs)
using System.IO;
using Newtonsoft.Json.Linq;
using UnityEngine;
using MCPForUnity.Editor.Tools;
using MCPForUnity.Editor.Helpers;
namespace MyProject.Editor.CustomTools
{
[McpForUnityTool(
name: "capture_screenshot",
Description = "Capture screenshots in Unity, saving them as PNGs"
)]
public static class CaptureScreenshotTool
{
// Define parameters as a nested class for clarity
public class Parameters
{
[ToolParameter("Screenshot filename without extension, e.g., screenshot_01")]
public string filename { get; set; }
[ToolParameter("Width of the screenshot in pixels", Required = false)]
public int? width { get; set; }
[ToolParameter("Height of the screenshot in pixels", Required = false)]
public int? height { get; set; }
}
public static object HandleCommand(JObject @params)
{
// Parse parameters
var parameters = PropertyConversion.ConvertTo<Parameters>(@params);
if (string.IsNullOrEmpty(parameters.filename))
{
return new ErrorResponse("filename is required");
}
try
{
int width = parameters.width ?? Screen.width;
int height = parameters.height ?? Screen.height;
string absolutePath = Path.Combine(Application.dataPath, "Screenshots",
parameters.filename + ".png");
Directory.CreateDirectory(Path.GetDirectoryName(absolutePath));
// Find camera
Camera camera = Camera.main ?? Object.FindFirstObjectByType<Camera>();
if (camera == null)
{
return new ErrorResponse("No camera found in the scene");
}
// Capture screenshot
RenderTexture rt = new RenderTexture(width, height, 24);
camera.targetTexture = rt;
camera.Render();
RenderTexture.active = rt;
Texture2D screenshot = new Texture2D(width, height, TextureFormat.RGB24, false);
screenshot.ReadPixels(new Rect(0, 0, width, height), 0, 0);
screenshot.Apply();
// Cleanup
camera.targetTexture = null;
RenderTexture.active = null;
Object.DestroyImmediate(rt);
// Save
byte[] bytes = screenshot.EncodeToPNG();
File.WriteAllBytes(absolutePath, bytes);
Object.DestroyImmediate(screenshot);
return new SuccessResponse($"Screenshot saved to {absolutePath}", new
{
path = absolutePath,
width = width,
height = height
});
}
catch (System.Exception ex)
{
return new ErrorResponse($"Failed to capture screenshot: {ex.Message}");
}
}
}
}
Long-Running (Polled) Tools
Some operations—like running tests, baking lightmaps, or building players—take time and might even trigger Unity domain reloads. For these cases, you'll want a polled tool.
Here's how it works: Your tool starts the work and returns a "pending" signal. Behind the scenes, the Python middleware automatically polls Unity for updates until the job completes (or times out after 10 minutes).
Setting Up Polling
Mark your tool with RequiresPolling = true and specify a PollAction (typically "status"):
[McpForUnityTool(RequiresPolling = true, PollAction = "status")]
The Three Key Ingredients
-
Start the work: Return
new PendingResponse("message", pollIntervalSeconds)to acknowledge the job has started. The poll interval tells the server how long to wait between checks. -
Implement the poll action: Create a method (like
Status) that checks progress and returns_mcp_statusofpending,complete, orerror. Important: The middleware calls yourPollActionstring exactly as written—no automatic case conversion—so make sure yourHandleCommandrecognizes it. -
Separate observations from execution ownership: Keep small display state in
SessionStateif it only needs to survive an assembly reload. Restart-safe work needs an operation-owned journal and reconciliation. See Migrating legacy editor helpers;McpJobStateStoreis deprecated and is not a crash-recovery store.
Keeping a transient observation
This stores a progress display within the current Editor session. It does not start, resume, or establish ownership of a bake. After a reload, reconnect to the actual operation before reporting that it is still running. An absent observation means unknown, not permission to restart a mutation.
using System;
using UnityEditor;
using UnityEngine;
internal static class BakeObservation
{
private const string Key = "Example.BakeLightmaps.Observation";
[Serializable]
internal sealed class State
{
public float progress;
public bool completed;
}
internal static void Save(State state) => SessionState.SetString(Key, JsonUtility.ToJson(state));
internal static State Read()
{
string json = SessionState.GetString(Key, "");
return string.IsNullOrEmpty(json) ? null : JsonUtility.FromJson<State>(json);
}
internal static void Clear() => SessionState.EraseString(Key);
}
How the Polling Protocol Works
_mcp_status: "pending"tells the middleware to keep checking back._mcp_poll_interval(in seconds) controls how long to wait between polls. The server clamps this between 0.1 and 5 seconds to balance responsiveness with performance.- Null or empty responses are treated as "still working" and trigger another poll.
- Timeout protection: After 10 minutes, the server gives up and returns a timeout error along with the last response it received.
- Action routing: The initial call uses whatever action your tool expects (often implicit). Subsequent polls use your exact
PollActionstring—no automatic snake_case or camelCase conversion—so make sure yourHandleCommandswitch statement handles it correctly.