Skip to main content
Glama

wait_for_element

Wait for a UI element to appear on screen within a specified timeout. Use this tool after navigation, loading screens, or animations to ensure elements are present before interaction.

Instructions

Wait for a UI element to appear on screen within a timeout period. Useful after navigation, loading screens, or animations. Polls the UI tree at regular intervals until the element is found.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
selectorYesElement selector to wait for
timeout_msNoMaximum wait time in milliseconds (default: 10000)
device_idNoDevice serial number

Implementation Reference

  • The core implementation of the waitForElement function, which polls the UI tree until the element is found or a timeout occurs.
    export async function waitForElement(
      selector: ElementSelector,
      timeoutMs: number = 10000,
      pollIntervalMs: number = 1000,
      deviceId?: string
    ): Promise<FoundElement> {
      const resolved = await deviceManager.resolveDeviceId(deviceId);
      const startTime = Date.now();
    
      while (Date.now() - startTime < timeoutMs) {
        try {
          const elements = await findElements(selector, resolved);
          if (elements.length > 0) {
            log.info('Element found after waiting', {
              selector,
              elapsedMs: Date.now() - startTime,
              deviceId: resolved,
            });
            return elements[0];
          }
        } catch (error) {
          // UI tree dump might fail transiently; keep trying
          log.debug('UI tree dump failed during wait, retrying...', {
            error: error instanceof Error ? error.message : String(error),
          });
        }
    
        await new Promise(resolve => setTimeout(resolve, pollIntervalMs));
      }
    
      const selectorStr = Object.entries(selector)
        .map(([k, v]) => `${k}="${v}"`)
        .join(', ');
      throw new TimeoutError(`waitForElement(${selectorStr})`, timeoutMs);
    }
  • Tool registration and handler wrapper for wait_for_element in the controller layer.
    server.registerTool(
      'wait_for_element',
      {
        description: 'Wait for a UI element to appear on screen within a timeout period. Useful after navigation, loading screens, or animations. Polls the UI tree at regular intervals until the element is found.',
        inputSchema: {
          selector: selectorSchema.describe('Element selector to wait for'),
          timeout_ms: z.number().optional().default(10000).describe('Maximum wait time in milliseconds (default: 10000)'),
          device_id: z.string().optional().describe('Device serial number'),
        },
      },
      async ({ selector, timeout_ms, device_id }) => {
        return await metrics.measure('wait_for_element', device_id || 'default', async () => {
          try {
            const element = await waitForElement(selector as ElementSelector, timeout_ms, undefined, device_id);
            return {
              content: [{
                type: 'text' as const,
                text: JSON.stringify({
                  success: true,
                  found: true,
                  element,
                }, null, 2),
Behavior4/5

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

No annotations provided, so description carries full burden. Discloses critical implementation detail: 'Polls the UI tree at regular intervals until the element is found.' This reveals the active polling mechanism vs. event-driven waiting. Missing explicit documentation of timeout failure behavior (exception vs. null return).

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, each earning its place: (1) core function, (2) usage context, (3) implementation mechanism. Front-loaded with essential purpose. No redundancy or filler.

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?

Appropriate for a 3-parameter polling tool with good schema coverage. Covers the polling mechanism and timeout concept. Lacks explicit documentation of return values on success/failure, but no output schema exists to set that expectation.

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 has 100% description coverage, establishing baseline 3. Description references 'timeout period' which aligns with timeout_ms parameter, but adds no additional semantic detail about selector composition or device_id scoping beyond what the schema already provides.

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?

Specific verb ('Wait') + resource ('UI element') + scope ('within a timeout period'). Clearly distinguishes from immediate-action siblings like find_element or click_element by emphasizing the temporal waiting aspect.

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?

Explicitly states when to use: 'after navigation, loading screens, or animations.' Provides clear contextual guidance for timing-sensitive operations, though does not explicitly name alternatives like find_element for non-waiting scenarios.

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