Skip to main content
Glama

capture-screenshot

Capture webpage screenshots for Vite Dev Server integration, storing images as MCP resources with optional element targeting and base64 encoding.

Instructions

Captures a screenshot of the current page or a specific element. Stores the screenshot in the MCP resource system and returns a resource URI. If ENABLE_BASE64 environment variable is set to 'true', also includes base64 encoded image in the response.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
selectorNoCSS selector to capture (captures full page if not provided)
urlNoURL to navigate to before capturing screenshot. Do not provide if you want to capture the current page.
contextIdNoBrowser ID to capture from (uses most recent browser if not provided)

Implementation Reference

  • Main handler function that performs the screenshot capture using Playwright. Handles browser context selection, optional navigation, element/full-page screenshot, saving via helper, and returns resource URI with optional base64 image.
    async ({ selector, url, contextId }) => {
      try {
        // Get browser for operation
        const browserStatus = getContextForOperation(contextId);
        if (!browserStatus.isStarted) {
          return browserStatus.error;
        }
    
        // Get current URL
        const currentUrl = browserStatus.page.url();
    
        // If URL is provided and different from current URL, navigate to it
        if (url && url !== currentUrl) {
          Logger.info(`Navigating to ${url} before capturing screenshot`);
          await browserStatus.page.goto(url, { waitUntil: 'networkidle' });
        }
    
        // Get current checkpoint ID
        const checkpointId = await getCurrentCheckpointId(browserStatus.page);
    
        let screenshot: Buffer;
    
        if (selector) {
          // Wait for element to appear
          await browserStatus.page.waitForSelector(selector, { state: 'visible', timeout: 5000 });
          const element = await browserStatus.page.locator(selector).first();
    
          if (!element) {
            return {
              content: [
                {
                  type: 'text',
                  text: `Element with selector "${selector}" not found`
                }
              ],
              isError: true
            };
          }
    
          screenshot = await element.screenshot();
        } else {
          // Capture full page
          screenshot = await browserStatus.page.screenshot({ fullPage: true });
        }
    
        // Get final URL (may be different after navigation)
        const finalUrl = browserStatus.page.url();
    
        // Use screenshot helpers if available
        if (!screenshotHelpers) {
          return {
            content: [
              {
                type: 'text',
                text: 'Screenshot helpers not available. Cannot save screenshot.'
              }
            ],
            isError: true
          };
        }
    
        // Add screenshot using the resource system
        const description = selector
          ? `Screenshot of element ${selector} at ${finalUrl}`
          : `Screenshot of full page at ${finalUrl}`;
    
        // Get browser context from the actual browser instance
        let browserContext = {};
        if (contextId) {
          const contextInstance = contextManager.getContext(contextId);
          if (contextInstance) {
            browserContext = {
              browser_id: contextInstance.id,
              browser_type: contextInstance.type,
              session_id: `${contextInstance.id}-${contextInstance.createdAt.getTime()}`
            };
          }
        } else {
          const contextInstance = contextManager.getMostRecentContext();
          if (contextInstance) {
            browserContext = {
              browser_id: contextInstance.id,
              browser_type: contextInstance.type,
              session_id: `${contextInstance.id}-${contextInstance.createdAt.getTime()}`
            };
          }
        }
    
        const screenshotResult = await screenshotHelpers.addScreenshot(
          screenshot,
          description,
          checkpointId,
          finalUrl.replace(/^http(s)?:\/\//, ''),
          browserContext
        );
    
        Logger.info(`Screenshot saved with ID: ${screenshotResult.id}, URI: ${screenshotResult.resourceUri}`);
    
        // Result message construction
        const resultMessage = {
          message: 'Screenshot captured successfully',
          id: screenshotResult.id,
          resourceUri: screenshotResult.resourceUri,
          checkpointId,
          url: finalUrl,
        };
    
        // Build content array
        const content: Array<{ type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }> = [
          {
            type: 'text' as const,
            text: JSON.stringify(resultMessage, null, 2)
          }
        ];
    
        // Add base64 image only if ENABLE_BASE64 is true
        if (ENABLE_BASE64) {
          content.push({
            type: 'image' as const,
            data: screenshot.toString('base64'),
            mimeType: 'image/png'
          });
        }
    
        return {
          content
        };
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        Logger.error(`Failed to capture screenshot: ${errorMessage}`);
        return {
          content: [
            {
              type: 'text',
              text: `Failed to capture screenshot: ${errorMessage}`
            }
          ],
          isError: true
        };
      }
    }
  • Input schema using Zod validation for tool parameters: selector (optional CSS selector), url (optional navigation URL), contextId (optional browser ID).
      selector: z.string().optional().describe('CSS selector to capture (captures full page if not provided)'),
      url: z.string().optional().describe('URL to navigate to before capturing screenshot. Do not provide if you want to capture the current page.'),
      contextId: z.string().optional().describe('Browser ID to capture from (uses most recent browser if not provided)')
    },
  • Registers the 'capture-screenshot' tool on the MCP server within registerBrowserTools function.
      server.tool(
        'capture-screenshot',
        `Captures a screenshot of the current page or a specific element.
    Stores the screenshot in the MCP resource system and returns a resource URI.
    If ENABLE_BASE64 environment variable is set to 'true', also includes base64 encoded image in the response.`,
        {
          selector: z.string().optional().describe('CSS selector to capture (captures full page if not provided)'),
          url: z.string().optional().describe('URL to navigate to before capturing screenshot. Do not provide if you want to capture the current page.'),
          contextId: z.string().optional().describe('Browser ID to capture from (uses most recent browser if not provided)')
        },
        async ({ selector, url, contextId }) => {
          try {
            // Get browser for operation
            const browserStatus = getContextForOperation(contextId);
            if (!browserStatus.isStarted) {
              return browserStatus.error;
            }
    
            // Get current URL
            const currentUrl = browserStatus.page.url();
    
            // If URL is provided and different from current URL, navigate to it
            if (url && url !== currentUrl) {
              Logger.info(`Navigating to ${url} before capturing screenshot`);
              await browserStatus.page.goto(url, { waitUntil: 'networkidle' });
            }
    
            // Get current checkpoint ID
            const checkpointId = await getCurrentCheckpointId(browserStatus.page);
    
            let screenshot: Buffer;
    
            if (selector) {
              // Wait for element to appear
              await browserStatus.page.waitForSelector(selector, { state: 'visible', timeout: 5000 });
              const element = await browserStatus.page.locator(selector).first();
    
              if (!element) {
                return {
                  content: [
                    {
                      type: 'text',
                      text: `Element with selector "${selector}" not found`
                    }
                  ],
                  isError: true
                };
              }
    
              screenshot = await element.screenshot();
            } else {
              // Capture full page
              screenshot = await browserStatus.page.screenshot({ fullPage: true });
            }
    
            // Get final URL (may be different after navigation)
            const finalUrl = browserStatus.page.url();
    
            // Use screenshot helpers if available
            if (!screenshotHelpers) {
              return {
                content: [
                  {
                    type: 'text',
                    text: 'Screenshot helpers not available. Cannot save screenshot.'
                  }
                ],
                isError: true
              };
            }
    
            // Add screenshot using the resource system
            const description = selector
              ? `Screenshot of element ${selector} at ${finalUrl}`
              : `Screenshot of full page at ${finalUrl}`;
    
            // Get browser context from the actual browser instance
            let browserContext = {};
            if (contextId) {
              const contextInstance = contextManager.getContext(contextId);
              if (contextInstance) {
                browserContext = {
                  browser_id: contextInstance.id,
                  browser_type: contextInstance.type,
                  session_id: `${contextInstance.id}-${contextInstance.createdAt.getTime()}`
                };
              }
            } else {
              const contextInstance = contextManager.getMostRecentContext();
              if (contextInstance) {
                browserContext = {
                  browser_id: contextInstance.id,
                  browser_type: contextInstance.type,
                  session_id: `${contextInstance.id}-${contextInstance.createdAt.getTime()}`
                };
              }
            }
    
            const screenshotResult = await screenshotHelpers.addScreenshot(
              screenshot,
              description,
              checkpointId,
              finalUrl.replace(/^http(s)?:\/\//, ''),
              browserContext
            );
    
            Logger.info(`Screenshot saved with ID: ${screenshotResult.id}, URI: ${screenshotResult.resourceUri}`);
    
            // Result message construction
            const resultMessage = {
              message: 'Screenshot captured successfully',
              id: screenshotResult.id,
              resourceUri: screenshotResult.resourceUri,
              checkpointId,
              url: finalUrl,
            };
    
            // Build content array
            const content: Array<{ type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }> = [
              {
                type: 'text' as const,
                text: JSON.stringify(resultMessage, null, 2)
              }
            ];
    
            // Add base64 image only if ENABLE_BASE64 is true
            if (ENABLE_BASE64) {
              content.push({
                type: 'image' as const,
                data: screenshot.toString('base64'),
                mimeType: 'image/png'
              });
            }
    
            return {
              content
            };
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            Logger.error(`Failed to capture screenshot: ${errorMessage}`);
            return {
              content: [
                {
                  type: 'text',
                  text: `Failed to capture screenshot: ${errorMessage}`
                }
              ],
              isError: true
            };
          }
        }
      );
  • Helper function addScreenshot that persists the screenshot image to disk and SQLite database, generates MCP resource URI, used by the capture-screenshot handler.
    addScreenshot: async (
      imageData: string | Buffer,
      description: string,
      checkpointId: string | null = null,
      url?: string,
      browserContext?: { browser_id?: string; browser_type?: string; session_id?: string }
    ): Promise<{ id: string; resourceUri: string }> => {
      const id = randomUUID();
    
      // Create filename and save
      const filename = `${id}.png`;
      const filePath = path.join(SCREENSHOTS_DIRECTORY, filename);
    
      // Save data to file
      if (typeof imageData === 'string') {
        // Convert base64 string if needed
        await fs.writeFile(filePath, Buffer.from(imageData, 'base64'));
      } else {
        // Save Buffer directly
        await fs.writeFile(filePath, imageData);
      }
      Logger.info(`External screenshot saved to file: ${filePath}`);
    
      // Save to database
      let resourceUri: string;
    
      if (url) {
        const parsed = db.parseUrl(url);
        Logger.info(`[addScreenshot] Saving screenshot with URL: ${url}`);
        Logger.info(`[addScreenshot] Parsed - hostname: ${parsed.hostname}, pathname: ${parsed.pathname}`);
    
        db.insert({
          id,
          hostname: parsed.hostname,
          pathname: parsed.pathname,
          query: parsed.query || null,
          hash: parsed.hash || null,
          checkpoint_id: checkpointId,
          timestamp: new Date(),
          mime_type: 'image/png',
          description,
          browser_id: browserContext?.browser_id,
          browser_type: browserContext?.browser_type,
          session_id: browserContext?.session_id
        });
        Logger.info(`[addScreenshot] Screenshot saved to database with ID: ${id}`);
    
        // Return hostname/path based URI
        resourceUri = `screenshot://${parsed.hostname}${parsed.pathname}`;
      } else {
        // If no URL, save with empty hostname/pathname
        db.insert({
          id,
          hostname: 'unknown',
          pathname: '/',
          query: null,
          hash: null,
          checkpoint_id: checkpointId,
          timestamp: new Date(),
          mime_type: 'image/png',
          description,
          browser_id: browserContext?.browser_id,
          browser_type: browserContext?.browser_type,
          session_id: browserContext?.session_id
        });
        Logger.info(`Screenshot saved to database with ID: ${id} (no URL)`);
    
        // Return ID-based URI for unknown URLs
        resourceUri = getScreenshotUri(id);
      }
    
      return { id, resourceUri };
    },
  • src/index.ts:87-92 (registration)
    Wires up the browser tools registration including capture-screenshot by calling registerBrowserTools with screenshotHelpers.
    registerBrowserTools(
      server,
      contextManager,
      lastHMREvents,
      screenshotHelpers
    );
Behavior4/5

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

With no annotations provided, the description carries full burden and does well by disclosing key behaviors: it stores the screenshot in the MCP resource system, returns a resource URI, and conditionally includes base64 encoding based on an environment variable. However, it doesn't mention potential side effects like navigation when using the 'url' parameter or performance implications.

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 perfectly concise with three focused sentences: the core functionality, the storage/return mechanism, and the conditional base64 behavior. Every sentence adds essential information with zero wasted words, and it's front-loaded with the primary purpose.

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 tool with 3 parameters, 100% schema coverage, and no output schema, the description provides good context about the storage mechanism and conditional response format. However, it doesn't explain what the resource URI format looks like or how to use it, leaving a minor gap in completeness.

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 already fully documents all three parameters. The description adds no additional parameter semantics beyond what's in the schema descriptions, maintaining the baseline score of 3 for adequate but not enhanced parameter documentation.

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'), the target ('current page or a specific element'), and the outcome ('stores the screenshot in the MCP resource system and returns a resource URI'). It distinguishes itself from sibling tools like 'get-element-dimensions' or 'get-element-html' by focusing on visual capture rather than data extraction or measurement.

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?

The description implies usage for capturing screenshots from web pages, but provides no explicit guidance on when to use this tool versus alternatives like 'get-element-dimensions' for measurements or 'monitor-network' for network activity. It mentions an environment variable condition but doesn't address tool selection context.

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