Skip to main content
Glama
yfmeii

WeChat Mini Program Dev MCP

by yfmeii

page_waitElement

Wait for a specific element to appear on a WeChat mini program page. Supports index syntax and configurable timeout and retry intervals.

Instructions

等待指定选择器的元素出现在页面上。支持 [index=N] 语法选择第 N 个元素。增强版:增加了超时和重试间隔参数。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
connectionNo
selectorYes
timeoutNo
retryIntervalNo

Implementation Reference

  • The `createWaitForElementTool` function creates the tool handler for 'page_waitElement'. It waits for a DOM element matching the given selector to appear on the page, polling with configurable timeout and retryInterval. Supports [index=N] syntax to target a specific element by index.
    function createWaitForElementTool(manager: WeappAutomatorManager): AnyTool {
      return {
        name: "page_waitElement",
        description: "等待指定选择器的元素出现在页面上。支持 [index=N] 语法选择第 N 个元素。增强版:增加了超时和重试间隔参数。",
        parameters: waitForElementParameters,
        execute: async (rawArgs, context: ToolContext) =>
          withUserErrorResult(async () => {
          const args = waitForElementParameters.parse(rawArgs ?? {});
          return manager.withPage<ContentResult>(
            context.log,
            { overrides: args.connection },
            async (page) => {
              if (typeof page.$$ !== "function") {
                throw new UserError("当前页面不支持查询元素数组。");
              }
    
              const startTime = Date.now();
              const timeout = args.timeout;
              const retryInterval = args.retryInterval;
    
              let selector = args.selector;
              let indexHint: number | undefined;
    
              const parsed = parseSelectorWithIndex(selector);
              if (parsed) {
                selector = parsed.baseSelector;
                indexHint = parsed.index;
              }
    
              while (Date.now() - startTime < timeout) {
                try {
                  let elements = await page.$$(selector);
                  if (!Array.isArray(elements) || elements.length === 0) {
                  } else if (indexHint !== undefined) {
                    if (indexHint >= 0 && indexHint < elements.length) {
                      return toTextResult(formatJson({
                        selector: args.selector,
                        index: indexHint,
                        found: true,
                        waitTime: Date.now() - startTime,
                      }));
                    }
                  } else {
                    return toTextResult(formatJson({
                      selector: args.selector,
                      found: true,
                      waitTime: Date.now() - startTime,
                    }));
                  }
                } catch (error) {
                  if (error instanceof UserError) {
                    throw error;
                  }
                }
                await new Promise(resolve => setTimeout(resolve, retryInterval));
              }
    
              throw new UserError(`等待元素 "${args.selector}" 超时 (${timeout}ms)。`);
            }
          );
          }),
      };
    }
  • The `waitForElementParameters` schema defines the input validation for the page_waitElement tool: selector (string), timeout (positive int, default 5000ms), retryInterval (positive int, default 200ms).
    const waitForElementParameters = connectionContainerSchema.extend({
      selector: z.string().trim().min(1),
      timeout: z.coerce.number().int().positive().optional().default(5000),
      retryInterval: z.coerce.number().int().positive().optional().default(200),
    });
  • The `createPageTools` function registers all page tools, including `createWaitForElementTool`, into an array returned to the caller. This is where page_waitElement is aggregated.
    export function createPageTools(manager: WeappAutomatorManager): AnyTool[] {
      return [
        createGetElementTool(manager),
        createGetElementsTool(manager),
        createWaitForElementTool(manager),
        createWaitForTimeoutTool(manager),
        createGetPageDataTool(manager),
        createSetPageDataTool(manager),
        createCallPageMethodTool(manager),
      ];
    }
  • src/tools.ts:1-13 (registration)
    The top-level `createTools` function spreads `createPageTools` results (which includes page_waitElement) into the final tool array.
    import { createApplicationTools } from "./tools/application.js";
    import { AnyTool } from "./tools/common.js";
    import { createElementTools } from "./tools/element.js";
    import { createPageTools } from "./tools/page.js";
    import { WeappAutomatorManager } from "./weappClient.js";
    
    export function createTools(manager: WeappAutomatorManager): AnyTool[] {
      return [
        ...createApplicationTools(manager),
        ...createPageTools(manager),
        ...createElementTools(manager),
      ];
    }
  • The `parseSelectorWithIndex` helper is used by the page_waitElement handler to parse the [index=N] suffix from selectors.
    export function parseSelectorWithIndex(selector: string): { baseSelector: string; index: number } | null {
      // 匹配 selector[index=N] 语法
      const match = selector.match(/^(.+?)\[index=(\d+)\]$/);
      if (match) {
        return {
          baseSelector: match[1],
          index: parseInt(match[2], 10),
        };
      }
      return null;
    }
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions timeout and retry interval, but does not specify behavior on failure (e.g., timeout error), return value, or side effects. The description is insufficient for an agent to fully predict tool behavior.

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

Conciseness4/5

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

The description is concise at two sentences. It front-loads the primary purpose and then adds secondary features. No redundant information. However, it could be slightly more structured by separating core purpose from enhancements.

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 tool has a complex 'connection' parameter, no output schema, and no annotations, the description is incomplete. It omits explanation of the connection object, error handling, and return values. The description only covers selector semantics and basic retry/timeout, leaving major gaps.

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 0%, so the description must compensate. It adds meaning to the selector parameter by explaining the [index=N] syntax. It also states timeout and retry interval are 'enhanced' parameters. However, the complex 'connection' object is left unexplained, and other parameters lack context.

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 tool waits for an element specified by a selector to appear on the page. It mentions support for [index=N] syntax, which adds clarity about selecting specific elements. However, it does not explicitly distinguish this tool from siblings like page_waitTimeout or page_getElement, which could lead to confusion.

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. It does not mention prerequisites, common use cases, or when not to use it. The sibling tools suggest broader workflow, but no explicit context is given.

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/yfmeii/weapp-dev-mcp'

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