Skip to main content
Glama
ananddtyagi

Webpage Screenshot MCP Server

screenshot-element

Capture a screenshot of a specific webpage element using a CSS selector. Save the image in PNG, JPEG, or WebP format with customizable quality and padding for precise visual verification.

Instructions

Captures a screenshot of a specific element on a webpage using a CSS selector

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
formatNoImage format for the screenshotpng
paddingNoPadding around the element in pixels
qualityNoQuality of the image (0-100), only applicable for jpeg and webp
selectorYesCSS selector for the element to screenshot
urlYesThe URL of the webpage
useDefaultBrowserNoWhether to use the system's default browser instead of Puppeteer's bundled Chromium
useSavedAuthNoWhether to use saved cookies from previous login
visibleBrowserNoWhether to show the browser window (non-headless mode)
waitForSelectorNoWhether to wait for the selector to appear

Implementation Reference

  • The handler function that executes the screenshot-element tool logic. It launches a browser (Puppeteer or default), loads cookies if requested, navigates to the URL, waits for the element selector, captures a screenshot of the specific element with optional padding/format/quality, and returns the base64 image.
    async ({ url, selector, waitForSelector, format, quality, padding, useSavedAuth, useDefaultBrowser, visibleBrowser }) => {
        let page: Page | null = null;
        
        try {
            // Initialize browser with appropriate options
            const isHeadless = !visibleBrowser;
            const browserInstance = await initBrowser(isHeadless, useDefaultBrowser && visibleBrowser);
            
            // Create a new page
            page = await browserInstance.newPage();
            
            // Load saved cookies if requested
            if (useSavedAuth) {
                const cookies = await loadCookies(url);
                if (cookies.length > 0) {
                    await page.setCookie(...cookies);
                }
            }
            
            // Set viewport (matching screenshot-page tool)
            await page.setViewport({ width: 1920, height: 1080 });
            
            // Set user agent to avoid bot detection
            await page.setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
            
            // Additional anti-detection measures for Google
            await page.evaluateOnNewDocument(() => {
                // Remove webdriver property
                delete (window.navigator as any).webdriver;
                
                // Override the plugins property to add fake plugins
                Object.defineProperty(window.navigator, 'plugins', {
                    get: () => [1, 2, 3, 4, 5]
                });
                
                // Override the languages property
                Object.defineProperty(window.navigator, 'languages', {
                    get: () => ['en-US', 'en']
                });
                
                // Override permissions
                Object.defineProperty(window.navigator, 'permissions', {
                    get: () => ({
                        query: () => Promise.resolve({ state: 'granted' })
                    })
                });
            });
            
            // Navigate to the URL
            await page.goto(url, {
                waitUntil: 'networkidle2',
                timeout: 30000
            });
            
            // Wait for the selector if requested
            if (waitForSelector) {
                await page.waitForSelector(selector, { timeout: 10000 });
            }
            
            // Get the element
            const element = await page.$(selector);
            
            if (!element) {
                return {
                    isError: true,
                    content: [
                        {
                            type: "text",
                            text: `Element not found with selector: ${selector}`,
                        },
                    ],
                };
            }
            
            // Add padding if requested
            if (padding > 0) {
                await page.evaluate((sel, pad) => {
                    const el = document.querySelector(sel);
                    if (el) {
                        (el as HTMLElement).style.padding = `${pad}px`;
                    }
                }, selector, padding);
            }
            
            // Prepare screenshot options
            const screenshotOptions: any = {
                encoding: 'base64',
                type: format
            };
            
            // Add quality option for jpeg and webp
            if ((format === 'jpeg' || format === 'webp') && quality !== undefined) {
                screenshotOptions.quality = quality;
            }
            
            // Take screenshot of the element
            const screenshot = await element.screenshot(screenshotOptions) as string;
            
            // Determine browser type for response
            const browserType = useDefaultBrowser && visibleBrowser ? 'default browser' : 'Puppeteer browser';
            const browserMode = visibleBrowser ? 'visible' : 'headless';
            
            return {
                content: [
                    {
                        type: "text",
                        text: `Element screenshot captured successfully!\n\nBrowser: ${browserType} (${browserMode})\nURL: ${url}\nSelector: ${selector}\nFormat: ${format}`
                    },
                    {
                        type: "image",
                        data: screenshot,
                        mimeType: `image/${format}`
                    }
                ],
            };
        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            return {
                isError: true,
                content: [
                    {
                        type: "text",
                        text: `Error capturing element screenshot: ${errorMessage}`,
                    },
                ],
            };
        } finally {
            // Close the page
            if (page) {
                await page.close().catch(() => {});
            }
        }
    }
  • The input schema defined using Zod for the screenshot-element tool parameters.
    {
        url: z.string().url().describe("The URL of the webpage"),
        selector: z.string().describe("CSS selector for the element to screenshot"),
        waitForSelector: z.boolean().optional().default(true).describe("Whether to wait for the selector to appear"),
        format: z.enum(['png', 'jpeg', 'webp']).optional().default('png').describe("Image format for the screenshot"),
        quality: z.number().min(0).max(100).optional().describe("Quality of the image (0-100), only applicable for jpeg and webp"),
        padding: z.number().optional().default(0).describe("Padding around the element in pixels"),
        useSavedAuth: z.boolean().optional().default(true).describe("Whether to use saved cookies from previous login"),
        useDefaultBrowser: z.boolean().optional().default(false).describe("Whether to use the system's default browser instead of Puppeteer's bundled Chromium"),
        visibleBrowser: z.boolean().optional().default(false).describe("Whether to show the browser window (non-headless mode)")
    },
  • src/index.ts:754-901 (registration)
    The registration of the screenshot-element tool using server.tool(), including name, description, schema, and inline handler.
    server.tool(
        "screenshot-element",
        "Captures a screenshot of a specific element on a webpage using a CSS selector",
        {
            url: z.string().url().describe("The URL of the webpage"),
            selector: z.string().describe("CSS selector for the element to screenshot"),
            waitForSelector: z.boolean().optional().default(true).describe("Whether to wait for the selector to appear"),
            format: z.enum(['png', 'jpeg', 'webp']).optional().default('png').describe("Image format for the screenshot"),
            quality: z.number().min(0).max(100).optional().describe("Quality of the image (0-100), only applicable for jpeg and webp"),
            padding: z.number().optional().default(0).describe("Padding around the element in pixels"),
            useSavedAuth: z.boolean().optional().default(true).describe("Whether to use saved cookies from previous login"),
            useDefaultBrowser: z.boolean().optional().default(false).describe("Whether to use the system's default browser instead of Puppeteer's bundled Chromium"),
            visibleBrowser: z.boolean().optional().default(false).describe("Whether to show the browser window (non-headless mode)")
        },
        async ({ url, selector, waitForSelector, format, quality, padding, useSavedAuth, useDefaultBrowser, visibleBrowser }) => {
            let page: Page | null = null;
            
            try {
                // Initialize browser with appropriate options
                const isHeadless = !visibleBrowser;
                const browserInstance = await initBrowser(isHeadless, useDefaultBrowser && visibleBrowser);
                
                // Create a new page
                page = await browserInstance.newPage();
                
                // Load saved cookies if requested
                if (useSavedAuth) {
                    const cookies = await loadCookies(url);
                    if (cookies.length > 0) {
                        await page.setCookie(...cookies);
                    }
                }
                
                // Set viewport (matching screenshot-page tool)
                await page.setViewport({ width: 1920, height: 1080 });
                
                // Set user agent to avoid bot detection
                await page.setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
                
                // Additional anti-detection measures for Google
                await page.evaluateOnNewDocument(() => {
                    // Remove webdriver property
                    delete (window.navigator as any).webdriver;
                    
                    // Override the plugins property to add fake plugins
                    Object.defineProperty(window.navigator, 'plugins', {
                        get: () => [1, 2, 3, 4, 5]
                    });
                    
                    // Override the languages property
                    Object.defineProperty(window.navigator, 'languages', {
                        get: () => ['en-US', 'en']
                    });
                    
                    // Override permissions
                    Object.defineProperty(window.navigator, 'permissions', {
                        get: () => ({
                            query: () => Promise.resolve({ state: 'granted' })
                        })
                    });
                });
                
                // Navigate to the URL
                await page.goto(url, {
                    waitUntil: 'networkidle2',
                    timeout: 30000
                });
                
                // Wait for the selector if requested
                if (waitForSelector) {
                    await page.waitForSelector(selector, { timeout: 10000 });
                }
                
                // Get the element
                const element = await page.$(selector);
                
                if (!element) {
                    return {
                        isError: true,
                        content: [
                            {
                                type: "text",
                                text: `Element not found with selector: ${selector}`,
                            },
                        ],
                    };
                }
                
                // Add padding if requested
                if (padding > 0) {
                    await page.evaluate((sel, pad) => {
                        const el = document.querySelector(sel);
                        if (el) {
                            (el as HTMLElement).style.padding = `${pad}px`;
                        }
                    }, selector, padding);
                }
                
                // Prepare screenshot options
                const screenshotOptions: any = {
                    encoding: 'base64',
                    type: format
                };
                
                // Add quality option for jpeg and webp
                if ((format === 'jpeg' || format === 'webp') && quality !== undefined) {
                    screenshotOptions.quality = quality;
                }
                
                // Take screenshot of the element
                const screenshot = await element.screenshot(screenshotOptions) as string;
                
                // Determine browser type for response
                const browserType = useDefaultBrowser && visibleBrowser ? 'default browser' : 'Puppeteer browser';
                const browserMode = visibleBrowser ? 'visible' : 'headless';
                
                return {
                    content: [
                        {
                            type: "text",
                            text: `Element screenshot captured successfully!\n\nBrowser: ${browserType} (${browserMode})\nURL: ${url}\nSelector: ${selector}\nFormat: ${format}`
                        },
                        {
                            type: "image",
                            data: screenshot,
                            mimeType: `image/${format}`
                        }
                    ],
                };
            } catch (error) {
                const errorMessage = error instanceof Error ? error.message : String(error);
                return {
                    isError: true,
                    content: [
                        {
                            type: "text",
                            text: `Error capturing element screenshot: ${errorMessage}`,
                        },
                    ],
                };
            } finally {
                // Close the page
                if (page) {
                    await page.close().catch(() => {});
                }
            }
        }
    );
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 important behavioral traits like: whether this navigates to new URLs, requires page loading, handles authentication, has rate limits, or what happens with invalid selectors. The description is minimal beyond the core action.

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?

Single sentence, zero waste words, front-loaded with the core action. Every word earns its place by specifying element-level capture with CSS selector mechanism.

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?

For a 9-parameter tool with no annotations and no output schema, the description is inadequate. It doesn't explain what the tool returns (image data? file path? error formats?), doesn't mention authentication dependencies despite sibling login tools, and provides minimal behavioral context for a complex screenshot operation.

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 fully documents all 9 parameters. The description adds no parameter-specific information beyond implying 'selector' and 'url' are involved. Baseline 3 is appropriate when schema does all parameter documentation work.

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 specific action ('Captures a screenshot') and target resource ('specific element on a webpage'), using precise terminology ('CSS selector'). It distinguishes from sibling 'screenshot-page' by specifying element-level rather than page-level capture.

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 explicit guidance on when to use this tool versus alternatives like 'screenshot-page' or other siblings. The description implies usage for element-specific screenshots but doesn't provide context about prerequisites (e.g., needing authentication via login tools) or exclusions.

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

Related 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/ananddtyagi/webpage-screenshot-mcp'

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