Skip to main content
Glama

search_html

Extracts HTML elements containing specific search queries from web pages, replacing non-matching content with placeholders to focus on relevant sections.

Instructions

Outputs the HTML of elements that deeply contain the given search query. Elements that don't contain the given query are omitted using a [...] placeholder.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSearch query

Implementation Reference

  • The core handler function `searchHTML` that performs a deep search in the page's HTML for the given query string. It serializes and returns HTML structure of matching elements, omitting non-matching parts with [...], and handles shadow DOM and same-origin iframes.
    export async function searchHTML(page: Page, query: string): Promise<string> {
      return await page.evaluate((searchQuery: string) => {
        function elementContainsQuery(element: Element, query: string): boolean {
          // Check text content
          if (
            element.textContent &&
            element.textContent.toLowerCase().includes(query.toLowerCase())
          ) {
            return true;
          }
    
          // Check attributes
          for (const attr of Array.from(element.attributes)) {
            if (attr.value.toLowerCase().includes(query.toLowerCase())) {
              return true;
            }
          }
    
          return false;
        }
    
        function hasDescendantWithQuery(element: Element, query: string): boolean {
          // Check if element itself contains query
          if (elementContainsQuery(element, query)) {
            return true;
          }
    
          // Check shadow DOM
          if ((element as any).shadowRoot) {
            for (const child of Array.from((element as any).shadowRoot.children)) {
              if (hasDescendantWithQuery(child as Element, query)) {
                return true;
              }
            }
          }
    
          // Check iframe content
          if (element.tagName.toLowerCase() === "iframe") {
            try {
              const iframeDoc = (element as HTMLIFrameElement).contentDocument;
              if (
                iframeDoc &&
                iframeDoc.body &&
                hasDescendantWithQuery(iframeDoc.body, query)
              ) {
                return true;
              }
            } catch (e) {
              // Cross-origin iframe, can't access content
            }
          }
    
          // Check children recursively
          for (const child of Array.from(element.children)) {
            if (
              child.tagName.toLowerCase() === "script" ||
              child.tagName.toLowerCase() === "style" ||
              child.tagName.toLowerCase() === "svg"
            ) {
              continue;
            }
    
            if (hasDescendantWithQuery(child, query)) {
              return true;
            }
          }
    
          return false;
        }
    
        function serializeElement(
          element: Element,
          query: string,
          depth: number = 0,
        ): string {
          const tagName = element.tagName.toLowerCase();
    
          // Skip script, style, and svg tags
          if (tagName === "script" || tagName === "style" || tagName === "svg") {
            return "";
          }
    
          const indent = "  ".repeat(depth);
    
          // Get attributes
          let attributes = "";
          for (const attr of Array.from(element.attributes)) {
            attributes += ` ${attr.name}="${attr.value}"`;
          }
    
          const openTag = `${indent}<${tagName}${attributes}>`;
    
          // Check if this element or any descendant contains the query
          const hasQueryContent = hasDescendantWithQuery(element, query);
    
          if (!hasQueryContent) {
            // Don't show [...] for empty body
            if (tagName === "body" && element.children.length === 0) {
              return `${openTag}\n${indent}</${tagName}>`;
            }
            return `${openTag}\n${indent}  [...]\n${indent}</${tagName}>`;
          }
    
          let content = "";
    
          // Check if element has shadow DOM or complex content first
          const hasShadowDOM = !!(element as any).shadowRoot;
          const hasChildElements = Array.from(element.childNodes).some(
            (child) => child.nodeType === Node.ELEMENT_NODE,
          );
    
          // Check if element has only text content (no child elements or shadow DOM)
          const hasOnlyTextContent =
            !hasShadowDOM &&
            !hasChildElements &&
            Array.from(element.childNodes).every(
              (child) => child.nodeType === Node.TEXT_NODE,
            );
    
          if (hasOnlyTextContent) {
            // Use inline format for simple text elements
            const textContent = element.textContent?.trim();
            if (textContent) {
              return `${openTag}${textContent}</${tagName}>`;
            } else {
              return `${openTag}</${tagName}>`;
            }
          }
    
          // Process child nodes with indentation
          for (const child of Array.from(element.childNodes)) {
            if (child.nodeType === Node.TEXT_NODE) {
              const textContent = child.textContent?.trim();
              if (textContent) {
                content += `\n${indent}  ${textContent}`;
              }
            } else if (child.nodeType === Node.ELEMENT_NODE) {
              const childElement = child as Element;
              const childTagName = childElement.tagName.toLowerCase();
    
              // Skip script, style, and svg tags
              if (
                childTagName === "script" ||
                childTagName === "style" ||
                childTagName === "svg"
              ) {
                continue;
              }
    
              const childHasQuery = hasDescendantWithQuery(childElement, query);
    
              if (childHasQuery) {
                const serializedChild = serializeElement(
                  childElement,
                  query,
                  depth + 1,
                );
                if (serializedChild) {
                  content += "\n" + serializedChild;
                }
              } else {
                // Check if there are any siblings that do contain the query
                let hasSiblingWithQuery = false;
                for (const sibling of Array.from(element.children)) {
                  if (
                    sibling !== childElement &&
                    hasDescendantWithQuery(sibling, query)
                  ) {
                    hasSiblingWithQuery = true;
                    break;
                  }
                }
    
                // Only show [...] if there are siblings with query content
                if (hasSiblingWithQuery) {
                  content += `\n${indent}  [...]`;
                }
              }
            }
          }
    
          // Handle shadow DOM content
          if ((element as any).shadowRoot) {
            const shadowRoot = (element as any).shadowRoot;
            for (const child of Array.from(shadowRoot.children)) {
              const childElement = child as Element;
              if (
                childElement.tagName.toLowerCase() === "script" ||
                childElement.tagName.toLowerCase() === "style" ||
                childElement.tagName.toLowerCase() === "svg"
              ) {
                continue;
              }
    
              const childHasQuery = hasDescendantWithQuery(childElement, query);
              if (childHasQuery) {
                const serializedChild = serializeElement(
                  childElement,
                  query,
                  depth + 1,
                );
                if (serializedChild) {
                  content += "\n" + serializedChild;
                }
              }
            }
          }
    
          // Handle iframe content
          if (element.tagName.toLowerCase() === "iframe") {
            try {
              const iframeDoc = (element as HTMLIFrameElement).contentDocument;
              if (iframeDoc && iframeDoc.body) {
                const iframeHasQuery = hasDescendantWithQuery(
                  iframeDoc.body,
                  query,
                );
                if (iframeHasQuery) {
                  const serializedIframe = serializeElement(
                    iframeDoc.body,
                    query,
                    depth + 1,
                  );
                  if (serializedIframe) {
                    content += "\n" + serializedIframe;
                  }
                }
              }
            } catch (e) {
              // Cross-origin iframe, can't access content
            }
          }
    
          const closeTag = `${indent}</${tagName}>`;
    
          if (content) {
            return `${openTag}${content}\n${closeTag}`;
          } else {
            return `${openTag}\n${closeTag}`;
          }
        }
    
        // Start serialization from body element
        const body = document.body;
        if (!body) {
          return "";
        }
    
        return serializeElement(body, searchQuery);
      }, query);
    }
  • The input schema definition for the 'search_html' tool, specifying a required 'query' string parameter.
    {
      name: "search_html",
      description:
        "Outputs the HTML of elements that deeply contain the given search query. Elements that don't contain the given query are omitted using a [...] placeholder.",
      inputSchema: {
        type: "object",
        properties: {
          query: { type: "string", description: "Search query" },
        },
        required: ["query"],
      },
    },
  • src/index.ts:20-170 (registration)
    The TOOLS array where 'search_html' is registered as one of the available tools, exported for the MCP ListTools handler.
    const TOOLS: Tool[] = [
      {
        name: "navigate",
        description: "Navigate to any URL in the browser",
        inputSchema: {
          type: "object",
          properties: {
            url: { type: "string", description: "URL to navigate to" },
          },
          required: ["url"],
        },
      },
      {
        name: "reload",
        description: "Reload the current page",
        inputSchema: {
          type: "object",
          properties: {},
          required: [],
        },
      },
      {
        name: "screenshot",
        description: "Capture screenshots of the entire page or specific elements",
        inputSchema: {
          type: "object",
          properties: {
            name: { type: "string", description: "Name for the screenshot" },
            width: {
              type: "number",
              description: "Width in pixels (default: 1280)",
            },
            height: {
              type: "number",
              description: "Height in pixels (default: 720)",
            },
            encoded: {
              type: "boolean",
              description:
                "If true, capture the screenshot as a base64-encoded data URI (as text) instead of binary image content. Default false.",
            },
          },
          required: ["name"],
        },
      },
      {
        name: "click",
        description: "Click elements on the page",
        inputSchema: {
          type: "object",
          properties: {
            selector: {
              type: "string",
              description: "CSS selector for element to click",
            },
          },
          required: ["selector"],
        },
      },
      {
        name: "select",
        description: "Select an element with SELECT tag",
        inputSchema: {
          type: "object",
          properties: {
            selector: {
              type: "string",
              description: "CSS selector for element to select",
            },
            value: { type: "string", description: "Value to select" },
          },
          required: ["selector", "value"],
        },
      },
      {
        name: "evaluate",
        description: "Execute JavaScript in the browser console",
        inputSchema: {
          type: "object",
          properties: {
            script: { type: "string", description: "JavaScript code to execute" },
          },
          required: ["script"],
        },
      },
      {
        name: "search_html",
        description:
          "Outputs the HTML of elements that deeply contain the given search query. Elements that don't contain the given query are omitted using a [...] placeholder.",
        inputSchema: {
          type: "object",
          properties: {
            query: { type: "string", description: "Search query" },
          },
          required: ["query"],
        },
      },
      {
        name: "print_element",
        description: "Outputs the full HTML of the given element",
        inputSchema: {
          type: "object",
          properties: {
            selector: { type: "string", description: "CSS selector" },
          },
          required: ["selector"],
        },
      },
      {
        name: "test_rule",
        description: "Tests the given Autoconsent rule on the given URL",
        inputSchema: {
          type: "object",
          properties: {
            url: { type: "string", description: "URL to navigate to" },
            rule: {
              type: "object",
              description: "Autoconsent rule (AutoConsentCMPRule)",
            },
          },
          required: ["url", "rule"],
        },
      },
      {
        name: "reset_browser_data",
        description:
          "Reset browser data including cookies, cache, localStorage, and sessionStorage",
        inputSchema: {
          type: "object",
          properties: {
            clearCookies: {
              type: "boolean",
              description: "Clear browser cookies (default: true)",
            },
            clearCache: {
              type: "boolean",
              description: "Clear browser cache (default: true)",
            },
            clearLocalStorage: {
              type: "boolean",
              description: "Clear localStorage (default: true)",
            },
            clearSessionStorage: {
              type: "boolean",
              description: "Clear sessionStorage (default: true)",
            },
          },
          required: [],
        },
      },
    ];
  • The switch case dispatcher in handleToolCall that invokes the searchHTML handler for 'search_html' tool calls.
    case "search_html":
      try {
        const html = await searchHTML(page, args.query);
        return {
          content: [
            {
              type: "text",
              text: html,
            },
          ],
          isError: false,
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Failed to search HTML: ${(error as Error).message}`,
            },
          ],
          isError: true,
        };
      }
  • src/index.ts:588-590 (registration)
    Registers the tool list handler which provides all tools including 'search_html'.
    server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: TOOLS,
    }));
Behavior3/5

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

No annotations are provided, so the description carries the full burden. It discloses key behavioral traits: it outputs HTML of matching elements and uses placeholders for non-matching ones. However, it lacks details on permissions, rate limits, error handling, or output format specifics, leaving gaps for a tool with no annotation coverage.

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 two sentences, front-loaded with the main purpose and followed by a clarifying detail about placeholder usage. Every sentence adds value with zero waste, making it appropriately sized and efficient.

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

Completeness3/5

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

Given no annotations, no output schema, and a simple single-parameter tool, the description is adequate but incomplete. It explains what the tool does but lacks details on output format (e.g., structure of returned HTML), error cases, or performance considerations, which would help an agent use it 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%, so the schema already documents the 'query' parameter fully. The description adds no additional meaning beyond what the schema provides, such as syntax examples or query format details. Baseline 3 is appropriate when schema does the heavy lifting.

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 verb ('outputs') and resource ('HTML of elements'), and distinguishes it from siblings by specifying it searches for elements containing a query and omits others with placeholders. This is more specific than generic tools like 'evaluate' or 'select'.

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 implies usage for searching HTML content with a query, but does not explicitly state when to use this tool versus alternatives like 'select' or 'evaluate'. It provides clear context (searching elements with queries) but lacks explicit exclusions or named alternatives.

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/noisysocks/autoconsent-mcp'

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