using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Newtonsoft.Json.Linq;
using UnityEditor;
using UnityEngine;
using MCPForUnity.Editor.Helpers; // For Response class
using static MCPForUnity.Editor.Tools.ManageGameObject;
#if UNITY_6000_0_OR_NEWER
using PhysicsMaterialType = UnityEngine.PhysicsMaterial;
using PhysicsMaterialCombine = UnityEngine.PhysicsMaterialCombine;
#else
using PhysicsMaterialType = UnityEngine.PhysicMaterial;
using PhysicsMaterialCombine = UnityEngine.PhysicMaterialCombine;
#endif
namespace MCPForUnity.Editor.Tools
{
///
/// Handles asset management operations within the Unity project.
///
[McpForUnityTool("manage_asset", AutoRegister = false)]
public static class ManageAsset
{
// --- Main Handler ---
// Define the list of valid actions
private static readonly List ValidActions = new List
{
"import",
"create",
"modify",
"delete",
"duplicate",
"move",
"rename",
"search",
"get_info",
"create_folder",
"get_components",
};
public static object HandleCommand(JObject @params)
{
string action = @params["action"]?.ToString().ToLower();
if (string.IsNullOrEmpty(action))
{
return new ErrorResponse("Action parameter is required.");
}
// Check if the action is valid before switching
if (!ValidActions.Contains(action))
{
string validActionsList = string.Join(", ", ValidActions);
return new ErrorResponse(
$"Unknown action: '{action}'. Valid actions are: {validActionsList}"
);
}
// Common parameters
string path = @params["path"]?.ToString();
// Coerce string JSON to JObject for 'properties' if provided as a JSON string
var propertiesToken = @params["properties"];
if (propertiesToken != null && propertiesToken.Type == JTokenType.String)
{
try
{
var parsed = JObject.Parse(propertiesToken.ToString());
@params["properties"] = parsed;
}
catch (Exception e)
{
Debug.LogWarning($"[ManageAsset] Could not parse 'properties' JSON string: {e.Message}");
}
}
try
{
switch (action)
{
case "import":
// Note: Unity typically auto-imports. This might re-import or configure import settings.
return ReimportAsset(path, @params["properties"] as JObject);
case "create":
return CreateAsset(@params);
case "modify":
var properties = @params["properties"] as JObject;
return ModifyAsset(path, properties);
case "delete":
return DeleteAsset(path);
case "duplicate":
return DuplicateAsset(path, @params["destination"]?.ToString());
case "move": // Often same as rename if within Assets/
case "rename":
return MoveOrRenameAsset(path, @params["destination"]?.ToString());
case "search":
return SearchAssets(@params);
case "get_info":
return GetAssetInfo(
path,
@params["generatePreview"]?.ToObject() ?? false
);
case "create_folder": // Added specific action for clarity
return CreateFolder(path);
case "get_components":
return GetComponentsFromAsset(path);
default:
// This error message is less likely to be hit now, but kept here as a fallback or for potential future modifications.
string validActionsListDefault = string.Join(", ", ValidActions);
return new ErrorResponse(
$"Unknown action: '{action}'. Valid actions are: {validActionsListDefault}"
);
}
}
catch (Exception e)
{
Debug.LogError($"[ManageAsset] Action '{action}' failed for path '{path}': {e}");
return new ErrorResponse(
$"Internal error processing action '{action}' on '{path}': {e.Message}"
);
}
}
// --- Action Implementations ---
private static object ReimportAsset(string path, JObject properties)
{
if (string.IsNullOrEmpty(path))
return new ErrorResponse("'path' is required for reimport.");
string fullPath = AssetPathUtility.SanitizeAssetPath(path);
if (!AssetExists(fullPath))
return new ErrorResponse($"Asset not found at path: {fullPath}");
try
{
// TODO: Apply importer properties before reimporting?
// This is complex as it requires getting the AssetImporter, casting it,
// applying properties via reflection or specific methods, saving, then reimporting.
if (properties != null && properties.HasValues)
{
Debug.LogWarning(
"[ManageAsset.Reimport] Modifying importer properties before reimport is not fully implemented yet."
);
// AssetImporter importer = AssetImporter.GetAtPath(fullPath);
// if (importer != null) { /* Apply properties */ AssetDatabase.WriteImportSettingsIfDirty(fullPath); }
}
AssetDatabase.ImportAsset(fullPath, ImportAssetOptions.ForceUpdate);
// AssetDatabase.Refresh(); // Usually ImportAsset handles refresh
return new SuccessResponse($"Asset '{fullPath}' reimported.", GetAssetData(fullPath));
}
catch (Exception e)
{
return new ErrorResponse($"Failed to reimport asset '{fullPath}': {e.Message}");
}
}
private static object CreateAsset(JObject @params)
{
string path = @params["path"]?.ToString();
string assetType =
@params["assetType"]?.ToString()
?? @params["asset_type"]?.ToString(); // tolerate snake_case payloads from batched commands
JObject properties = @params["properties"] as JObject;
if (string.IsNullOrEmpty(path))
return new ErrorResponse("'path' is required for create.");
if (string.IsNullOrEmpty(assetType))
return new ErrorResponse("'assetType' is required for create.");
string fullPath = AssetPathUtility.SanitizeAssetPath(path);
string directory = Path.GetDirectoryName(fullPath);
// Ensure directory exists
if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), directory)))
{
Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), directory));
AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport); // Make sure Unity knows about the new folder
}
if (AssetExists(fullPath))
return new ErrorResponse($"Asset already exists at path: {fullPath}");
try
{
UnityEngine.Object newAsset = null;
string lowerAssetType = assetType.ToLowerInvariant();
// Handle common asset types
if (lowerAssetType == "folder")
{
return CreateFolder(path); // Use dedicated method
}
else if (lowerAssetType == "material")
{
var requested = properties?["shader"]?.ToString();
Shader shader = RenderPipelineUtility.ResolveShader(requested);
if (shader == null)
return new ErrorResponse($"Could not find a project-compatible shader (requested: '{requested ?? "none"}'). Consider installing URP/HDRP or provide an explicit shader path.");
var mat = new Material(shader);
if (properties != null)
{
JObject propertiesForApply = properties;
if (propertiesForApply["shader"] != null)
{
propertiesForApply = (JObject)properties.DeepClone();
propertiesForApply.Remove("shader");
}
if (propertiesForApply.HasValues)
{
MaterialOps.ApplyProperties(mat, propertiesForApply, ManageGameObject.InputSerializer);
}
}
AssetDatabase.CreateAsset(mat, fullPath);
newAsset = mat;
}
else if (lowerAssetType == "physicsmaterial")
{
PhysicsMaterialType pmat = new PhysicsMaterialType();
if (properties != null)
ApplyPhysicsMaterialProperties(pmat, properties);
AssetDatabase.CreateAsset(pmat, fullPath);
newAsset = pmat;
}
else if (lowerAssetType == "prefab")
{
// Creating prefabs usually involves saving an existing GameObject hierarchy.
// A common pattern is to create an empty GameObject, configure it, and then save it.
return new ErrorResponse(
"Creating prefabs programmatically usually requires a source GameObject. Use manage_gameobject to create/configure, then save as prefab via a separate mechanism or future enhancement."
);
// Example (conceptual):
// GameObject source = GameObject.Find(properties["sourceGameObject"].ToString());
// if(source != null) PrefabUtility.SaveAsPrefabAsset(source, fullPath);
}
// TODO: Add more asset types (Animation Controller, Scene, etc.)
else
{
// Generic creation attempt (might fail or create empty files)
// For some types, just creating the file might be enough if Unity imports it.
// File.Create(Path.Combine(Directory.GetCurrentDirectory(), fullPath)).Close();
// AssetDatabase.ImportAsset(fullPath); // Let Unity try to import it
// newAsset = AssetDatabase.LoadAssetAtPath(fullPath);
return new ErrorResponse(
$"Creation for asset type '{assetType}' is not explicitly supported yet. Supported: Folder, Material, PhysicsMaterial."
);
}
if (
newAsset == null
&& !Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), fullPath))
) // Check if it wasn't a folder and asset wasn't created
{
return new ErrorResponse(
$"Failed to create asset '{assetType}' at '{fullPath}'. See logs for details."
);
}
AssetDatabase.SaveAssets();
// AssetDatabase.Refresh(); // CreateAsset often handles refresh
return new SuccessResponse(
$"Asset '{fullPath}' created successfully.",
GetAssetData(fullPath)
);
}
catch (Exception e)
{
return new ErrorResponse($"Failed to create asset at '{fullPath}': {e.Message}");
}
}
private static object CreateFolder(string path)
{
if (string.IsNullOrEmpty(path))
return new ErrorResponse("'path' is required for create_folder.");
string fullPath = AssetPathUtility.SanitizeAssetPath(path);
string parentDir = Path.GetDirectoryName(fullPath);
string folderName = Path.GetFileName(fullPath);
if (AssetExists(fullPath))
{
// Check if it's actually a folder already
if (AssetDatabase.IsValidFolder(fullPath))
{
return new SuccessResponse(
$"Folder already exists at path: {fullPath}",
GetAssetData(fullPath)
);
}
else
{
return new ErrorResponse(
$"An asset (not a folder) already exists at path: {fullPath}"
);
}
}
try
{
// Ensure parent exists
if (!string.IsNullOrEmpty(parentDir) && !AssetDatabase.IsValidFolder(parentDir))
{
// Recursively create parent folders if needed (AssetDatabase handles this internally)
// Or we can do it manually: Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), parentDir)); AssetDatabase.Refresh();
}
string guid = AssetDatabase.CreateFolder(parentDir, folderName);
if (string.IsNullOrEmpty(guid))
{
return new ErrorResponse(
$"Failed to create folder '{fullPath}'. Check logs and permissions."
);
}
// AssetDatabase.Refresh(); // CreateFolder usually handles refresh
return new SuccessResponse(
$"Folder '{fullPath}' created successfully.",
GetAssetData(fullPath)
);
}
catch (Exception e)
{
return new ErrorResponse($"Failed to create folder '{fullPath}': {e.Message}");
}
}
private static object ModifyAsset(string path, JObject properties)
{
if (string.IsNullOrEmpty(path))
return new ErrorResponse("'path' is required for modify.");
if (properties == null || !properties.HasValues)
return new ErrorResponse("'properties' are required for modify.");
string fullPath = AssetPathUtility.SanitizeAssetPath(path);
if (!AssetExists(fullPath))
return new ErrorResponse($"Asset not found at path: {fullPath}");
try
{
UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(
fullPath
);
if (asset == null)
return new ErrorResponse($"Failed to load asset at path: {fullPath}");
bool modified = false; // Flag to track if any changes were made
// --- NEW: Handle GameObject / Prefab Component Modification ---
if (asset is GameObject gameObject)
{
// Iterate through the properties JSON: keys are component names, values are properties objects for that component
foreach (var prop in properties.Properties())
{
string componentName = prop.Name; // e.g., "Collectible"
// Check if the value associated with the component name is actually an object containing properties
if (
prop.Value is JObject componentProperties
&& componentProperties.HasValues
) // e.g., {"bobSpeed": 2.0}
{
// Resolve component type via ComponentResolver, then fetch by Type
Component targetComponent = null;
bool resolved = ComponentResolver.TryResolve(componentName, out var compType, out var compError);
if (resolved)
{
targetComponent = gameObject.GetComponent(compType);
}
// Only warn about resolution failure if component also not found
if (targetComponent == null && !resolved)
{
Debug.LogWarning(
$"[ManageAsset.ModifyAsset] Failed to resolve component '{componentName}' on '{gameObject.name}': {compError}"
);
}
if (targetComponent != null)
{
// Apply the nested properties (e.g., bobSpeed) to the found component instance
// Use |= to ensure 'modified' becomes true if any component is successfully modified
modified |= ApplyObjectProperties(
targetComponent,
componentProperties
);
}
else
{
// Log a warning if a specified component couldn't be found
Debug.LogWarning(
$"[ManageAsset.ModifyAsset] Component '{componentName}' not found on GameObject '{gameObject.name}' in asset '{fullPath}'. Skipping modification for this component."
);
}
}
else
{
// Log a warning if the structure isn't {"ComponentName": {"prop": value}}
// We could potentially try to apply this property directly to the GameObject here if needed,
// but the primary goal is component modification.
Debug.LogWarning(
$"[ManageAsset.ModifyAsset] Property '{prop.Name}' for GameObject modification should have a JSON object value containing component properties. Value was: {prop.Value.Type}. Skipping."
);
}
}
// Note: 'modified' is now true if ANY component property was successfully changed.
}
// --- End NEW ---
// --- Existing logic for other asset types (now as else-if) ---
// Example: Modifying a Material
else if (asset is Material material)
{
// Apply properties directly to the material. If this modifies, it sets modified=true.
// Use |= in case the asset was already marked modified by previous logic (though unlikely here)
modified |= MaterialOps.ApplyProperties(material, properties, ManageGameObject.InputSerializer);
}
// Example: Modifying a ScriptableObject (Use manage_scriptable_object instead!)
else if (asset is ScriptableObject so)
{
// Deprecated: Prefer manage_scriptable_object for robust patching.
// Kept for simple property setting fallback on existing assets if manage_scriptable_object isn't used.
modified |= ApplyObjectProperties(so, properties);
}
// Example: Modifying TextureImporter settings
else if (asset is Texture)
{
AssetImporter importer = AssetImporter.GetAtPath(fullPath);
if (importer is TextureImporter textureImporter)
{
bool importerModified = ApplyObjectProperties(textureImporter, properties);
if (importerModified)
{
// Importer settings need saving and reimporting
AssetDatabase.WriteImportSettingsIfDirty(fullPath);
AssetDatabase.ImportAsset(fullPath, ImportAssetOptions.ForceUpdate); // Reimport to apply changes
modified = true; // Mark overall operation as modified
}
}
else
{
Debug.LogWarning($"Could not get TextureImporter for {fullPath}.");
}
}
// TODO: Add modification logic for other common asset types (Models, AudioClips importers, etc.)
else // Fallback for other asset types OR direct properties on non-GameObject assets
{
// This block handles non-GameObject/Material/ScriptableObject/Texture assets.
// Attempts to apply properties directly to the asset itself.
Debug.LogWarning(
$"[ManageAsset.ModifyAsset] Asset type '{asset.GetType().Name}' at '{fullPath}' is not explicitly handled for component modification. Attempting generic property setting on the asset itself."
);
modified |= ApplyObjectProperties(asset, properties);
}
// --- End Existing Logic ---
// Check if any modification happened (either component or direct asset modification)
if (modified)
{
// Mark the asset as dirty (important for prefabs/SOs) so Unity knows to save it.
EditorUtility.SetDirty(asset);
// Save all modified assets to disk.
AssetDatabase.SaveAssets();
// Refresh might be needed in some edge cases, but SaveAssets usually covers it.
// AssetDatabase.Refresh();
return new SuccessResponse(
$"Asset '{fullPath}' modified successfully.",
GetAssetData(fullPath)
);
}
else
{
// If no changes were made (e.g., component not found, property names incorrect, value unchanged), return a success message indicating nothing changed.
return new SuccessResponse(
$"No applicable or modifiable properties found for asset '{fullPath}'. Check component names, property names, and values.",
GetAssetData(fullPath)
);
// Previous message: return new SuccessResponse($"No applicable properties found to modify for asset '{fullPath}'.", GetAssetData(fullPath));
}
}
catch (Exception e)
{
// Log the detailed error internally
Debug.LogError($"[ManageAsset] Action 'modify' failed for path '{path}': {e}");
// Return a user-friendly error message
return new ErrorResponse($"Failed to modify asset '{fullPath}': {e.Message}");
}
}
private static object DeleteAsset(string path)
{
if (string.IsNullOrEmpty(path))
return new ErrorResponse("'path' is required for delete.");
string fullPath = AssetPathUtility.SanitizeAssetPath(path);
if (!AssetExists(fullPath))
return new ErrorResponse($"Asset not found at path: {fullPath}");
try
{
bool success = AssetDatabase.DeleteAsset(fullPath);
if (success)
{
// AssetDatabase.Refresh(); // DeleteAsset usually handles refresh
return new SuccessResponse($"Asset '{fullPath}' deleted successfully.");
}
else
{
// This might happen if the file couldn't be deleted (e.g., locked)
return new ErrorResponse(
$"Failed to delete asset '{fullPath}'. Check logs or if the file is locked."
);
}
}
catch (Exception e)
{
return new ErrorResponse($"Error deleting asset '{fullPath}': {e.Message}");
}
}
private static object DuplicateAsset(string path, string destinationPath)
{
if (string.IsNullOrEmpty(path))
return new ErrorResponse("'path' is required for duplicate.");
string sourcePath = AssetPathUtility.SanitizeAssetPath(path);
if (!AssetExists(sourcePath))
return new ErrorResponse($"Source asset not found at path: {sourcePath}");
string destPath;
if (string.IsNullOrEmpty(destinationPath))
{
// Generate a unique path if destination is not provided
destPath = AssetDatabase.GenerateUniqueAssetPath(sourcePath);
}
else
{
destPath = AssetPathUtility.SanitizeAssetPath(destinationPath);
if (AssetExists(destPath))
return new ErrorResponse($"Asset already exists at destination path: {destPath}");
// Ensure destination directory exists
EnsureDirectoryExists(Path.GetDirectoryName(destPath));
}
try
{
bool success = AssetDatabase.CopyAsset(sourcePath, destPath);
if (success)
{
// AssetDatabase.Refresh();
return new SuccessResponse(
$"Asset '{sourcePath}' duplicated to '{destPath}'.",
GetAssetData(destPath)
);
}
else
{
return new ErrorResponse(
$"Failed to duplicate asset from '{sourcePath}' to '{destPath}'."
);
}
}
catch (Exception e)
{
return new ErrorResponse($"Error duplicating asset '{sourcePath}': {e.Message}");
}
}
private static object MoveOrRenameAsset(string path, string destinationPath)
{
if (string.IsNullOrEmpty(path))
return new ErrorResponse("'path' is required for move/rename.");
if (string.IsNullOrEmpty(destinationPath))
return new ErrorResponse("'destination' path is required for move/rename.");
string sourcePath = AssetPathUtility.SanitizeAssetPath(path);
string destPath = AssetPathUtility.SanitizeAssetPath(destinationPath);
if (!AssetExists(sourcePath))
return new ErrorResponse($"Source asset not found at path: {sourcePath}");
if (AssetExists(destPath))
return new ErrorResponse(
$"An asset already exists at the destination path: {destPath}"
);
// Ensure destination directory exists
EnsureDirectoryExists(Path.GetDirectoryName(destPath));
try
{
// Validate will return an error string if failed, null if successful
string error = AssetDatabase.ValidateMoveAsset(sourcePath, destPath);
if (!string.IsNullOrEmpty(error))
{
return new ErrorResponse(
$"Failed to move/rename asset from '{sourcePath}' to '{destPath}': {error}"
);
}
string guid = AssetDatabase.MoveAsset(sourcePath, destPath);
if (!string.IsNullOrEmpty(guid)) // MoveAsset returns the new GUID on success
{
// AssetDatabase.Refresh(); // MoveAsset usually handles refresh
return new SuccessResponse(
$"Asset moved/renamed from '{sourcePath}' to '{destPath}'.",
GetAssetData(destPath)
);
}
else
{
// This case might not be reachable if ValidateMoveAsset passes, but good to have
return new ErrorResponse(
$"MoveAsset call failed unexpectedly for '{sourcePath}' to '{destPath}'."
);
}
}
catch (Exception e)
{
return new ErrorResponse($"Error moving/renaming asset '{sourcePath}': {e.Message}");
}
}
private static object SearchAssets(JObject @params)
{
string searchPattern = @params["searchPattern"]?.ToString();
string filterType = @params["filterType"]?.ToString();
string pathScope = @params["path"]?.ToString(); // Use path as folder scope
string filterDateAfterStr = @params["filterDateAfter"]?.ToString();
int pageSize = @params["pageSize"]?.ToObject() ?? 50; // Default page size
int pageNumber = @params["pageNumber"]?.ToObject() ?? 1; // Default page number (1-based)
bool generatePreview = @params["generatePreview"]?.ToObject() ?? false;
List searchFilters = new List();
if (!string.IsNullOrEmpty(searchPattern))
searchFilters.Add(searchPattern);
if (!string.IsNullOrEmpty(filterType))
searchFilters.Add($"t:{filterType}");
string[] folderScope = null;
if (!string.IsNullOrEmpty(pathScope))
{
folderScope = new string[] { AssetPathUtility.SanitizeAssetPath(pathScope) };
if (!AssetDatabase.IsValidFolder(folderScope[0]))
{
// Maybe the user provided a file path instead of a folder?
// We could search in the containing folder, or return an error.
Debug.LogWarning(
$"Search path '{folderScope[0]}' is not a valid folder. Searching entire project."
);
folderScope = null; // Search everywhere if path isn't a folder
}
}
DateTime? filterDateAfter = null;
if (!string.IsNullOrEmpty(filterDateAfterStr))
{
if (
DateTime.TryParse(
filterDateAfterStr,
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
out DateTime parsedDate
)
)
{
filterDateAfter = parsedDate;
}
else
{
Debug.LogWarning(
$"Could not parse filterDateAfter: '{filterDateAfterStr}'. Expected ISO 8601 format."
);
}
}
try
{
string[] guids = AssetDatabase.FindAssets(
string.Join(" ", searchFilters),
folderScope
);
List