Skip to main content
Glama

spa_read

Extract content from JavaScript-heavy Single Page Applications by rendering pages with a headless browser and converting them to LLM-ready Markdown.

Instructions

Render a JavaScript SPA page and extract its content as LLM-ready Markdown. Uses a headless browser to execute JavaScript, then extracts the main article content.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
urlYesThe URL of the SPA page to read
waitForSelectorNoCSS selector to wait for before extraction
waitTimeoutNoNavigation timeout in ms (default: 30000)
includeMetadataNoInclude title/author/excerpt as YAML frontmatter (default: true)
cookiesNoCookies to inject before page load (e.g., session tokens)
headersNoCustom HTTP headers (e.g., Authorization)

Implementation Reference

  • The main handler function that executes the spa_read tool logic. It takes URL and options, renders the page using a headless browser, extracts article content, and returns LLM-ready Markdown. Includes error handling and metadata formatting.
    async ({ url, waitForSelector, waitTimeout, includeMetadata, cookies, headers }) => {
      try {
        const renderResult = await renderPage({ url, waitForSelector, waitTimeout, cookies, headers });
        const extraction = extractArticle(renderResult.html, renderResult.url);
    
        if (extraction.markdown.length === 0) {
          return {
            content: [
              {
                type: "text" as const,
                text: `Error: Page rendered but no content found at ${url}`,
              },
            ],
            isError: true,
          };
        }
    
        const markdown = formatAsLlmMarkdown(
          extraction,
          renderResult.url,
          includeMetadata ?? true,
        );
    
        return {
          content: [{ type: "text" as const, text: markdown }],
        };
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
          content: [
            {
              type: "text" as const,
              text: `Error reading ${url}: ${message}`,
            },
          ],
          isError: true,
        };
      }
    },
  • Input validation schemas using Zod: cookieSchema (lines 10-19) defines cookie structure, and the tool input schema (lines 26-50) validates URL, waitForSelector, waitTimeout, includeMetadata, cookies, and headers parameters.
    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 registerSpaReadTool(server: McpServer): void {
      server.tool(
        "spa_read",
        "Render a JavaScript SPA page and extract its content as LLM-ready Markdown. " +
          "Uses a headless browser to execute JavaScript, then extracts the main article content.",
        {
          url: z.string().url().describe("The URL of the SPA page to read"),
          waitForSelector: z
            .string()
            .optional()
            .describe("CSS selector to wait for before extraction"),
          waitTimeout: z
            .number()
            .min(1000)
            .max(120000)
            .optional()
            .describe("Navigation timeout in ms (default: 30000)"),
          includeMetadata: z
            .boolean()
            .optional()
            .describe("Include title/author/excerpt as YAML frontmatter (default: true)"),
          cookies: z
            .array(cookieSchema)
            .optional()
            .describe("Cookies to inject before page load (e.g., session tokens)"),
          headers: z
            .record(z.string(), z.string())
            .optional()
            .describe("Custom HTTP headers (e.g., Authorization)"),
        },
  • Registration of the spa_read tool with the MCP server. Calls server.tool() with tool name 'spa_read', description, input schema, and handler function.
    export function registerSpaReadTool(server: McpServer): void {
      server.tool(
        "spa_read",
        "Render a JavaScript SPA page and extract its content as LLM-ready Markdown. " +
          "Uses a headless browser to execute JavaScript, then extracts the main article content.",
        {
          url: z.string().url().describe("The URL of the SPA page to read"),
          waitForSelector: z
            .string()
            .optional()
            .describe("CSS selector to wait for before extraction"),
          waitTimeout: z
            .number()
            .min(1000)
            .max(120000)
            .optional()
            .describe("Navigation timeout in ms (default: 30000)"),
          includeMetadata: z
            .boolean()
            .optional()
            .describe("Include title/author/excerpt as YAML frontmatter (default: true)"),
          cookies: z
            .array(cookieSchema)
            .optional()
            .describe("Cookies to inject before page load (e.g., session tokens)"),
          headers: z
            .record(z.string(), z.string())
            .optional()
            .describe("Custom HTTP headers (e.g., Authorization)"),
        },
        async ({ url, waitForSelector, waitTimeout, includeMetadata, cookies, headers }) => {
          try {
            const renderResult = await renderPage({ url, waitForSelector, waitTimeout, cookies, headers });
            const extraction = extractArticle(renderResult.html, renderResult.url);
    
            if (extraction.markdown.length === 0) {
              return {
                content: [
                  {
                    type: "text" as const,
                    text: `Error: Page rendered but no content found at ${url}`,
                  },
                ],
                isError: true,
              };
            }
    
            const markdown = formatAsLlmMarkdown(
              extraction,
              renderResult.url,
              includeMetadata ?? true,
            );
    
            return {
              content: [{ type: "text" as const, text: markdown }],
            };
          } catch (error) {
            const message = error instanceof Error ? error.message : String(error);
            return {
              content: [
                {
                  type: "text" as const,
                  text: `Error reading ${url}: ${message}`,
                },
              ],
              isError: true,
            };
          }
        },
      );
    }
  • src/index.ts:8-18 (registration)
    Import and registration of the spa_read tool in the main server initialization. Imports registerSpaReadTool and calls it with the server instance.
    import { registerSpaReadTool } from "./tools/spa-read.js";
    import { registerSpaScreenshotTool } from "./tools/spa-screenshot.js";
    import { closeBrowser } from "./lib/renderer.js";
    
    const server = new McpServer({
      name: "spa-reader",
      version: "1.0.0",
    });
    
    registerSpaReadTool(server);
    registerSpaScreenshotTool(server);
  • Core helper function renderPage() that launches a headless Chromium browser, navigates to the URL, waits for network idle and optional selector, and returns HTML content. Includes URL validation, cookie injection, and header customization.
    export async function renderPage(options: RenderOptions): Promise<RenderResult> {
      const { parsedUrl, timeout, resolvedCookies, cleanedHeaders } = validateOptions(options);
    
      const browser = await getBrowser();
      const context: BrowserContext = await browser.newContext({
        userAgent: "spa-reader-mcp/1.0.0",
        extraHTTPHeaders: Object.keys(cleanedHeaders).length > 0 ? cleanedHeaders : undefined,
      });
    
      try {
        if (resolvedCookies.length > 0) {
          await context.addCookies(resolvedCookies);
        }
    
        const page = await context.newPage();
        await navigateAndWait(page, options, parsedUrl, timeout);
    
        const html = await page.content();
        const url = page.url();
        const title = await page.title();
    
        return { html, url, title };
      } finally {
        await context.close();
      }
    }
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 using a headless browser and extracting main article content, but lacks critical details such as whether this is a read-only operation, potential performance impacts (e.g., timeouts, resource usage), error handling, or authentication requirements (though headers/cookies parameters hint at this). The description is insufficient for a tool with complex behavior involving browser automation.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is front-loaded with the core purpose in the first sentence and adds implementation detail in the second. Both sentences are relevant and non-redundant, though it could be slightly more structured (e.g., explicitly separating purpose from method). No wasted words, making it efficient for an agent to parse.

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 tool's complexity (headless browser execution, 6 parameters, no output schema, and no annotations), the description is incomplete. It lacks information on return values (e.g., format of extracted Markdown, error responses), behavioral constraints (e.g., rate limits, side effects), and does not compensate for the absence of annotations. This leaves significant gaps for an agent to use the tool 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 additional parameter semantics beyond what the schema provides, such as explaining how 'waitForSelector' relates to content extraction or typical use cases for cookies/headers. The baseline score of 3 reflects adequate but minimal value added over the schema.

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 ('Render a JavaScript SPA page and extract its content as LLM-ready Markdown') and distinguishes it from the sibling tool spa_screenshot by focusing on content extraction rather than visual capture. It specifies the method ('Uses a headless browser to execute JavaScript') and the target resource ('SPA page').

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 SPA pages with JavaScript-rendered content, but does not explicitly state when to use this tool versus alternatives like spa_screenshot or other non-SPA reading tools. No exclusions or prerequisites are mentioned, leaving the agent to infer the context from the tool name and description 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/XXO47OXX/spa-reader-mcp'

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