Skip to main content
Glama
dylangroos

Patchright Lite MCP Server

by dylangroos

extract

Extract text, HTML, or screenshots from web pages using browser automation while avoiding bot detection.

Instructions

Extract information from the current page as text, html, or screenshot

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
browserIdYesBrowser ID from a previous browse operation
pageIdYesPage ID from a previous browse operation
typeYesType of content to extract

Implementation Reference

  • src/index.ts:217-293 (registration)
    Registration of the 'extract' tool using server.tool, including name, description, schema, and handler function.
    server.tool(
      "extract",
      "Extract information from the current page as text, html, or screenshot",
      {
        browserId: z.string().describe("Browser ID from a previous browse operation"),
        pageId: z.string().describe("Page ID from a previous browse operation"),
        type: z.enum(["text", "html", "screenshot"]).describe("Type of content to extract")
      },
      async ({ browserId, pageId, type }: { 
        browserId: string; 
        pageId: string; 
        type: "text" | "html" | "screenshot" 
      }) => {
        try {
          // Get the browser instance and page
          const instance = browserInstances.get(browserId);
          if (!instance) {
            throw new Error(`Browser instance not found: ${browserId}`);
          }
          
          const page = instance.pages.get(pageId);
          if (!page) {
            throw new Error(`Page not found: ${pageId}`);
          }
          
          let extractedContent = '';
          let screenshotPath = '';
          
          // Extract content based on requested type
          switch (type) {
            case "text":
              // Get visible text with stealth isolation
              extractedContent = await page.evaluate(`
                Array.from(document.querySelectorAll('body, body *'))
                  .filter(element => {
                    const style = window.getComputedStyle(element);
                    return style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0';
                  })
                  .map(element => element.textContent)
                  .filter(text => text && text.trim().length > 0)
                  .join('\\n')
              `) as string;
              break;
            case "html":
              // Get HTML content
              extractedContent = await page.content();
              break;
            case "screenshot":
              // Take a screenshot
              screenshotPath = path.join(TEMP_DIR, `screenshot-${pageId}-${Date.now()}.png`);
              await page.screenshot({ path: screenshotPath });
              extractedContent = `Screenshot saved to: ${screenshotPath}`;
              break;
          }
          
          return {
            content: [
              {
                type: "text",
                text: type === "text" || type === "screenshot" 
                  ? extractedContent.substring(0, 2000) + (extractedContent.length > 2000 ? '...' : '')
                  : `Extracted HTML content (${extractedContent.length} characters). First 100 characters:\n${extractedContent.substring(0, 100)}...`
              }
            ]
          };
        } catch (error) {
          return {
            content: [
              {
                type: "text",
                text: `Failed to extract content: ${error}`
              }
            ]
          };
        }
      }
    );
  • Handler function for the 'extract' tool that retrieves text, HTML, or screenshot from the specified page using Patchright/Playwright.
    async ({ browserId, pageId, type }: { 
      browserId: string; 
      pageId: string; 
      type: "text" | "html" | "screenshot" 
    }) => {
      try {
        // Get the browser instance and page
        const instance = browserInstances.get(browserId);
        if (!instance) {
          throw new Error(`Browser instance not found: ${browserId}`);
        }
        
        const page = instance.pages.get(pageId);
        if (!page) {
          throw new Error(`Page not found: ${pageId}`);
        }
        
        let extractedContent = '';
        let screenshotPath = '';
        
        // Extract content based on requested type
        switch (type) {
          case "text":
            // Get visible text with stealth isolation
            extractedContent = await page.evaluate(`
              Array.from(document.querySelectorAll('body, body *'))
                .filter(element => {
                  const style = window.getComputedStyle(element);
                  return style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0';
                })
                .map(element => element.textContent)
                .filter(text => text && text.trim().length > 0)
                .join('\\n')
            `) as string;
            break;
          case "html":
            // Get HTML content
            extractedContent = await page.content();
            break;
          case "screenshot":
            // Take a screenshot
            screenshotPath = path.join(TEMP_DIR, `screenshot-${pageId}-${Date.now()}.png`);
            await page.screenshot({ path: screenshotPath });
            extractedContent = `Screenshot saved to: ${screenshotPath}`;
            break;
        }
        
        return {
          content: [
            {
              type: "text",
              text: type === "text" || type === "screenshot" 
                ? extractedContent.substring(0, 2000) + (extractedContent.length > 2000 ? '...' : '')
                : `Extracted HTML content (${extractedContent.length} characters). First 100 characters:\n${extractedContent.substring(0, 100)}...`
            }
          ]
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Failed to extract content: ${error}`
            }
          ]
        };
      }
    }
  • Input schema for the 'extract' tool defined using Zod, specifying browserId, pageId, and type parameters.
      browserId: z.string().describe("Browser ID from a previous browse operation"),
      pageId: z.string().describe("Page ID from a previous browse operation"),
      type: z.enum(["text", "html", "screenshot"]).describe("Type of content to extract")
    },
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 lacks behavioral details. It doesn't disclose whether extraction is read-only (implied but not stated), if it requires specific permissions, rate limits, or what happens on failure (e.g., invalid IDs). The description only states what it does, not how it behaves.

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 with zero wasted words. It front-loads the core action ('extract information') and specifies key details (source: current page; formats: text, html, screenshot). Every element earns its place.

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 tool with 3 required parameters, no annotations, and no output schema, the description is incomplete. It doesn't explain the relationship to 'browse' (source of browserId/pageId), what 'extract' returns (e.g., raw text, file path), or error handling. The agent lacks context for effective use.

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 parameters are well-documented in the schema. The description adds minimal value by mentioning the 'type' enum options (text, html, screenshot), but doesn't explain semantics beyond what the schema already provides (e.g., what 'text' extraction includes vs. 'html'). Baseline 3 is appropriate.

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 clearly states the verb 'extract' and the resource 'information from the current page', specifying the output formats (text, html, or screenshot). It distinguishes from sibling tools like 'browse' (which likely navigates) and 'interact' (which likely performs actions), but doesn't explicitly differentiate from 'close' (which likely terminates a session).

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. It doesn't mention prerequisites (e.g., needing a browser/page ID from 'browse'), exclusions, or contextual cues for choosing between extraction types. The agent must infer usage from parameter names alone.

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/dylangroos/patchright-mcp-lite'

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