Skip to main content
Glama

get_ui_tree

Capture the current Android screen's UI hierarchy to analyze visible elements, their properties, text, bounds, and states for automation and debugging.

Instructions

Capture the current UI hierarchy from the Android screen. Returns a structured representation of all visible UI elements with their properties, text, bounds, and states. This is the primary way to understand what is currently on screen.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
formatNoOutput format: "summary" (readable, compact) or "full" (complete JSON tree)summary
device_idNoDevice serial number

Implementation Reference

  • The implementation of getUITree which executes adb shell uiautomator dump, reads the XML, and parses it into a UIElement tree.
    export async function getUITree(deviceId?: string): Promise<UIElement> {
      const resolved = await deviceManager.resolveDeviceId(deviceId);
    
      // Dump UI hierarchy to device file
      await adbShell(['uiautomator', 'dump', '/sdcard/window_dump.xml'], resolved, 15000);
    
      // Read the XML content
      const catResult = await adbShell(['cat', '/sdcard/window_dump.xml'], resolved);
      const xmlContent = catResult.stdout;
    
      if (!xmlContent || xmlContent.includes('ERROR') || !xmlContent.includes('<hierarchy')) {
        throw new Error(`UIAutomator dump failed or returned empty content: ${xmlContent.substring(0, 200)}`);
      }
    
      // Parse XML
      const parser = new XMLParser({
        ignoreAttributes: false,
        attributeNamePrefix: '@_',
        isArray: (name) => name === 'node',
      });
    
      const parsed = parser.parse(xmlContent);
      const hierarchy = parsed?.hierarchy;
    
      if (!hierarchy) {
        throw new Error('Failed to parse UI hierarchy XML');
      }
    
      // The root hierarchy node wraps all content
      const rootElement = parseNode(hierarchy);
      rootElement.className = 'hierarchy';
    
      // Clean up temp file
      adbShell(['rm', '-f', '/sdcard/window_dump.xml'], resolved).catch(() => {});
    
      log.info('UI tree captured', { deviceId: resolved });
      return rootElement;
    }
  • Registration of the get_ui_tree tool within the MCP server.
    server.registerTool(
      'get_ui_tree',
      {
        description: 'Capture the current UI hierarchy from the Android screen. Returns a structured representation of all visible UI elements with their properties, text, bounds, and states. This is the primary way to understand what is currently on screen.',
        inputSchema: {
          format: z.enum(['summary', 'full']).optional().default('summary').describe('Output format: "summary" (readable, compact) or "full" (complete JSON tree)'),
          device_id: z.string().optional().describe('Device serial number'),
        },
      },
      async ({ format, device_id }) => {
        return await metrics.measure('get_ui_tree', device_id || 'default', async () => {
          const tree = await getUITree(device_id);
    
          if (format === 'full') {
            return {
              content: [{
                type: 'text' as const,
                text: JSON.stringify({ success: true, tree }, null, 2),
              }],
            };
          }
    
          // Summary format — more AI-friendly
          const summary = summarizeTree(tree);
          const allElements = flattenTree(tree);
          const clickableCount = allElements.filter(e => e.clickable).length;
          const textElements = allElements.filter(e => e.text).length;
    
          return {
            content: [{
              type: 'text' as const,
              text: JSON.stringify({
                success: true,
                stats: {
                  totalElements: allElements.length,
                  clickableElements: clickableCount,
                  textElements: textElements,
                },
                uiTree: summary,
              }, null, 2),
            }],
          };
        });
      }
    );
Behavior4/5

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

With no annotations provided, the description carries the full burden and adequately discloses the return structure (properties, text, bounds, states). However, it omits operational details like required permissions (ADB/accessibility service) or performance characteristics.

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?

Three sentences with zero waste: action definition, return value specification, and usage guidance. Information is front-loaded and each sentence earns its place.

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?

Despite lacking an output schema, the description compensates by detailing the return structure (elements with properties, text, bounds, states). It appropriately covers the two optional parameters for a straightforward inspection tool.

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% (both format and device_id are fully documented in the schema), establishing the baseline score. The description adds no supplemental parameter guidance, but none is needed given the comprehensive schema.

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 uses a specific verb ('Capture') with a clear resource ('UI hierarchy from the Android screen'), distinguishing it from visual capture tools like capture_screenshot by emphasizing 'structured representation' rather than image data.

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 statement 'This is the primary way to understand what is currently on screen' provides clear context for when to use the tool (introspection/debugging), though it does not explicitly name alternatives like capture_screenshot or analyze_screen.

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/divineDev-dotcom/android_mcp'

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