Skip to main content
Glama

godot_analyze_scene

Read-onlyIdempotent

Analyze Godot scene and resource files to detect antipatterns like deep nesting, oversized scenes, missing scripts, and format errors in .tscn/.tres files.

Instructions

Parse .tscn scene files or .tres resource files and return structured analysis. Detects antipatterns (deep nesting, oversized scenes, missing scripts) and format errors (preload in .tres, custom class names in type field, integer resource IDs).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesPath to .tscn or .tres file (e.g., res://scenes/main.tscn)

Implementation Reference

  • The main async handler function that executes the godot_analyze_scene tool logic. It validates the project directory, resolves the safe path, checks file existence, reads the file content, parses it (using parseTscn or parseTres based on file extension), and returns the analysis as JSON.
    async (args) => {
      if (!ctx.projectDir) {
        return { content: [{ type: "text", text: formatError(projectNotFound()) }] };
      }
    
      const safeResult = resolveSafePath(ctx.projectDir, args.path);
      if ("error" in safeResult) {
        return { content: [{ type: "text", text: safeResult.error }] };
      }
    
      if (!existsSync(safeResult.path)) {
        return {
          content: [
            {
              type: "text",
              text: formatError({
                message: `File not found: ${args.path}`,
                suggestion:
                  "Check the path and try again. Use godot_get_project_info to list available scenes.",
              }),
            },
          ],
        };
      }
    
      const content = readFileSync(safeResult.path, "utf-8");
      const isTres = args.path.endsWith(".tres");
    
      const analysis = isTres
        ? parseTres(content)
        : parseTscn(content, ctx.projectDir);
    
      return { content: [{ type: "text", text: JSON.stringify(analysis, null, 2) }] };
    }
  • Zod schema definition for the tool input, specifying a single 'path' parameter (string) that describes the path to a .tscn or .tres file.
      path: z
        .string()
        .describe("Path to .tscn or .tres file (e.g., res://scenes/main.tscn)"),
    },
  • Registration function that registers the 'godot_analyze_scene' tool with the MCP server. Includes the tool name, description, input schema, hints, and handler function.
    export function registerSceneAnalysis(server: McpServer, ctx: ServerContext): void {
      server.tool(
        "godot_analyze_scene",
        "Parse .tscn scene files or .tres resource files and return structured analysis. Detects antipatterns (deep nesting, oversized scenes, missing scripts) and format errors (preload in .tres, custom class names in type field, integer resource IDs).",
        {
          path: z
            .string()
            .describe("Path to .tscn or .tres file (e.g., res://scenes/main.tscn)"),
        },
        { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
        async (args) => {
          if (!ctx.projectDir) {
            return { content: [{ type: "text", text: formatError(projectNotFound()) }] };
          }
    
          const safeResult = resolveSafePath(ctx.projectDir, args.path);
          if ("error" in safeResult) {
            return { content: [{ type: "text", text: safeResult.error }] };
          }
    
          if (!existsSync(safeResult.path)) {
            return {
              content: [
                {
                  type: "text",
                  text: formatError({
                    message: `File not found: ${args.path}`,
                    suggestion:
                      "Check the path and try again. Use godot_get_project_info to list available scenes.",
                  }),
                },
              ],
            };
          }
    
          const content = readFileSync(safeResult.path, "utf-8");
          const isTres = args.path.endsWith(".tres");
    
          const analysis = isTres
            ? parseTres(content)
            : parseTscn(content, ctx.projectDir);
    
          return { content: [{ type: "text", text: JSON.stringify(analysis, null, 2) }] };
        }
      );
    }
  • Helper function parseTscn that parses .tscn scene files, extracting nodes, external resources, and detecting antipatterns like deep nesting, oversized scenes, and missing scripts.
    function parseTscn(content: string, projectDir: string): SceneAnalysis {
      const result: SceneAnalysis = {
        format: "tscn",
        nodes: [],
        externalResources: [],
        warnings: [],
        nodeCount: 0,
        maxDepth: 0,
      };
    
      const lines = content.split("\n");
    
      for (const line of lines) {
        // External resources: [ext_resource type="..." path="..." id="..."]
        const extMatch = line.match(
          /\[ext_resource\s+(?:type="([^"]*)")?\s*(?:path="([^"]*)")?\s*(?:uid="([^"]*)")?\s*(?:id="([^"]*)")?\s*\]/
        );
        if (extMatch) {
          result.externalResources.push({
            type: extMatch[1] ?? "",
            path: extMatch[2] ?? "",
            id: extMatch[4] ?? extMatch[3] ?? "",
          });
        }
    
        // Also match reordered attributes
        const extMatch2 = line.match(/\[ext_resource\s+/);
        if (extMatch2 && !extMatch) {
          const typeM = line.match(/type="([^"]*)"/);
          const pathM = line.match(/path="([^"]*)"/);
          const idM = line.match(/id="([^"]*)"/);
          const uidM = line.match(/uid="([^"]*)"/);
          if (typeM || pathM) {
            result.externalResources.push({
              type: typeM?.[1] ?? "",
              path: pathM?.[1] ?? "",
              id: idM?.[1] ?? uidM?.[1] ?? "",
            });
          }
        }
    
        // Nodes: [node name="..." type="..." parent="..."]
        const nodeMatch = line.match(/\[node\s+name="([^"]*)"\s+(?:type="([^"]*)"\s*)?(?:parent="([^"]*)")?/);
        if (nodeMatch) {
          const parent = nodeMatch[3] ?? "";
          const depth = parent === "" ? 0 : parent.split("/").length;
          result.nodes.push({
            name: nodeMatch[1],
            type: nodeMatch[2] ?? "Node",
            parent,
            script: null,
            depth,
          });
          if (depth > result.maxDepth) result.maxDepth = depth;
        }
    
        // Script on node
        if (line.match(/^script\s*=/) && result.nodes.length > 0) {
          const scriptMatch = line.match(/ExtResource\(\s*"?([^)"]*)"?\s*\)/);
          if (scriptMatch) {
            const lastNode = result.nodes[result.nodes.length - 1];
            const ext = result.externalResources.find((e) => e.id === scriptMatch[1]);
            lastNode.script = ext?.path ?? scriptMatch[1];
          }
        }
      }
    
      result.nodeCount = result.nodes.length;
    
      // Antipattern detection
      if (result.maxDepth > 8) {
        result.warnings.push({
          severity: "warning",
          message: `Deep nesting detected (${result.maxDepth} levels). Consider extracting subtrees into separate scenes.`,
        });
      }
    
      if (result.nodeCount > 100) {
        result.warnings.push({
          severity: "warning",
          message: `Large scene (${result.nodeCount} nodes). Consider breaking into smaller reusable scenes.`,
        });
      }
    
      // Missing script references
      for (const node of result.nodes) {
        if (node.script && node.script.startsWith("res://")) {
          const safeResult = resolveSafePath(projectDir, node.script);
          if ("path" in safeResult && !existsSync(safeResult.path)) {
            result.warnings.push({
              severity: "error",
              message: `Script not found: ${node.script}. The referenced script may have been moved or deleted.`,
            });
          }
        }
      }
    
      // Check for integer resource IDs instead of uid://
      if (content.match(/\[ext_resource\s+[^\]]*id=(\d+)/)) {
        result.warnings.push({
          severity: "warning",
          message:
            "Integer resource ID found. Godot 4 uses uid:// strings for resource identification. Regenerate UIDs by opening the scene in the editor.",
        });
      }
    
      return result;
    }
  • Helper function parseTres that parses .tres resource files, detecting issues like preload() usage, custom class names in type fields, and integer resource IDs.
    function parseTres(content: string): SceneAnalysis {
      const result: SceneAnalysis = {
        format: "tres",
        nodes: [],
        externalResources: [],
        warnings: [],
        nodeCount: 0,
        maxDepth: 0,
      };
    
      // Check for preload() usage
      if (content.includes("preload(")) {
        result.warnings.push({
          severity: "warning",
          message:
            "preload() found in .tres file. Use ExtResource() for resource references in .tres files.",
        });
      }
    
      // Check for custom class name in type field
      const headerMatch = content.match(/\[gd_resource\s+type="([^"]*)"/);
      if (headerMatch) {
        const type = headerMatch[1];
        // Built-in Godot types are PascalCase and well-known
        const builtinTypes = new Set([
          "Resource", "Theme", "StyleBox", "StyleBoxFlat", "StyleBoxTexture",
          "Font", "FontFile", "Texture2D", "ImageTexture", "AtlasTexture",
          "Material", "ShaderMaterial", "StandardMaterial3D",
          "Animation", "AnimationLibrary", "AudioStream", "AudioStreamMP3",
          "AudioStreamWAV", "AudioStreamOggVorbis", "Curve", "Curve2D", "Curve3D",
          "Gradient", "GradientTexture1D", "GradientTexture2D",
          "Environment", "Sky", "WorldEnvironment",
          "PhysicsMaterial", "NavigationMesh", "TileSet",
          "PackedScene", "Script", "GDScript", "CSharpScript",
        ]);
    
        if (!builtinTypes.has(type) && !type.startsWith("Packed") && type !== "Resource") {
          result.warnings.push({
            severity: "warning",
            message: `Custom class name "${type}" in .tres type field. Use type="Resource" (the base Godot type), not the custom class name. Custom class names in the type field cause parse errors.`,
          });
        }
      }
    
      // Check for integer resource IDs
      if (content.match(/\[ext_resource\s+[^\]]*id=(\d+)/)) {
        result.warnings.push({
          severity: "warning",
          message:
            "Integer resource ID found. Godot 4 uses uid:// strings for resource identification.",
        });
      }
    
      // Parse external resources (same format as .tscn)
      const lines = content.split("\n");
      for (const line of lines) {
        const extMatch = line.match(/\[ext_resource/);
        if (extMatch) {
          const typeM = line.match(/type="([^"]*)"/);
          const pathM = line.match(/path="([^"]*)"/);
          const idM = line.match(/id="([^"]*)"/);
          result.externalResources.push({
            type: typeM?.[1] ?? "",
            path: pathM?.[1] ?? "",
            id: idM?.[1] ?? "",
          });
        }
      }
    
      return result;
    }
Behavior4/5

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

The description adds valuable behavioral context beyond annotations by specifying what the analysis detects (antipatterns like deep nesting, format errors like preload in .tres), while annotations already cover read-only, non-open-world, and idempotent characteristics. No contradiction with annotations exists.

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 efficiently structured in two sentences: the first states the core functionality, and the second details the analysis scope. Every sentence adds value without redundancy, making it appropriately sized and front-loaded.

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

Completeness4/5

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

Given the tool's complexity (analyzing file formats for antipatterns), no output schema, and rich annotations, the description is mostly complete. It could benefit from clarifying the output format (e.g., structured data types), but it adequately covers the analysis scope and file types.

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?

With 100% schema description coverage for the single 'path' parameter, the description doesn't add meaning beyond what the schema provides (e.g., no additional format or validation details). The baseline score of 3 is appropriate as the schema adequately documents the parameter.

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

Purpose5/5

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

The description clearly states the tool's purpose with specific verbs ('parse', 'return structured analysis') and resources ('.tscn scene files or .tres resource files'), and distinguishes it from siblings by focusing on file analysis rather than script analysis (godot_analyze_script) or diagnostics (godot_get_diagnostics).

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

Usage Guidelines4/5

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

The description provides clear context for when to use this tool (parsing .tscn/.tres files for analysis), but doesn't explicitly state when not to use it or name specific alternatives among the sibling tools, though the distinction is implied through the different resource types analyzed.

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

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/gregario/godot-forge'

If you have feedback or need assistance with the MCP directory API, please join our Discord server