Skip to main content
Glama

get-element-html

Retrieve HTML content of a specific element and its children using a CSS selector. Control whether to get outer or inner HTML and limit depth for shallow inspection. Ideal for observing live HMR updates in Vite dev server.

Instructions

Retrieves the HTML content of a specific element and its children with optional depth control

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
selectorYesCSS selector of the element to inspect
includeOuterNoIf true, includes the selected element's outer HTML; otherwise returns only inner HTML (default: false)
depthNoControl HTML depth limit: -1 = unlimited (default), 0 = text only, 1+ = limited depth with deeper elements shown as <!-- omitted -->

Implementation Reference

  • The tool 'get-element-html' is registered in browser-tools.ts via server.tool() call at line 603.
    // Element HTML content retrieval tool
    server.tool(
      'get-element-html',
  • Zod schema defining three input parameters: selector (string, required), includeOuter (boolean, optional, default false), depth (number, optional, default -1).
    {
      selector: z.string().describe('CSS selector of the element to inspect'),
      includeOuter: z.boolean().optional().describe("If true, includes the selected element's outer HTML; otherwise returns only inner HTML (default: false)"),
      depth: z.number().int().min(-1).optional().describe('Control HTML depth limit: -1 = unlimited (default), 0 = text only, 1+ = limited depth with deeper elements shown as <!-- omitted -->')
    },
  • The handler function that executes 'get-element-html' logic. It waits for the selector, then evaluates JavaScript in the browser to retrieve HTML content with optional depth control: depth=-1 returns all HTML, depth=0 returns textContent only, depth>=1 limits nesting (replacing deeper elements with '<!-- omitted -->').
      async ({ selector, includeOuter = false, depth = -1 }) => {
        try {
          // Check browser status
          const browserStatus = getContextForOperation();
          if (!browserStatus.isStarted) {
            return browserStatus.error;
          }
    
          // Check if element exists
          await browserStatus.page.waitForSelector(selector, { state: 'visible', timeout: 5000 });
    
          // Get element's HTML content with depth control
          const htmlContent = await browserStatus.page.evaluate(({ selector, includeOuter, depth }: { selector: string; includeOuter: boolean; depth: number }) => {
            const element = document.querySelector(selector);
            if (!element) return null;
            
            // Handle unlimited depth (backward compatibility)
            if (depth === -1) {
              return includeOuter ? element.outerHTML : element.innerHTML;
            }
            
            // Handle text-only mode
            if (depth === 0) {
              return element.textContent || '';
            }
            
            // Handle depth-limited mode with DOM cloning
            const cloned = element.cloneNode(true) as Element;
            
            function trimDepth(node: Element, currentDepth: number) {
              if (currentDepth >= depth) {
                // Replace content with omitted marker
                node.innerHTML = '<!-- omitted -->';
                return;
              }
              
              // Process child elements
              Array.from(node.children).forEach(child => {
                trimDepth(child, currentDepth + 1);
              });
            }
            
            // Start depth counting from appropriate level
            trimDepth(cloned, includeOuter ? 0 : 1);
            
            return includeOuter ? cloned.outerHTML : cloned.innerHTML;
          }, { selector, includeOuter, depth });
    
          if (htmlContent === null) {
            return {
              content: [
                {
                  type: 'text',
                  text: `Element with selector "${selector}" not found`
                }
              ],
              isError: true
            };
          }
    
          // Result message construction
          const resultMessage = {
            selector,
            htmlType: depth === 0 ? 'textContent' : (includeOuter ? 'outerHTML' : 'innerHTML'),
            depth,
            depthLimited: depth !== -1,
            length: htmlContent.length,
            checkpointId: await getCurrentCheckpointId(browserStatus.page)
          };
    
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify(resultMessage, null, 2)
              },
              {
                type: 'text',
                text: htmlContent
              }
            ]
          };
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : String(error);
          Logger.error(`Failed to get element HTML: ${errorMessage}`);
          return {
            content: [
              {
                type: 'text',
                text: `Failed to get element HTML: ${errorMessage}`
              }
            ],
            isError: true
          };
        }
      }
    );
  • src/index.ts:87-88 (registration)
    Registration of browser tools (including get-element-html) is initiated from the main entry point index.ts.
    registerBrowserTools(
      server,

Schema Changelog

Changes observed during successful MCP inspections.

  1. Changed1 schema field changedv1.0.0
    • addedInput schema / properties / depth
      Added value: +{
      +  "description": "Control HTML depth limit: -1 = unlimited (default), 0 = text only, 1+ = limited depth with deeper elements shown as <!-- omitted -->",
      +  "minimum": -1,
      +  "type": "integer"
      +}
  2. First observed

TDQS

A4/5.0
Behavior3/5

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

No annotations are provided, so the description carries the behavioral disclosure burden. It clearly states the tool returns HTML and supports depth control, but it does not describe the exact return payload or any side effects. For a read-only inspection tool, this is a modest but acceptable gap.

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?

A single, front-loaded sentence conveys the core action, target, scope, and key option. There is no redundant wording or repetition of schema details.

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?

For a relatively simple read-only tool with three parameters, the description plus fully documented schema provides enough information to invoke it correctly. It does not explain the exact return format, but that omission is minor given the availability of output examples over time and the clear purpose.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100%, so the baseline is 3. The description adds meaning by clarifying that the tool returns content for the element and its children, which goes beyond individual parameter descriptions and helps interpret depth and includeOuter behavior.

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 ('Retrieves') with a concrete resource ('HTML content of a specific element and its children') and mentions depth control. This clearly distinguishes it from sibling inspection tools like get-element-properties or get-element-styles.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Usage context is implied: this tool should be used when HTML content is needed, as opposed to properties, styles, or dimensions. However, it does not explicitly say when not to use it or mention alternatives to consider.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.