Skip to main content
Glama

print_element

Extract full HTML content from web page elements using CSS selectors to analyze and test consent management interfaces in browser automation workflows.

Instructions

Outputs the full HTML of the given element

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
selectorYesCSS selector

Implementation Reference

  • Core handler function that uses Puppeteer to evaluate JavaScript on the page, selecting the element by CSS selector and serializing its full HTML structure recursively, including child elements, text content, shadow DOM, and same-origin iframe contents.
    export async function printElement(
      page: Page,
      selector: string,
    ): Promise<string> {
      return await page.evaluate((sel: string) => {
        function serializeFullElement(element: Element, depth: number = 0): string {
          const tagName = element.tagName.toLowerCase();
          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}>`;
          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 serializedChild = serializeFullElement(childElement, depth + 1);
              if (serializedChild) {
                content += "\n" + serializedChild;
              }
            }
          }
    
          // Handle shadow DOM content
          if ((element as any).shadowRoot) {
            const shadowRoot = (element as any).shadowRoot;
            for (const child of Array.from(shadowRoot.children)) {
              const serializedChild = serializeFullElement(
                child as Element,
                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 serializedIframe = serializeFullElement(
                  iframeDoc.body,
                  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}</${tagName}>`;
          }
        }
    
        const element = document.querySelector(sel);
        if (!element) {
          throw new Error(`Element not found: ${sel}`);
        }
    
        return serializeFullElement(element);
      }, selector);
    }
  • src/index.ts:117-127 (registration)
    Tool registration in the TOOLS array, defining the name, description, and input schema (selector: string) for the print_element tool.
    {
      name: "print_element",
      description: "Outputs the full HTML of the given element",
      inputSchema: {
        type: "object",
        properties: {
          selector: { type: "string", description: "CSS selector" },
        },
        required: ["selector"],
      },
    },
  • Handler dispatch in the main tool call switch statement, invoking the printElement function with page and selector, and formatting the result as MCP CallToolResult.
    case "print_element":
      try {
        const html = await printElement(page, args.selector);
        return {
          content: [
            {
              type: "text",
              text: html,
            },
          ],
          isError: false,
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Failed to print element: ${(error as Error).message}`,
            },
          ],
          isError: true,
        };
      }
  • Input schema definition for the print_element tool, specifying a required 'selector' string parameter.
    inputSchema: {
      type: "object",
      properties: {
        selector: { type: "string", description: "CSS selector" },
      },
      required: ["selector"],
    },
Behavior2/5

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

With no annotations provided, the description carries full burden but only states the basic function. It doesn't disclose whether this is a read-only operation, if it requires the element to be visible/loaded, what happens with invalid selectors, or any performance/rate limit considerations. For a tool with zero annotation coverage, this is insufficient behavioral context.

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 a single, efficient sentence that directly states the tool's function with zero wasted words. It's appropriately sized for a simple tool and front-loads the essential information.

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?

For a single-parameter tool with 100% schema coverage but no annotations and no output schema, the description is minimally adequate. It explains what the tool does but lacks context about when to use it, behavioral details, or what the output looks like (HTML string format, error cases). Given the simplicity, it's passable but has clear 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 100% (the 'selector' parameter is documented as 'CSS selector'), so the baseline is 3. The description adds no additional parameter semantics beyond what the schema already provides—it doesn't clarify selector syntax examples, scope, or special cases.

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 action ('Outputs') and resource ('full HTML of the given element'), making the purpose immediately understandable. It doesn't explicitly differentiate from siblings like 'search_html' or 'select', but the verb+resource combination is specific enough for basic understanding.

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?

No guidance is provided on when to use this tool versus alternatives like 'search_html' (which might search within HTML) or 'select' (which might interact with elements). The description only states what it does, not when it's appropriate or what prerequisites exist.

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