Skip to main content
Glama

scrape

Extract specific content from web pages using CSS selectors, with JavaScript rendering options for dynamic sites.

Instructions

Extrai conteúdo inteligente de uma URL específica

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
urlYesURL da página para fazer scraping
selectorNoSeletor CSS para extrair elemento específico
javascriptNoRenderizar JavaScript antes de extrair
timeoutNoTimeout em milissegundos

Implementation Reference

  • Core handler function for the 'scrape' tool. Handles caching, fetches/scrapes HTML using scrapePage helper, extracts structured content, applies optional CSS selector, caches results, and returns a ScrapeResult object.
    export async function scrape(params: ScrapeParams): Promise<ScrapeResult> {
      const { url, selector, javascript = false, timeout = 30000 } = params;
    
      const cached = getFromCache(url);
      if (cached && !selector) {
        return {
          url,
          title: cached.title,
          content: cached.content,
          markdown: cached.markdown,
          fromCache: true,
          timestamp: new Date(cached.cached_at).toISOString(),
        };
      }
    
      try {
        const { html } = await scrapePage(url, { javascript, timeout });
        const extracted = await extractContent(html, url);
    
        if (!extracted) {
          throw new Error("Failed to extract content");
        }
    
        if (!cached) {
          saveToCache(url, {
            content: extracted.textContent,
            markdown: extracted.markdown,
            title: extracted.title,
          });
        }
    
        let selectedContent: string | undefined;
        if (selector) {
          try {
            const dom = new JSDOM(html, { url });
            const element = dom.window.document.querySelector(selector);
            selectedContent = element ? element.textContent || undefined : undefined;
          } catch (e) {
            console.error("Selector error:", e);
          }
        }
    
        return {
          url,
          title: extracted.title,
          content: extracted.textContent,
          markdown: extracted.markdown,
          selectedContent,
          fromCache: false,
          timestamp: new Date().toISOString(),
        };
      } catch (error) {
        console.error("Scrape error:", error);
        throw error;
      }
    }
  • src/index.ts:82-109 (registration)
    Registers the 'scrape' tool with the MCP server, including description, Zod input schema validation, and a thin wrapper that invokes the scrape handler and formats the response as MCP content.
    server.tool(
      "scrape",
      "Extrai conteúdo inteligente de uma URL específica",
      {
        url: z
          .string()
          .url()
          .describe("URL da página para fazer scraping"),
        selector: z
          .string()
          .optional()
          .describe("Seletor CSS para extrair elemento específico"),
        javascript: z
          .boolean()
          .default(false)
          .describe("Renderizar JavaScript antes de extrair"),
        timeout: z
          .number()
          .int()
          .default(30000)
          .describe("Timeout em milissegundos"),
      },
      async (params) => {
        const result = await scrape(params);
        return {
          content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
        };
      }
  • TypeScript interfaces defining the input parameters (ScrapeParams) and output structure (ScrapeResult) for the scrape tool handler.
    interface ScrapeParams {
      url: string;
      selector?: string;
      javascript?: boolean;
      timeout?: number;
    }
    
    interface ScrapeResult {
      url: string;
      title: string;
      content: string;
      markdown: string;
      selectedContent?: string;
      fromCache: boolean;
      timestamp: string;
    }
  • Supporting utility scrapePage: fetches HTML from URL using simple fetch (no JS) or full browser rendering with Playwright Chromium (with JS). Called by the main handler.
    export async function scrapePage(
      url: string,
      options: { javascript?: boolean; timeout?: number } = {}
    ): Promise<ScrapeResult> {
      const { javascript = false, timeout = 30000 } = options;
    
      if (!javascript) {
        try {
          const response = await fetch(url, {
            headers: {
              "User-Agent":
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
            },
          });
          return {
            html: await response.text(),
            status: response.status,
          };
        } catch (error) {
          console.error("Fetch error:", error);
          throw error;
        }
      }
    
      const browser = await chromium.launch();
      try {
        const page = await browser.newPage({
          userAgent:
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
        });
    
        await page.goto(url, { waitUntil: "networkidle", timeout });
        const html = await page.content();
    
        await page.close();
    
        return { html, status: 200 };
      } catch (error) {
        console.error("Browser scraping error:", error);
        throw error;
      } finally {
        await browser.close();
      }
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions 'conteúdo inteligente' which hints at some processing beyond raw HTML, but doesn't specify what 'inteligente' means (e.g., text extraction, summarization, structured data). It lacks details on error handling, rate limits, authentication needs, or output format. For a web scraping tool with no annotation coverage, this is a significant gap.

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 in Portuguese that directly states the tool's purpose. It's appropriately sized for a tool with clear parameters in the schema, with zero wasted words. The structure is front-loaded with the core functionality.

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?

Given the complexity of web scraping (network operations, potential failures, diverse outputs) and the absence of both annotations and an output schema, the description is insufficient. It doesn't explain what 'conteúdo inteligente' returns, how errors are handled, or any behavioral constraints. For a 4-parameter tool with no structured safety or output information, more descriptive context is needed.

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 4 parameters thoroughly. The description adds no parameter-specific information beyond what's in the schema. It implies URL-based extraction but doesn't clarify parameter interactions or usage examples. With high schema coverage, the baseline is 3 even without additional param details in the description.

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 'Extrai conteúdo inteligente de uma URL específica' clearly states the tool's purpose with a specific verb ('extrai') and resource ('conteúdo inteligente de uma URL específica'). It distinguishes from 'fetchFullContent' by implying intelligent extraction rather than full content retrieval, from 'rag' by focusing on web scraping rather than retrieval-augmented generation, and from 'screenshot' by extracting content rather than capturing images. However, it doesn't explicitly contrast with all siblings.

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 like 'fetchFullContent', 'rag', or 'screenshot'. It doesn't mention prerequisites, constraints, or typical use cases. The agent must infer usage from the tool name and description alone without explicit direction.

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/alucardeht/isis-mcp'

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