Skip to main content
Glama

get-element-styles

Retrieve computed CSS styles for specific HTML elements using CSS selectors and property names to inspect styling during development.

Instructions

Retrieves style information of a specific element

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
selectorYesCSS selector of the element to inspect
stylePropertiesYesArray of style property names to retrieve (e.g., ['color', 'fontSize', 'backgroundColor'])

Implementation Reference

  • Handler function that validates browser context, waits implicitly via evaluate, uses document.querySelector and window.getComputedStyle to fetch specified style properties, formats response with checkpoint ID or error.
    async ({ selector, styleProperties }) => {
      try {
        // Check browser status
        const browserStatus = getContextForOperation();
        if (!browserStatus.isStarted) {
          return browserStatus.error;
        }
    
        // Get current checkpoint ID
        const checkpointId = await getCurrentCheckpointId(browserStatus.page);
    
        // Retrieve element styles
        const styles = await browserStatus.page.evaluate(({ selector, stylePropsToGet }: { selector: string; stylePropsToGet: string[] }) => {
          const element = document.querySelector(selector);
          if (!element) return null;
    
          const computedStyle = window.getComputedStyle(element);
          const result: Record<string, string> = {};
    
          stylePropsToGet.forEach((prop: string) => {
            result[prop] = computedStyle.getPropertyValue(prop);
          });
    
          return result;
        }, { selector, stylePropsToGet: styleProperties });
    
        if (!styles) {
          return {
            content: [
              {
                type: 'text',
                text: `Element with selector "${selector}" not found`
              }
            ],
            isError: true
          };
        }
    
        // Result message construction
        const resultMessage = {
          selector,
          styles,
          checkpointId
        };
    
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(resultMessage, null, 2)
            }
          ]
        };
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        Logger.error(`Failed to get element styles: ${errorMessage}`);
        return {
          content: [
            {
              type: 'text',
              text: `Failed to get element styles: ${errorMessage}`
            }
          ],
          isError: true
        };
      }
    }
  • Zod schema defining input parameters: selector (CSS selector string) and styleProperties (array of style property names).
      selector: z.string().describe('CSS selector of the element to inspect'),
      styleProperties: z.array(z.string()).describe("Array of style property names to retrieve (e.g., ['color', 'fontSize', 'backgroundColor'])")
    },
  • server.tool registration call for 'get-element-styles' within registerBrowserTools function, which is called from src/index.ts
    server.tool(
      'get-element-styles',
      'Retrieves style information of a specific element',
      {
        selector: z.string().describe('CSS selector of the element to inspect'),
        styleProperties: z.array(z.string()).describe("Array of style property names to retrieve (e.g., ['color', 'fontSize', 'backgroundColor'])")
      },
      async ({ selector, styleProperties }) => {
        try {
          // Check browser status
          const browserStatus = getContextForOperation();
          if (!browserStatus.isStarted) {
            return browserStatus.error;
          }
    
          // Get current checkpoint ID
          const checkpointId = await getCurrentCheckpointId(browserStatus.page);
    
          // Retrieve element styles
          const styles = await browserStatus.page.evaluate(({ selector, stylePropsToGet }: { selector: string; stylePropsToGet: string[] }) => {
            const element = document.querySelector(selector);
            if (!element) return null;
    
            const computedStyle = window.getComputedStyle(element);
            const result: Record<string, string> = {};
    
            stylePropsToGet.forEach((prop: string) => {
              result[prop] = computedStyle.getPropertyValue(prop);
            });
    
            return result;
          }, { selector, stylePropsToGet: styleProperties });
    
          if (!styles) {
            return {
              content: [
                {
                  type: 'text',
                  text: `Element with selector "${selector}" not found`
                }
              ],
              isError: true
            };
          }
    
          // Result message construction
          const resultMessage = {
            selector,
            styles,
            checkpointId
          };
    
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify(resultMessage, null, 2)
              }
            ]
          };
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : String(error);
          Logger.error(`Failed to get element styles: ${errorMessage}`);
          return {
            content: [
              {
                type: 'text',
                text: `Failed to get element styles: ${errorMessage}`
              }
            ],
            isError: true
          };
        }
      }
    );
  • Helper function used by get-element-styles to retrieve the active Page object from ContextManager, falling back to most recent context if no contextId provided, returns error structure if no browser available.
    const getContextForOperation = (contextId?: string): BrowserStatus => {
      let contextInstance;
      
      if (contextId) {
        contextInstance = contextManager.getContext(contextId);
        if (!contextInstance) {
          return {
            isStarted: false,
            error: {
              content: [
                {
                  type: 'text',
                  text: `Browser '${contextId}' not found. Use 'list-browsers' to see available browsers or 'start-browser' to create one.`
                }
              ],
              isError: true
            }
          };
        }
      } else {
        contextInstance = contextManager.getMostRecentContext();
        if (!contextInstance) {
          return {
            isStarted: false,
            error: {
              content: [
                {
                  type: 'text',
                  text: 'No active browsers found. Use \'start-browser\' to create a browser first.'
                }
              ],
              isError: true
            }
          };
        }
      }
    
      // Note: contextInstance.page is now always defined (never null)
    
      return { isStarted: true, page: contextInstance.page };
    };
  • Helper function used to extract the current checkpoint ID from the page's meta tag for including in tool responses.
    const getCurrentCheckpointId = async (page: Page) => {
      const checkpointId = await page.evaluate(() => {
        const metaTag = document.querySelector('meta[name="__mcp_checkpoint"]');
        return metaTag ? metaTag.getAttribute('data-id') : null;
      });
      return checkpointId;
    };
  • src/index.ts:87-92 (registration)
    Invocation of registerBrowserTools in main server setup, which registers all browser tools including get-element-styles.
    registerBrowserTools(
      server,
      contextManager,
      lastHMREvents,
      screenshotHelpers
    );
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 for behavioral disclosure. It states the tool retrieves information (implying read-only), but doesn't mention potential side effects (e.g., whether it modifies the DOM), error conditions, performance implications, or return format. For a tool with zero annotation coverage, this leaves significant behavioral gaps.

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 purpose without unnecessary words. It's appropriately sized for a straightforward retrieval tool and front-loads the key action ('retrieves'). Every word earns its place.

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 the tool's moderate complexity (2 required parameters, no output schema, no annotations), the description is minimally adequate but incomplete. It covers the basic purpose but lacks behavioral context, usage guidelines, and output details. The high schema coverage helps, but the absence of annotations and output schema means the description should do more to compensate.

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%, with both parameters clearly documented in the schema. The description adds no additional parameter semantics beyond what the schema provides (e.g., no examples of valid selectors or style properties beyond the schema's example). This meets the baseline for high schema coverage.

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 verb ('retrieves') and resource ('style information of a specific element'), making the purpose understandable. However, it doesn't explicitly distinguish this tool from sibling tools like 'get-element-properties' or 'get-element-dimensions', which likely retrieve different types of element information. This prevents a perfect score.

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. With sibling tools like 'get-element-properties' and 'get-element-dimensions' available, the agent must infer usage context from tool names alone. There's no mention of prerequisites, constraints, or comparative scenarios.

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/ESnark/blowback'

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