Skip to main content
Glama
nathanonn
by nathanonn

fetch-html

Extract HTML content from any URL or convert web pages to text-only format for streamlined processing and analysis with the MCP URL Fetcher server.

Instructions

Fetch content from any URL and convert to HTML format

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
extractTextNoWhether to extract text content only (default: false)
urlYesURL to fetch content from

Implementation Reference

  • src/index.ts:201-240 (registration)
    Registration of the "fetch-html" MCP tool, specifying name, description, input schema with Zod, and the handler function.
    server.tool(
      "fetch-html",
      "Fetch content from any URL and convert to HTML format",
      {
        url: z.string().url().describe("URL to fetch content from"),
        extractText: z.boolean().optional().describe("Whether to extract text content only (default: false)"),
      },
      async ({ url, extractText = false }) => {
        try {
          const response = await fetchUrl(url);
          const contentText = await response.text();
          const detectedType = detectContentType(response, url);
    
          let htmlContent;
          if (extractText) {
            const plainText = await convertToText(contentText, detectedType, url);
            htmlContent = `<pre>${escapeHtml(plainText)}</pre>`;
          } else {
            htmlContent = await convertToHtml(contentText, detectedType, url);
          }
    
          // Record this fetch
          recordUrlFetch(url, "html");
    
          return {
            content: [{ type: "text", text: htmlContent }],
          };
        } catch (error) {
          return {
            isError: true,
            content: [
              {
                type: "text",
                text: `Error converting to HTML: ${error instanceof Error ? error.message : String(error)}`,
              },
            ],
          };
        }
      }
    );
  • Input schema definition for the "fetch-html" tool using Zod validators for URL and optional extractText flag.
    {
      url: z.string().url().describe("URL to fetch content from"),
      extractText: z.boolean().optional().describe("Whether to extract text content only (default: false)"),
    },
  • Handler function that executes the "fetch-html" tool: fetches URL, detects content type, conditionally extracts text or converts to HTML using helpers, records the fetch, and returns formatted content or error.
    async ({ url, extractText = false }) => {
      try {
        const response = await fetchUrl(url);
        const contentText = await response.text();
        const detectedType = detectContentType(response, url);
    
        let htmlContent;
        if (extractText) {
          const plainText = await convertToText(contentText, detectedType, url);
          htmlContent = `<pre>${escapeHtml(plainText)}</pre>`;
        } else {
          htmlContent = await convertToHtml(contentText, detectedType, url);
        }
    
        // Record this fetch
        recordUrlFetch(url, "html");
    
        return {
          content: [{ type: "text", text: htmlContent }],
        };
      } catch (error) {
        return {
          isError: true,
          content: [
            {
              type: "text",
              text: `Error converting to HTML: ${error instanceof Error ? error.message : String(error)}`,
            },
          ],
        };
      }
    }
  • Core helper function convertToHtml that performs format-specific conversions to HTML, used by the fetch-html handler for non-extractText mode.
    async function convertToHtml(content: string, sourceType: string, sourceUrl: string): Promise<string> {
      try {
        switch (sourceType) {
          case "html":
            // Already HTML, just sanitize it
            return sanitizeHtml(content, {
              allowedTags: sanitizeHtml.defaults.allowedTags.concat(["img", "h1", "h2", "h3", "h4", "h5", "h6"]),
              allowedAttributes: {
                ...sanitizeHtml.defaults.allowedAttributes,
                img: ["src", "alt", "title", "width", "height"],
                a: ["href", "name", "target"],
              },
            });
    
          case "json":
            try {
              // Format JSON as HTML
              const jsonObj = JSON.parse(content);
              return `<!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>JSON Viewer</title>
      <style>
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; line-height: 1.6; padding: 20px; }
        pre { background-color: #f5f5f5; padding: 15px; border-radius: 5px; overflow-x: auto; }
        .json-key { color: #0033b3; }
        .json-string { color: #388E3C; }
        .json-number { color: #1976D2; }
        .json-boolean { color: #7E57C2; }
        .json-null { color: #5D4037; }
      </style>
    </head>
    <body>
      <h1>JSON Content</h1>
      <pre>${formatJsonForHtml(JSON.stringify(jsonObj, null, 2))}</pre>
      <footer>
        <p>Source: ${escapeHtml(sourceUrl)}</p>
        <p>Converted at: ${new Date().toLocaleString()}</p>
      </footer>
    </body>
    </html>`;
            } catch (e) {
              return `<pre>${escapeHtml(content)}</pre>`;
            }
    
          case "markdown":
            // Convert markdown to HTML
            const htmlContent = marked.parse(content);
    
            return `<!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Markdown Content</title>
      <style>
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; line-height: 1.6; padding: 20px; max-width: 800px; margin: 0 auto; }
        img { max-width: 100%; height: auto; }
        pre { background-color: #f5f5f5; padding: 15px; border-radius: 5px; overflow-x: auto; }
        code { background-color: #f5f5f5; padding: 2px 4px; border-radius: 3px; }
        blockquote { border-left: 4px solid #ddd; padding-left: 15px; color: #666; }
        table { border-collapse: collapse; width: 100%; }
        table, th, td { border: 1px solid #ddd; }
        th, td { padding: 8px; text-align: left; }
        th { background-color: #f5f5f5; }
      </style>
    </head>
    <body>
      ${htmlContent}
      <footer>
        <p>Source: ${escapeHtml(sourceUrl)}</p>
        <p>Converted at: ${new Date().toLocaleString()}</p>
      </footer>
    </body>
    </html>`;
    
          case "csv":
            // Convert CSV to HTML table
            const jsonData = await csvtojson().fromString(content);
            if (jsonData.length === 0) {
              throw new Error("CSV data appears to be empty or invalid");
            }
    
            // Get headers from the first row
            const headers = Object.keys(jsonData[0]);
    
            // Generate HTML table
            let tableHtml = '<table border="1"><thead><tr>';
    
            // Add header row
            headers.forEach((header) => {
              tableHtml += `<th>${escapeHtml(header)}</th>`;
            });
            tableHtml += "</tr></thead><tbody>";
    
            // Add data rows
            jsonData.forEach((row) => {
              tableHtml += "<tr>";
              headers.forEach((header) => {
                tableHtml += `<td>${escapeHtml(String(row[header]))}</td>`;
              });
              tableHtml += "</tr>";
            });
    
            tableHtml += "</tbody></table>";
    
            return `<!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>CSV Data</title>
      <style>
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; padding: 20px; }
        table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }
        th, td { padding: 8px; text-align: left; border: 1px solid #ddd; }
        th { background-color: #f5f5f5; position: sticky; top: 0; }
        tr:nth-child(even) { background-color: #f9f9f9; }
        .container { max-height: 600px; overflow-y: auto; margin-top: 20px; }
      </style>
    </head>
    <body>
      <h1>CSV Data</h1>
      <div class="container">
        ${tableHtml}
      </div>
      <footer>
        <p>Source: ${escapeHtml(sourceUrl)}</p>
        <p>Converted at: ${new Date().toLocaleString()}</p>
        <p>Total rows: ${jsonData.length}</p>
      </footer>
    </body>
    </html>`;
    
          case "xml":
            try {
              // Parse XML to JSON then generate an HTML representation
              const jsonObj = xmlParser.parse(content);
    
              return `<!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>XML Content</title>
      <style>
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; line-height: 1.6; padding: 20px; }
        pre { background-color: #f5f5f5; padding: 15px; border-radius: 5px; overflow-x: auto; }
        .xml-tag { color: #0033b3; }
        .xml-attr { color: #7E57C2; }
        .xml-content { color: #388E3C; }
      </style>
    </head>
    <body>
      <h1>XML Content</h1>
      <h2>Original XML</h2>
      <pre>${escapeHtml(content)}</pre>
      <h2>As JSON</h2>
      <pre>${formatJsonForHtml(JSON.stringify(jsonObj, null, 2))}</pre>
      <footer>
        <p>Source: ${escapeHtml(sourceUrl)}</p>
        <p>Converted at: ${new Date().toLocaleString()}</p>
      </footer>
    </body>
    </html>`;
            } catch (xmlError) {
              return `<pre>${escapeHtml(content)}</pre>`;
            }
    
          default:
            // Wrap plain text in HTML
            return `<!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Text Content</title>
      <style>
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; line-height: 1.6; padding: 20px; }
        pre { background-color: #f5f5f5; padding: 15px; border-radius: 5px; overflow-x: auto; white-space: pre-wrap; }
      </style>
    </head>
    <body>
      <h1>Text Content</h1>
      <pre>${escapeHtml(content)}</pre>
      <footer>
        <p>Source: ${escapeHtml(sourceUrl)}</p>
        <p>Converted at: ${new Date().toLocaleString()}</p>
      </footer>
    </body>
    </html>`;
        }
      } catch (error) {
        throw new Error(`HTML conversion error: ${error instanceof Error ? error.message : String(error)}`);
      }
    }
  • Reusable fetchUrl helper function to retrieve content from a URL, handling errors and used by multiple fetch tools including fetch-html.
    async function fetchUrl(url: string) {
      try {
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response;
      } catch (error) {
        console.error(`Error fetching URL: ${url}`, error);
        throw error;
      }
    }
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. While it mentions fetching and converting to HTML, it doesn't address important behavioral aspects like error handling (e.g., what happens with invalid URLs), authentication requirements, rate limits, timeout behavior, or whether the tool performs any sanitization of the fetched HTML.

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 communicates the core functionality without any wasted words. It's appropriately sized for a simple tool and front-loads the essential information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a relatively simple tool with good schema coverage but no annotations and no output schema, the description provides the basic purpose but lacks important contextual information. It doesn't explain what the HTML output looks like, whether it includes metadata, or how it handles different content types. The absence of output schema means the description should ideally provide some information about return values.

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 input schema has 100% description coverage, with both parameters clearly documented. The description adds no additional parameter information beyond what's in the schema. According to scoring rules, when schema_description_coverage is high (>80%), the baseline is 3 even with no param info 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 clearly states the verb ('fetch') and resource ('content from any URL') with the specific output format ('HTML format'), making the purpose immediately understandable. However, it doesn't explicitly differentiate from sibling tools like fetch-json or fetch-markdown, which presumably fetch the same content but convert to different formats.

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 its siblings (fetch, fetch-json, fetch-markdown, fetch-text). It mentions converting to HTML format, but doesn't explain when HTML format is preferable over other formats or what distinguishes it from the generic 'fetch' tool.

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

Related 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/nathanonn/mcp-url-fetcher'

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