Skip to main content
Glama

load_sprite

Load a texture into a Sprite2D node within a Godot scene to display images in your game project.

Instructions

Load a sprite into a Sprite2D node

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
projectPathYesPath to the Godot project directory
scenePathYesPath to the scene file (relative to project)
nodePathYesPath to the Sprite2D node (e.g., "root/Player/Sprite2D")
texturePathYesPath to the texture file (relative to project)

Implementation Reference

  • Schema definition and registration of the load_sprite tool in the ListTools response, specifying input parameters: projectPath, scenePath, nodePath, texturePath.
    name: 'load_sprite',
    description: 'Load a sprite into a Sprite2D node',
    inputSchema: {
      type: 'object',
      properties: {
        projectPath: {
          type: 'string',
          description: 'Path to the Godot project directory',
        },
        scenePath: {
          type: 'string',
          description: 'Path to the scene file (relative to project)',
        },
        nodePath: {
          type: 'string',
          description: 'Path to the Sprite2D node (e.g., "root/Player/Sprite2D")',
        },
        texturePath: {
          type: 'string',
          description: 'Path to the texture file (relative to project)',
        },
      },
      required: ['projectPath', 'scenePath', 'nodePath', 'texturePath'],
    },
  • src/index.ts:953-954 (registration)
    Registration of the load_sprite tool handler in the CallToolRequestSchema switch statement, dispatching to handleLoadSprite method.
      return await this.handleLoadSprite(request.params.arguments);
    case 'export_mesh_library':
  • Core handler function for load_sprite tool. Performs input validation, file existence checks, parameter normalization, executes Godot operation 'load_sprite' via executeOperation, and handles responses/errors.
    private async handleLoadSprite(args: any) {
      // Normalize parameters to camelCase
      args = this.normalizeParameters(args);
      
      if (!args.projectPath || !args.scenePath || !args.nodePath || !args.texturePath) {
        return this.createErrorResponse(
          'Missing required parameters',
          ['Provide projectPath, scenePath, nodePath, and texturePath']
        );
      }
    
      if (
        !this.validatePath(args.projectPath) ||
        !this.validatePath(args.scenePath) ||
        !this.validatePath(args.nodePath) ||
        !this.validatePath(args.texturePath)
      ) {
        return this.createErrorResponse(
          'Invalid path',
          ['Provide valid paths without ".." or other potentially unsafe characters']
        );
      }
    
      try {
        // Check if the project directory exists and contains a project.godot file
        const projectFile = join(args.projectPath, 'project.godot');
        if (!existsSync(projectFile)) {
          return this.createErrorResponse(
            `Not a valid Godot project: ${args.projectPath}`,
            [
              'Ensure the path points to a directory containing a project.godot file',
              'Use list_projects to find valid Godot projects',
            ]
          );
        }
    
        // Check if the scene file exists
        const scenePath = join(args.projectPath, args.scenePath);
        if (!existsSync(scenePath)) {
          return this.createErrorResponse(
            `Scene file does not exist: ${args.scenePath}`,
            [
              'Ensure the scene path is correct',
              'Use create_scene to create a new scene first',
            ]
          );
        }
    
        // Check if the texture file exists
        const texturePath = join(args.projectPath, args.texturePath);
        if (!existsSync(texturePath)) {
          return this.createErrorResponse(
            `Texture file does not exist: ${args.texturePath}`,
            [
              'Ensure the texture path is correct',
              'Upload or create the texture file first',
            ]
          );
        }
    
        // Prepare parameters for the operation (already in camelCase)
        const params = {
          scenePath: args.scenePath,
          nodePath: args.nodePath,
          texturePath: args.texturePath,
        };
    
        // Execute the operation
        const { stdout, stderr } = await this.executeOperation('load_sprite', params, args.projectPath);
    
        if (stderr && stderr.includes('Failed to')) {
          return this.createErrorResponse(
            `Failed to load sprite: ${stderr}`,
            [
              'Check if the node path is correct',
              'Ensure the node is a Sprite2D, Sprite3D, or TextureRect',
              'Verify the texture file is a valid image format',
            ]
          );
        }
    
        return {
          content: [
            {
              type: 'text',
              text: `Sprite loaded successfully with texture: ${args.texturePath}\n\nOutput: ${stdout}`,
            },
          ],
        };
      } catch (error: any) {
        return this.createErrorResponse(
          `Failed to load sprite: ${error?.message || 'Unknown error'}`,
          [
            'Ensure Godot is installed correctly',
            'Check if the GODOT_PATH environment variable is set correctly',
            'Verify the project path is accessible',
          ]
        );
      }
    }
  • Helper method executeOperation used by load_sprite (and other tools) to spawn Godot headless with the operations GD script, passing 'load_sprite' operation and JSON params.
    private async executeOperation(
      operation: string,
      params: OperationParams,
      projectPath: string
    ): Promise<{ stdout: string; stderr: string }> {
      this.logDebug(`Executing operation: ${operation} in project: ${projectPath}`);
      this.logDebug(`Original operation params: ${JSON.stringify(params)}`);
    
      // Convert camelCase parameters to snake_case for Godot script
      const snakeCaseParams = this.convertCamelToSnakeCase(params);
      this.logDebug(`Converted snake_case params: ${JSON.stringify(snakeCaseParams)}`);
    
    
      // Ensure godotPath is set
      if (!this.godotPath) {
        await this.detectGodotPath();
        if (!this.godotPath) {
          throw new Error('Could not find a valid Godot executable path');
        }
      }
    
      try {
        // Serialize the snake_case parameters to a valid JSON string
        const paramsJson = JSON.stringify(snakeCaseParams);
        // Escape single quotes in the JSON string to prevent command injection
        const escapedParams = paramsJson.replace(/'/g, "'\\''");
        // On Windows, cmd.exe does not strip single quotes, so we use
        // double quotes and escape them to ensure the JSON is parsed
        // correctly by Godot.
        const isWindows = process.platform === 'win32';
        const quotedParams = isWindows
          ? `\"${paramsJson.replace(/\"/g, '\\"')}\"`
          : `'${escapedParams}'`;
    
    
        // Add debug arguments if debug mode is enabled
        const debugArgs = GODOT_DEBUG_MODE ? ['--debug-godot'] : [];
    
        // Construct the command with the operation and JSON parameters
        const cmd = [
          `"${this.godotPath}"`,
          '--headless',
          '--path',
          `"${projectPath}"`,
          '--script',
          `"${this.operationsScriptPath}"`,
          operation,
          quotedParams, // Pass the JSON string as a single argument
          ...debugArgs,
        ].join(' ');
    
        this.logDebug(`Command: ${cmd}`);
    
        const { stdout, stderr } = await execAsync(cmd);
    
        return { stdout, stderr };
      } catch (error: unknown) {
        // If execAsync throws, it still contains stdout/stderr
        if (error instanceof Error && 'stdout' in error && 'stderr' in error) {
          const execError = error as Error & { stdout: string; stderr: string };
          return {
            stdout: execError.stdout,
            stderr: execError.stderr,
          };
        }
    
        throw error;
      }
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observedv1.0.0

TDQS

C2.9/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries full responsibility for disclosing side effects. It only states that a sprite is loaded into a node, without mentioning whether this modifies the scene file, requires a saved scene, returns a value, or has any persistent effects. This lack of detail leaves significant ambiguity about the tool's actual behavior.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, focused sentence with no redundant words or unnecessary details. It is concise and front-loaded, clearly stating the core action without distraction.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the lack of an output schema and the mutation-like nature of the action, the description is insufficiently contextual. It does not explain what 'load' means operationally (e.g., sets a texture property, replaces an existing asset), whether the scene must be saved, or what the expected result is. This leaves gaps for an agent attempting to use the tool correctly.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%—all four parameters have individual descriptions explaining their meaning (e.g., 'Path to the texture file (relative to project)'). The tool description itself adds no extra parameter information, so the baseline score of 3 applies.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action (load) and the target resource (a sprite into a Sprite2D node), making the tool's primary purpose understandable. It does not explicitly contrast with sibling tools like add_node, but the specific action is distinct enough for basic identification.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives, such as add_node or other scene modification tools. It omits any contextual conditions or prerequisites, leaving the agent to infer appropriate usage solely from the action description.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.