Skip to main content
Glama

getSelectedElement

Retrieve the currently highlighted webpage element for AI applications to analyze browser content through Chrome extension integration.

Instructions

Get the selected element from the browser

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • MCP tool registration and handler for getSelectedElement. Fetches data from the browser connector server's /selected-element endpoint and returns it as MCP content.
    server.tool(
      "getSelectedElement",
      "Get the selected element from the browser",
      async () => {
        return await withServerConnection(async () => {
          const response = await fetch(
            `http://${discoveredHost}:${discoveredPort}/selected-element`
          );
          const json = await response.json();
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(json, null, 2),
              },
            ],
          };
        });
      }
    );
  • GET endpoint /selected-element that returns the currently stored selectedElement object or a no-selection message.
    app.get("/selected-element", (req, res) => {
      res.json(selectedElement || { message: "No element selected" });
    });
  • Handler in /extension-log POST for type 'selected-element', stores the element data in global selectedElement variable.
    case "selected-element":
      console.log("Updating selected element:", {
        tagName: data.element?.tagName,
        id: data.element?.id,
        className: data.element?.className,
      });
      selectedElement = data.element;
      break;
  • Global variable to store the currently selected DOM element data.
    let selectedElement: any = null;
  • Chrome DevTools Elements panel selection listener that triggers captureAndSendElement() when $0 changes.
    chrome.devtools.panels.elements.onSelectionChanged.addListener(() => {
      captureAndSendElement();
    });
  • Function that evaluates JS in inspected window to extract data from selected element $0 and sends it to the browser connector.
    function captureAndSendElement() {
      chrome.devtools.inspectedWindow.eval(
        `(function() {
          const el = $0;  // $0 is the currently selected element in DevTools
          if (!el) return null;
    
          const rect = el.getBoundingClientRect();
    
          return {
            tagName: el.tagName,
            id: el.id,
            className: el.className,
            textContent: el.textContent?.substring(0, 100),
            attributes: Array.from(el.attributes).map(attr => ({
              name: attr.name,
              value: attr.value
            })),
            dimensions: {
              width: rect.width,
              height: rect.height,
              top: rect.top,
              left: rect.left
            },
            innerHTML: el.innerHTML.substring(0, 500)
          };
        })()`,
        (result, isException) => {
          if (isException || !result) return;
    
          console.log("Element selected:", result);
    
          // Send to browser connector
          sendToBrowserConnector({
            type: "selected-element",
            timestamp: Date.now(),
            element: result,
          });
        }
      );
    }
Behavior2/5

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

No annotations are provided, so the description carries full burden. It states the action ('Get') but does not disclose behavioral traits such as whether it requires specific permissions, how it handles errors (e.g., if no element is selected), or what the return format might be. This leaves significant gaps for a tool interacting with browser elements.

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 with no wasted words. It is front-loaded and appropriately sized for a simple tool, making it easy to parse quickly.

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 complexity of browser interaction and lack of annotations or output schema, the description is incomplete. It does not explain what 'selected element' entails (e.g., DOM element, properties returned) or potential side effects, leaving the agent with insufficient context for reliable use.

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?

The tool has 0 parameters with 100% schema description coverage, so no parameter information is needed. The description does not add parameter details, which is appropriate here, but it could have clarified context (e.g., implicit parameters like browser session), though not required for a baseline score.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states the tool's purpose ('Get the selected element from the browser') with a clear verb ('Get') and resource ('selected element'), but it does not distinguish it from sibling tools like 'takeScreenshot' or 'runAccessibilityAudit' that might also interact with browser elements. It's vague about what 'selected element' means in context.

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. The description does not mention prerequisites (e.g., needing a browser context or selection), exclusions, or comparisons to sibling tools like 'runAuditMode' that might involve element inspection.

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/Sugatraj/Cursor-Browser-Tools-MCP'

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