rokojori_action_library/Tools/mcp/Routes/WriteResourceRoute.cs

109 lines
3.1 KiB
C#
Raw Normal View History

2026-10-03 12:15:58 +00:00
#if TOOLS
using Godot;
namespace Rokojori.Tools
{
using Rokojori;
public static class WriteResourceRoute
{
public static JSONObject ToolDefinition()
{
var pathSchema = new JSONObject();
pathSchema.Set( "type", "string" );
pathSchema.Set( "description", "res:// path to write the resource to" );
var typeSchema = new JSONObject();
typeSchema.Set( "type", "string" );
typeSchema.Set( "description", "Godot class name, required only when creating a new resource at 'path'" );
var propertiesSchema = new JSONObject();
propertiesSchema.Set( "type", "object" );
propertiesSchema.Set( "description", "Property name -> JSON value map, as returned by read_resource" );
var properties = new JSONObject();
properties.Set( "path", pathSchema );
properties.Set( "type", typeSchema );
properties.Set( "properties", propertiesSchema );
var required = new JSONArray();
required.Push( "path" );
required.Push( "properties" );
var schema = new JSONObject();
schema.Set( "type", "object" );
schema.Set( "properties", properties );
schema.Set( "required", required );
var tool = new JSONObject();
tool.Set( "name", "write_resource" );
tool.Set( "description", "Create or update a Resource's stored properties and save it." );
tool.Set( "inputSchema", schema );
return tool;
}
public static ToolCallOutcome Execute( JSONObject arguments )
{
var path = JsonUtil.GetStringOrNull( arguments, "path" );
var typeName = JsonUtil.GetStringOrNull( arguments, "type" );
var properties = arguments != null ? arguments.GetObject( "properties" ) : null;
if ( string.IsNullOrEmpty( path ) )
{
return ToolCallOutcome.Error( "Missing required argument: path" );
}
if ( properties == null )
{
return ToolCallOutcome.Error( "Missing required argument: properties" );
}
Resource resource = null;
if ( ResourceLoader.Exists( path, "" ) )
{
resource = ResourceLoader.Load( path );
}
if ( resource == null )
{
if ( string.IsNullOrEmpty( typeName ) )
{
return ToolCallOutcome.Error( "Resource does not exist yet at '" + path + "' - 'type' is required to create it" );
}
if ( ! ClassDB.ClassExists( typeName ) )
{
return ToolCallOutcome.Error( "Unknown class: " + typeName );
}
resource = ClassDB.Instantiate( typeName ).As<Resource>();
if ( resource == null )
{
return ToolCallOutcome.Error( "Class is not a Resource: " + typeName );
}
}
PropertyReflection.ApplyFromJson( resource, properties );
var error = ResourceSaver.Save( resource, path );
if ( error != Error.Ok )
{
return ToolCallOutcome.Error( "Failed to save resource: " + error );
}
var result = new JSONObject();
result.Set( "path", path );
result.Set( "type", resource.GetClass() );
return ToolCallOutcome.Ok( JSON.Stringify( result ) );
}
}
}
#endif