Skip to main content
Glama

fetch-content

Extract content from URLs for Web3 research by converting web pages into text, HTML, markdown, or JSON formats.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
urlYesURL to fetch content from (can be a resource:// URL)
formatNoOutput formatmarkdown

Implementation Reference

  • Executes the 'fetch-content' tool logic: determines if URL is local resource or web, fetches content using appropriate helper, stores full content as a resource in storage, returns a text preview (truncated if long).
      url,
      format,
    }: {
      url: string;
      format: "text" | "html" | "markdown" | "json";
    }) => {
      storage.addLogEntry(`Fetching content from: ${url} (format: ${format})`);
    
      try {
        let content;
    
        if (url.startsWith("research://resource/")) {
          content = await getResourceContent(url, storage);
        } else {
          content = await fetchContent(url, format);
        }
    
        const resourceId = url.startsWith("research://resource/")
          ? `derived_${url.replace(
              "research://resource/",
              ""
            )}_${new Date().getTime()}`
          : url
              .replace(/https?:\/\//, "")
              .replace(/[^\w]/g, "_")
              .substring(0, 30);
    
        storage.addToSection("resources", {
          [resourceId]: {
            url,
            format,
            content,
            fetchedAt: new Date().toISOString(),
          },
        });
    
        return {
          content: [
            {
              type: "text",
              text: `Fetched content from ${url} (${format}):\n\n${content.substring(
                0,
                1000
              )}${
                content.length > 1000
                  ? "...\n\n[Content truncated, full version saved as resource]"
                  : ""
              }`,
            },
          ],
        };
      } catch (error) {
        storage.addLogEntry(`Error fetching content from ${url}: ${error}`);
        return {
          isError: true,
          content: [
            {
              type: "text",
              text: `Error fetching content: ${error}`,
            },
          ],
        };
      }
    }
  • Input schema using Zod for the 'fetch-content' tool: url (string, supports research://), format (enum with default 'markdown').
    {
      url: z
        .string()
        .describe("URL to fetch content from (can be a resource:// URL)"),
      format: z
        .enum(["text", "html", "markdown", "json"])
        .default("markdown")
        .describe("Output format"),
    },
  • Registers the 'fetch-content' tool on the MCP server within registerResearchTools function.
    server.tool(
      "fetch-content",
      {
        url: z
          .string()
          .describe("URL to fetch content from (can be a resource:// URL)"),
        format: z
          .enum(["text", "html", "markdown", "json"])
          .default("markdown")
          .describe("Output format"),
      },
      async ({
        url,
        format,
      }: {
        url: string;
        format: "text" | "html" | "markdown" | "json";
      }) => {
        storage.addLogEntry(`Fetching content from: ${url} (format: ${format})`);
    
        try {
          let content;
    
          if (url.startsWith("research://resource/")) {
            content = await getResourceContent(url, storage);
          } else {
            content = await fetchContent(url, format);
          }
    
          const resourceId = url.startsWith("research://resource/")
            ? `derived_${url.replace(
                "research://resource/",
                ""
              )}_${new Date().getTime()}`
            : url
                .replace(/https?:\/\//, "")
                .replace(/[^\w]/g, "_")
                .substring(0, 30);
    
          storage.addToSection("resources", {
            [resourceId]: {
              url,
              format,
              content,
              fetchedAt: new Date().toISOString(),
            },
          });
    
          return {
            content: [
              {
                type: "text",
                text: `Fetched content from ${url} (${format}):\n\n${content.substring(
                  0,
                  1000
                )}${
                  content.length > 1000
                    ? "...\n\n[Content truncated, full version saved as resource]"
                    : ""
                }`,
              },
            ],
          };
        } catch (error) {
          storage.addLogEntry(`Error fetching content from ${url}: ${error}`);
          return {
            isError: true,
            content: [
              {
                type: "text",
                text: `Error fetching content: ${error}`,
              },
            ],
          };
        }
      }
    );
  • Supporting utility that performs the actual HTTP fetch of web content, handles JSON/HTML, parses to requested format using cheerio (removes scripts/styles), with retry logic and realistic headers.
    export async function fetchContent(
      url: string,
      format: "text" | "html" | "markdown" | "json" = "text",
      retries = 2
    ): Promise<string> {
      if (url.startsWith("research://")) {
        throw new Error("Only HTTP(S) protocols are supported");
      }
    
      for (let i = 0; i <= retries; i++) {
        try {
          await sleep(1000 + Math.random() * 2000);
    
          const response = await fetch(url, {
            headers: {
              "User-Agent":
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
              Accept:
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
              "Accept-Language": "en-US,en;q=0.9",
              Connection: "keep-alive",
              "Upgrade-Insecure-Requests": "1",
              Referer: "https://www.google.com/",
              "Cache-Control": "max-age=0",
              "sec-ch-ua":
                '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
              "sec-ch-ua-mobile": "?0",
              "sec-ch-ua-platform": '"Windows"',
              "Sec-Fetch-Dest": "document",
              "Sec-Fetch-Mode": "navigate",
              "Sec-Fetch-Site": "none",
              "Sec-Fetch-User": "?1",
            },
            redirect: "follow",
          });
    
          if (!response.ok) {
            throw new Error(
              `HTTP error ${response.status}: ${response.statusText}`
            );
          }
    
          const contentType = response.headers.get("content-type") || "";
    
          if (contentType.includes("application/json")) {
            const json = await response.json();
            return format === "json"
              ? JSON.stringify(json, null, 2)
              : JSON.stringify(json);
          } else {
            const html = await response.text();
    
            switch (format) {
              case "html":
                return html;
              case "markdown":
                const $ = cheerio.load(html);
                $("script, style, meta, link, noscript, iframe").remove();
                const title = $("title").text();
                const body = $("body").text().replace(/\s+/g, " ").trim();
                return `# ${title}\n\n${body}`;
              case "text":
              default:
                const $text = cheerio.load(html);
                $text("script, style, meta, link").remove();
                return $text("body").text().replace(/\s+/g, " ").trim();
            }
          }
        } catch (error) {
          if (i < retries) {
            const delay = 3000 * Math.pow(2, i);
            await sleep(delay);
          } else {
            throw error;
          }
        }
      }
    
      throw new Error(`Failed to fetch ${url} after ${retries} retries`);
    }
  • Helper function to retrieve content from locally stored research resources via research://resource/ URLs.
    export async function getResourceContent(
      url: string,
      storage: ResearchStorage
    ): Promise<string> {
      if (url.startsWith("research://resource/")) {
        const resourceId = url.replace("research://resource/", "");
        const resource = storage.getResource(resourceId);
    
        if (!resource) {
          throw new Error(`Resource not found: ${resourceId}`);
        }
    
        return resource.content;
      }
    
      return fetchContent(url, "markdown");
    }
Behavior1/5

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

Tool has no description.

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

Conciseness1/5

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

Tool has no description.

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

Completeness1/5

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

Tool has no description.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Tool has no description.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose1/5

Does the description clearly state what the tool does and how it differs from similar tools?

Tool has no description.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines1/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Tool has no description.

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/aaronjmars/web3-research-mcp'

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