Skip to main content
Glama

Fetch Document Text

fetch_document_text

Extract full text from Australian legislation and case law documents using OCR for scanned PDFs. Supports multiple output formats including JSON, text, markdown, and HTML.

Instructions

Fetch full text for a legislation or case URL, with OCR fallback for scanned PDFs.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
formatNojson
urlYes

Implementation Reference

  • Core handler function that fetches document from URL, detects content type, extracts text (PDF with OCR fallback, HTML parsing), and returns FetchResponse.
    export async function fetchDocumentText(url: string): Promise<FetchResponse> {
      try {
        const response = await axios.get(url, {
          responseType: "arraybuffer",
          headers: {
            "User-Agent": "auslaw-mcp/0.1.0 (legal research tool)",
          },
          timeout: 30000,
          maxContentLength: 50 * 1024 * 1024, // 50MB limit
        });
    
        const buffer = Buffer.from(response.data);
        const contentType = response.headers["content-type"] || "";
    
        // Detect file type from buffer
        const detectedType = await fileTypeFromBuffer(buffer);
    
        let text: string;
        let ocrUsed = false;
    
        // Handle PDF documents
        if (
          contentType.includes("application/pdf") ||
          detectedType?.mime === "application/pdf"
        ) {
          const result = await extractTextFromPdf(buffer, url);
          text = result.text;
          ocrUsed = result.ocrUsed;
        }
        // Handle HTML documents
        else if (
          contentType.includes("text/html") ||
          detectedType?.mime === "text/html"
        ) {
          const html = buffer.toString("utf-8");
          text = extractTextFromHtml(html, url);
        }
        // Handle plain text
        else if (contentType.includes("text/plain")) {
          text = buffer.toString("utf-8");
        }
        // Unsupported format
        else {
          throw new Error(
            `Unsupported content type: ${contentType}${detectedType ? ` (detected: ${detectedType.mime})` : ""}`,
          );
        }
    
        // Extract basic metadata
        const metadata: Record<string, string> = {
          contentLength: String(buffer.length),
          contentType: contentType || detectedType?.mime || "unknown",
        };
    
        return {
          text,
          contentType: contentType || detectedType?.mime || "unknown",
          sourceUrl: url,
          ocrUsed,
          metadata,
        };
      } catch (error) {
        if (axios.isAxiosError(error)) {
          throw new Error(
            `Failed to fetch document from ${url}: ${error.message}`,
          );
        }
        throw error;
      }
    }
  • src/index.ts:90-103 (registration)
    Registers the 'fetch_document_text' tool with MCP server, providing input schema and a handler that parses input, calls fetchDocumentText, and formats output.
    server.registerTool(
      "fetch_document_text",
      {
        title: "Fetch Document Text",
        description:
          "Fetch full text for a legislation or case URL, with OCR fallback for scanned PDFs.",
        inputSchema: fetchDocumentShape,
      },
      async (rawInput) => {
        const { url, format } = fetchDocumentParser.parse(rawInput);
        const response = await fetchDocumentText(url);
        return formatFetchResponse(response, format ?? "json");
      },
    );
  • Defines the input schema for fetch_document_text tool using Zod: required URL and optional format (json/text/markdown/html).
    const fetchDocumentShape = {
      url: z.string().url("URL must be valid."),
      format: formatEnum.optional(),
    };
    const fetchDocumentParser = z.object(fetchDocumentShape);
  • TypeScript interface defining the structure of the output returned by fetchDocumentText.
    export interface FetchResponse {
      text: string;
      contentType: string;
      sourceUrl: string;
      ocrUsed: boolean;
      metadata?: Record<string, string>;
    }
  • Helper function to extract text from PDF buffers, first trying direct extraction, falling back to OCR if insufficient text.
    async function extractTextFromPdf(
      buffer: Buffer,
      url: string,
    ): Promise<{ text: string; ocrUsed: boolean }> {
      try {
        // First try to extract text from PDF directly
        const pdfData = await pdf(buffer);
        const extractedText = pdfData.text.trim();
    
        // If we got substantial text, return it
        if (extractedText.length > 100) {
          return { text: extractedText, ocrUsed: false };
        }
    
        // Otherwise, fall back to OCR
        console.warn(`PDF at ${url} has minimal text, attempting OCR...`);
        return await performOcr(buffer);
      } catch (error) {
        console.warn(`PDF parsing failed for ${url}, attempting OCR:`, error);
        return await performOcr(buffer);
      }
    }
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 'OCR fallback for scanned PDFs', which adds some context about handling different document types, but it lacks details on permissions, rate limits, error handling, or response format. This leaves significant gaps in understanding the tool's behavior beyond basic functionality.

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 that front-loads the core purpose ('Fetch full text for a legislation or case URL') and adds a key behavioral detail ('with OCR fallback for scanned PDFs') without any waste. It is appropriately sized and structured for quick comprehension.

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 (handling URLs with OCR fallback) and lack of annotations and output schema, the description is incomplete. It does not cover return values, error cases, or detailed behavioral traits, making it inadequate for an AI agent to fully understand how to invoke and interpret results from this tool.

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?

The schema description coverage is 0%, so the description must compensate. It implies the 'url' parameter is for legislation or case URLs and hints at format handling with OCR, but it does not explain the 'format' parameter's options or semantics. The description adds minimal meaning beyond the schema, resulting in a baseline score due to incomplete 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 ('Fetch full text') and resource ('for a legislation or case URL'), distinguishing it from sibling tools like 'search_cases' and 'search_legislation' by focusing on text extraction rather than searching. It also specifies the scope ('with OCR fallback for scanned PDFs'), making the purpose highly specific and well-defined.

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 when text extraction from legislation or case URLs is needed, but it does not explicitly state when to use this tool versus alternatives like the sibling search tools. There is no guidance on prerequisites, exclusions, or specific scenarios, leaving the context somewhat vague for an AI agent.

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/russellbrenner/auslaw-mcp'

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