Quickstart for LLMs and agent builders

This page shows how to give your own agent a screenshot tool by calling the GetScreenshot REST API directly. You define one function, call one GET endpoint in the handler, and pass the image back to the model. If your agent runs inside an MCP client, the MCP Server does the same job with no code.

Sections in this article

The API in one request

curl "https://api.rasterwise.com/v1/get-screenshot?apikey=$GETSCREENSHOT_API_KEY&url=https%3A%2F%2Fexample.com"
{
  "status": "success",
  "originUrl": "https://example.com",
  "pageStatus": 200,
  "captureDate": "2026/11/18",
  "captureHour": "14:03:22",
  "aiAnalysis": null,
  "screenshotImage": "https://storage.googleapis.com/getscreenshot-storage/imageAbC123xYz9.png"
}

What a tool handler needs to know:

  • The endpoint is GET only. Every option is a query parameter.
  • Authentication is the apikey query parameter. There is no header authentication.
  • The response is always JSON. It never contains image bytes. Download the file at screenshotImage in a second request.
  • screenshotImage is a public URL that works for 30 days. Anyone with the link can fetch it.
  • A capture typically takes about 9 seconds, and slow pages around 25. The API gives up after 90 seconds, so set your HTTP timeout above that.
  • Every authenticated request uses one screenshot of the monthly quota, including captures that fail.
  • The capture runs on GetScreenshot’s servers. It cannot reach localhost or hosts on a private network.

All parameters are listed in the API reference.

Tool definition

Paste this into your agent’s tool list. It uses the Anthropic Messages API shape, where the JSON Schema sits under input_schema:

{
  "name": "get_screenshot",
  "description": "Take a screenshot of a public web page and return it as an image. Use it to see how a page looks: layout, visual bugs, and content that only appears after JavaScript runs. It cannot reach localhost or private networks. A call takes about 10 seconds.",
  "input_schema": {
    "type": "object",
    "properties": {
      "url": {
        "type": "string",
        "description": "Public http or https URL of the page. URL shorteners are rejected."
      },
      "full_page": {
        "type": "boolean",
        "description": "Capture the full scrollable page instead of the viewport. Tall pages produce large images. Default false."
      },
      "element": {
        "type": "string",
        "description": "CSS selector. Capture only this element. The call fails if nothing matches."
      },
      "width": {
        "type": "integer",
        "description": "Viewport width in CSS pixels. Default 1280. Use 390 for a phone-sized layout."
      },
      "height": {
        "type": "integer",
        "description": "Viewport height in CSS pixels. Default 800. Use 844 for a phone-sized layout."
      },
      "wait_until": {
        "type": "string",
        "enum": ["load", "domcontentloaded", "networkidle0", "networkidle2"],
        "description": "When the page counts as loaded. Default networkidle2. Use domcontentloaded if a capture times out."
      }
    },
    "required": ["url"]
  }
}

Other providers take the same JSON Schema under a different key. OpenAI-style function calling, for example, expects it under parameters.

Handler in Python

The handler calls the API, downloads the image, and returns it as a base64 image block inside the tool_result. Save the tool definition above as get_screenshot_tool.json next to the script.

import base64
import json
import os

import anthropic
import requests

API_URL = "https://api.rasterwise.com/v1/get-screenshot"

with open("get_screenshot_tool.json") as f:
    TOOL = json.load(f)


def get_screenshot(url, full_page=False, element=None, width=1280, height=800, wait_until=None):
    """Capture a page and return content blocks for a tool_result."""
    params = {
        "apikey": os.environ["GETSCREENSHOT_API_KEY"],
        "url": url,
        "width": width,
        "height": height,
        "format": "jpeg",
    }
    if full_page:
        params["fullpage"] = "true"
    if element:
        params["element"] = element
    if wait_until:
        params["waituntil"] = wait_until

    resp = requests.get(API_URL, params=params, timeout=100)
    try:
        data = resp.json()
    except ValueError:
        data = None  # some errors are plain text, not JSON
    if not isinstance(data, dict):
        data = {}
    if resp.status_code != 200 or data.get("status") != "success":
        message = data.get("message") or resp.text[:200]
        raise RuntimeError(f"Screenshot failed (HTTP {resp.status_code}): {message}")

    image = requests.get(data["screenshotImage"], timeout=30)
    image.raise_for_status()

    summary = (
        f"Screenshot of {data['originUrl']}. The page returned HTTP {data['pageStatus']}. "
        f"Full-size image: {data['screenshotImage']}"
    )
    return [
        {
            "type": "image",
            "source": {
                "type": "base64",
                "media_type": "image/jpeg",
                "data": base64.standard_b64encode(image.content).decode("ascii"),
            },
        },
        {"type": "text", "text": summary},
    ]


client = anthropic.Anthropic()
messages = [
    {"role": "user", "content": "Look at https://example.com and describe the page layout."}
]

while True:
    response = client.messages.create(
        model="claude-sonnet-5-5",
        max_tokens=16000,
        tools=[TOOL],
        messages=messages,
    )
    if response.stop_reason != "tool_use":
        break

    messages.append({"role": "assistant", "content": response.content})

    results = []
    for block in response.content:
        if block.type != "tool_use":
            continue
        try:
            content = get_screenshot(**block.input)
            results.append({"type": "tool_result", "tool_use_id": block.id, "content": content})
        except Exception as err:
            results.append(
                {"type": "tool_result", "tool_use_id": block.id, "content": str(err), "is_error": True}
            )
    messages.append({"role": "user", "content": results})

print("".join(block.text for block in response.content if block.type == "text"))

Install the dependencies with pip install anthropic requests. The Anthropic client reads ANTHROPIC_API_KEY from the environment.

Handler in TypeScript

The same flow with the official TypeScript SDK and the built-in fetch of Node.js 18 or later:

import Anthropic from "@anthropic-ai/sdk";
import { readFileSync } from "node:fs";

const API_URL = "https://api.rasterwise.com/v1/get-screenshot";

const tool: Anthropic.Tool = JSON.parse(readFileSync("get_screenshot_tool.json", "utf8"));

type ScreenshotInput = {
  url: string;
  full_page?: boolean;
  element?: string;
  width?: number;
  height?: number;
  wait_until?: string;
};

type ToolResultContent = Anthropic.ToolResultBlockParam["content"];

async function getScreenshot(input: ScreenshotInput): Promise<ToolResultContent> {
  const params = new URLSearchParams({
    apikey: process.env.GETSCREENSHOT_API_KEY ?? "",
    url: input.url,
    width: String(input.width ?? 1280),
    height: String(input.height ?? 800),
    format: "jpeg",
  });
  if (input.full_page) params.set("fullpage", "true");
  if (input.element) params.set("element", input.element);
  if (input.wait_until) params.set("waituntil", input.wait_until);

  const res = await fetch(`${API_URL}?${params}`, { signal: AbortSignal.timeout(100_000) });
  const body = await res.text();
  let data: Record<string, any> = {};
  try {
    const parsed = JSON.parse(body);
    if (parsed && typeof parsed === "object") data = parsed;
  } catch {
    // some errors are plain text, not JSON
  }
  if (!res.ok || data.status !== "success") {
    throw new Error(`Screenshot failed (HTTP ${res.status}): ${data.message ?? body.slice(0, 200)}`);
  }

  const image = await fetch(data.screenshotImage);
  if (!image.ok) throw new Error(`Could not download the screenshot (HTTP ${image.status})`);
  const base64 = Buffer.from(await image.arrayBuffer()).toString("base64");

  return [
    { type: "image", source: { type: "base64", media_type: "image/jpeg", data: base64 } },
    {
      type: "text",
      text: `Screenshot of ${data.originUrl}. The page returned HTTP ${data.pageStatus}. Full-size image: ${data.screenshotImage}`,
    },
  ];
}

const client = new Anthropic();
const messages: Anthropic.MessageParam[] = [
  { role: "user", content: "Look at https://example.com and describe the page layout." },
];

let response = await client.messages.create({
  model: "claude-sonnet-5-5",
  max_tokens: 16000,
  tools: [tool],
  messages,
});

while (response.stop_reason === "tool_use") {
  messages.push({ role: "assistant", content: response.content });

  const results: Anthropic.ToolResultBlockParam[] = [];
  for (const block of response.content) {
    if (block.type !== "tool_use") continue;
    try {
      const content = await getScreenshot(block.input as ScreenshotInput);
      results.push({ type: "tool_result", tool_use_id: block.id, content });
    } catch (err) {
      results.push({ type: "tool_result", tool_use_id: block.id, content: String(err), is_error: true });
    }
  }
  messages.push({ role: "user", content: results });

  response = await client.messages.create({
    model: "claude-sonnet-5-5",
    max_tokens: 16000,
    tools: [tool],
    messages,
  });
}

for (const block of response.content) {
  if (block.type === "text") console.log(block.text);
}

Install the SDK with npm install @anthropic-ai/sdk and run the file as an ES module.

Other providers

The pattern is the same everywhere:

  1. Declare the function with the JSON Schema above.
  2. In the handler, call the API and read screenshotImage from the JSON.
  3. Give the image to the model as an image input, either as base64 bytes or as the URL itself where the provider accepts image URLs.

Some providers only accept text in a tool or function result. In that case return a short text result, such as the URL and the page status, and attach the image to the next user message.

Image size and tokens

Vision models charge for images by pixel area, so the viewport you ask for decides the cost. The figures below are approximate and use ceil(width / 28) × ceil(height / 28), which follows how Claude models count image tokens.

Capture Image size Approximate tokens
Default viewport 1280 x 800 1,334
Phone-sized viewport, width=390&height=844 390 x 844 434
Default viewport with devicefactor=2 2560 x 1600 5,336 before the model downscales it
Full page, 1280 wide and 6,000 px tall 1280 x 6000 9,890 before the model downscales it

Guidance:

  • Keep the default 1280 x 800 viewport for a first look. It is enough to judge layout and read normal-sized text.
  • Leave devicefactor at 1. A retina capture has four times the pixels, and most models scale it back down before reading it.
  • Be careful with fullpage=true. A long page becomes one very tall image. Models shrink oversized images to fit their limits, which makes text unreadable, and providers reject images above their size limits. Capture an element instead, or cut the image into viewport-sized slices before sending it.
  • format=jpeg makes the download smaller. It does not change the token cost, which depends on pixel dimensions.
  • Cookie banners are hidden by default. Add hidemsg=true to hide chat widgets as well.

The MCP Server does this sizing for you. It downsizes captures, slices full pages, and reports an estimated token cost per image.

Error handling

Return errors to the model as a tool result marked as an error, with a message that says what to do next. These are the responses your handler will see:

HTTP Body Meaning What the agent should do next
401 {"message":"Unauthorized"} The apikey parameter is missing. Stop. This is a configuration problem for the developer.
500 {"message": "error"} The API key is not recognised. This case usually returns 500, not 401. Stop and report that the key is invalid. Do not retry.
403 {"message":"Forbidden"} The key exists but is disabled, because the subscription was cancelled or a payment failed. An unrecognised key can also get this answer. Stop and tell the user to check the key and their account.
429 {"message":"Limit Exceeded"} The monthly quota is used up. Stop capturing until the quota resets.
429 {"message":"Too Many Requests"} Rate limited. Wait a few seconds and retry with backoff.
400 {"status":"denied","message":"Bad posture."} url is missing or is not a valid http or https URL. Fix the URL and call again.
403 {"status":"denied","message":"Access denied - URL not allowed (shortener or blocked domain)"} The URL is a shortener or a blocked domain. Use the final destination URL.
500 {"status":"failed","message":"Could not load the target page within the time limit. ..."} The page is slow, offline, or blocks automated browsers. Retry once with wait_until set to domcontentloaded. If it fails again, report it.
500 Plain text Internal Server Error, not JSON The capture crashed. Most often the element selector matched nothing. Check the selector, or retry without element.
504 {"message": "error"} The capture took longer than 90 seconds. Retry once with domcontentloaded and without full_page.

Two details matter for the handler:

  • Not every error body is JSON, so parse defensively. Both samples above do.
  • An unrecognised key and a timeout both return {"message": "error"}. Tell them apart by the status code: 500 for the key, 504 for the timeout.

Failed captures still count toward the quota. Tell the model to retry at most once, with different settings, instead of repeating the same call.

Machine-readable references


CLI and Agent Skill
Integrate with Zapier

Related Docs