Skip to main content
Glama

spa_screenshot

Capture screenshots of JavaScript Single Page Applications after full rendering. Use a headless browser to execute scripts and generate PNG images of web pages.

Instructions

Take a screenshot of a JavaScript SPA page after rendering. Uses a headless browser to execute JavaScript and capture the visual output as PNG.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
urlYesThe URL to screenshot
waitForSelectorNoCSS selector to wait for before capturing
waitTimeoutNoNavigation timeout in ms (default: 30000)
widthNoViewport width in pixels (default: 1280)
heightNoViewport height in pixels (default: 720)
fullPageNoCapture full scrollable page (default: false)
cookiesNoCookies to inject before screenshot
headersNoCustom HTTP headers

Implementation Reference

  • The main handler function that executes the spa_screenshot tool logic. It processes input parameters, calls takeScreenshot helper, converts the buffer to base64, and returns the image content or error.
    async ({ url, waitForSelector, waitTimeout, width, height, fullPage, cookies, headers }) => {
      try {
        const viewport =
          width !== undefined || height !== undefined
            ? { width: width ?? 1280, height: height ?? 720 }
            : undefined;
    
        const buffer = await takeScreenshot({
          url,
          waitForSelector,
          waitTimeout,
          viewport,
          fullPage,
          cookies,
          headers,
        });
    
        const base64 = buffer.toString("base64");
    
        return {
          content: [
            {
              type: "image" as const,
              data: base64,
              mimeType: "image/png",
            },
          ],
        };
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
          content: [
            {
              type: "text" as const,
              text: `Error capturing screenshot of ${url}: ${message}`,
            },
          ],
          isError: true,
        };
      }
    },
  • Registers the spa_screenshot tool with the MCP server, defining the tool name, description, Zod schema for input validation (url, waitForSelector, waitTimeout, width, height, fullPage, cookies, headers), and the async handler.
    export function registerSpaScreenshotTool(server: McpServer): void {
      server.tool(
        "spa_screenshot",
        "Take a screenshot of a JavaScript SPA page after rendering. " +
          "Uses a headless browser to execute JavaScript and capture the visual output as PNG.",
        {
          url: z.string().url().describe("The URL to screenshot"),
          waitForSelector: z
            .string()
            .optional()
            .describe("CSS selector to wait for before capturing"),
          waitTimeout: z
            .number()
            .min(1000)
            .max(120000)
            .optional()
            .describe("Navigation timeout in ms (default: 30000)"),
          width: z
            .number()
            .min(320)
            .max(3840)
            .optional()
            .describe("Viewport width in pixels (default: 1280)"),
          height: z
            .number()
            .min(240)
            .max(2160)
            .optional()
            .describe("Viewport height in pixels (default: 720)"),
          fullPage: z
            .boolean()
            .optional()
            .describe("Capture full scrollable page (default: false)"),
          cookies: z
            .array(cookieSchema)
            .optional()
            .describe("Cookies to inject before screenshot"),
          headers: z
            .record(z.string(), z.string())
            .optional()
            .describe("Custom HTTP headers"),
        },
        async ({ url, waitForSelector, waitTimeout, width, height, fullPage, cookies, headers }) => {
          try {
            const viewport =
              width !== undefined || height !== undefined
                ? { width: width ?? 1280, height: height ?? 720 }
                : undefined;
    
            const buffer = await takeScreenshot({
              url,
              waitForSelector,
              waitTimeout,
              viewport,
              fullPage,
              cookies,
              headers,
            });
    
            const base64 = buffer.toString("base64");
    
            return {
              content: [
                {
                  type: "image" as const,
                  data: base64,
                  mimeType: "image/png",
                },
              ],
            };
          } catch (error) {
            const message = error instanceof Error ? error.message : String(error);
            return {
              content: [
                {
                  type: "text" as const,
                  text: `Error capturing screenshot of ${url}: ${message}`,
                },
              ],
              isError: true,
            };
          }
        },
      );
    }
  • Input schema definitions using Zod: cookieSchema (lines 9-18) for cookie validation and the main tool parameters schema (lines 25-61) with url, waitForSelector, waitTimeout, width, height, fullPage, cookies, and headers fields.
    const cookieSchema = z.object({
      name: z.string().min(1).describe("Cookie name"),
      value: z.string().describe("Cookie value"),
      domain: z.string().optional().describe("Cookie domain (auto-inferred from URL if omitted)"),
      path: z.string().optional().describe("Cookie path (default: '/')"),
      secure: z.boolean().optional().describe("Secure flag"),
      httpOnly: z.boolean().optional().describe("HttpOnly flag"),
      expires: z.number().optional().describe("Expiration timestamp"),
      sameSite: z.enum(["Strict", "Lax", "None"]).optional().describe("SameSite attribute"),
    });
    
    export function registerSpaScreenshotTool(server: McpServer): void {
      server.tool(
        "spa_screenshot",
        "Take a screenshot of a JavaScript SPA page after rendering. " +
          "Uses a headless browser to execute JavaScript and capture the visual output as PNG.",
        {
          url: z.string().url().describe("The URL to screenshot"),
          waitForSelector: z
            .string()
            .optional()
            .describe("CSS selector to wait for before capturing"),
          waitTimeout: z
            .number()
            .min(1000)
            .max(120000)
            .optional()
            .describe("Navigation timeout in ms (default: 30000)"),
          width: z
            .number()
            .min(320)
            .max(3840)
            .optional()
            .describe("Viewport width in pixels (default: 1280)"),
          height: z
            .number()
            .min(240)
            .max(2160)
            .optional()
            .describe("Viewport height in pixels (default: 720)"),
          fullPage: z
            .boolean()
            .optional()
            .describe("Capture full scrollable page (default: false)"),
          cookies: z
            .array(cookieSchema)
            .optional()
            .describe("Cookies to inject before screenshot"),
          headers: z
            .record(z.string(), z.string())
            .optional()
            .describe("Custom HTTP headers"),
        },
  • The takeScreenshot helper function that uses Playwright to launch a headless browser, navigate to the URL, wait for rendering, and capture a PNG screenshot. Handles viewport configuration, cookies, headers, and full-page capture.
    export async function takeScreenshot(options: ScreenshotOptions): Promise<Buffer> {
      const { parsedUrl, timeout, resolvedCookies, cleanedHeaders } = validateOptions(options);
      const width = options.viewport?.width ?? DEFAULT_VIEWPORT_WIDTH;
      const height = options.viewport?.height ?? DEFAULT_VIEWPORT_HEIGHT;
    
      const browser = await getBrowser();
      const viewportSize = { width, height };
      const context: BrowserContext = await browser.newContext({
        userAgent: "spa-reader-mcp/1.0.0",
        viewport: viewportSize,
        screen: viewportSize,
        extraHTTPHeaders: Object.keys(cleanedHeaders).length > 0 ? cleanedHeaders : undefined,
      });
    
      try {
        if (resolvedCookies.length > 0) {
          await context.addCookies(resolvedCookies);
        }
    
        const page = await context.newPage();
        await page.setViewportSize(viewportSize);
        await navigateAndWait(page, options, parsedUrl, timeout);
    
        const screenshot = await page.screenshot({
          fullPage: options.fullPage ?? false,
          type: "png",
        });
    
        return Buffer.from(screenshot);
      } finally {
        await context.close();
      }
    }
  • TypeScript interface ScreenshotOptions extending RenderOptions with optional viewport (width/height) and fullPage boolean properties.
    export interface ScreenshotOptions extends RenderOptions {
      readonly viewport?: ViewportConfig;
      readonly fullPage?: boolean;
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions the headless browser method and PNG output format, but lacks critical details like authentication requirements, rate limits, error conditions, or whether the operation is idempotent. For a complex tool with 8 parameters, this is insufficient.

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 two sentences that directly communicate the tool's purpose and method. Every word earns its place with zero redundancy or unnecessary elaboration.

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 complex tool with 8 parameters, no annotations, and no output schema, the description is incomplete. It lacks information about return values, error handling, performance characteristics, and operational constraints that would help an agent use it effectively.

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 documents all parameters thoroughly. The description adds no parameter-specific information beyond what's in the schema, 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 ('Take a screenshot'), target resource ('JavaScript SPA page'), and method ('Uses a headless browser to execute JavaScript and capture the visual output as PNG'). It distinguishes from the sibling tool 'spa_read' by focusing on visual capture rather than content reading.

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, nor does it mention any prerequisites or exclusions. It simply states what the tool does without contextual usage information.

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/XXO47OXX/spa-reader-mcp'

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