Skip to main content
Glama

fetch-url

Fetch web content from URLs using HTTP methods like GET, POST, PUT, and DELETE. Configure requests with headers, body, timeout, and response formats including text, JSON, and binary.

Instructions

Fetch content from a URL

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
urlYesURL to fetch
methodNoHTTP methodGET
headersNoHTTP headers
bodyNoRequest body for POST/PUT/PATCH requests
timeoutNoRequest timeout in milliseconds
responseTypeNoHow to parse the responsetext
followRedirectsNoWhether to follow redirects

Implementation Reference

  • Main execution logic for the 'fetch-url' tool: validates input, performs HTTP fetch with undici, processes response based on type (text/json/binary/html-fragment), includes metadata, handles errors.
    async function handleFetchUrl(args: FetchUrlArgs): Promise<z.infer<typeof CallToolResultSchema>> {
      try {
        const { url, method, headers, body, timeout, responseType, followRedirects } = args;
        
        // Log the fetch request
        console.error(`Fetching ${url} with method ${method}`);
        
        // Create request options
        const options: any = {
          method,
          headers: headers || {},
          body: body || undefined,
          redirect: followRedirects ? "follow" : "manual",
        };
        
        if (timeout) {
          // @ts-ignore - undici specific options
          options.bodyTimeout = timeout;
          // @ts-ignore - undici specific options
          options.headersTimeout = timeout;
        }
        
        // Perform the request
        const response = await fetch(url, options);
        
        // Create a result object with metadata
        const result: Record<string, any> = {
          status: response.status,
          statusText: response.statusText,
          headers: Object.fromEntries(response.headers.entries()),
          url: response.url,
        };
        
        // Process the response based on the requested type
        switch (responseType) {
          case "json":
            try {
              const jsonContent = await response.json();
              result.content = JSON.stringify(jsonContent, null, 2);
            } catch (e) {
              throw new Error(`Failed to parse response as JSON: ${(e as Error).message}`);
            }
            break;
          
          case "binary":
            const buffer = await response.arrayBuffer();
            result.content = Buffer.from(buffer).toString("base64");
            result.encoding = "base64";
            break;
          
          case "html-fragment":
            try {
              const htmlContent = await response.text();
              // Use JSDOM to parse the HTML
              const dom = new JSDOM(htmlContent);
              const document = dom.window.document;
              
              // Only look for fragments if a selector is provided
              if (args.fragmentSelector) {
                const elements = document.querySelectorAll(args.fragmentSelector);
                if (elements.length === 0) {
                  throw new Error(`No elements found matching selector "${args.fragmentSelector}"`);
                }
                
                // Extract the HTML from the selected element(s)
                if (elements.length === 1) {
                  result.content = elements[0].outerHTML;
                } else {
                  result.content = Array.from(elements).map(el => el.outerHTML).join('\n');
                }
                result.matchCount = elements.length;
              } else {
                // No selector provided, return the full HTML
                result.content = htmlContent;
              }
              result.contentType = 'text/html';
            } catch (e) {
              throw new Error(`Failed to parse or extract HTML fragment: ${(e as Error).message}`);
            }
            break;
            
          case "text":
          default:
            result.content = await response.text();
            break;
        }
        
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(result, null, 2)
            }
          ]
        };
      } catch (error) {
        console.error(`Error fetching URL:`, error);
        return {
          isError: true,
          content: [
            {
              type: "text",
              text: `Error fetching URL: ${(error as Error).message}`
            }
          ]
        };
      }
    }
  • Zod input validation schema for the fetch-url tool arguments.
    const FetchUrlArgsSchema = z.object({
      url: z.string().url().describe("URL to fetch"),
      method: z.enum(["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "PATCH"]).default("GET").describe("HTTP method"),
      headers: z.record(z.string()).optional().describe("HTTP headers"),
      body: z.string().optional().describe("Request body for POST/PUT/PATCH requests"),
      timeout: z.number().positive().optional().describe("Request timeout in milliseconds"),
      responseType: z.enum(["text", "json", "binary", "html-fragment"]).default("text").describe("How to parse the response"),
      followRedirects: z.boolean().default(true).describe("Whether to follow redirects"),
      fragmentSelector: z.string().optional().describe("CSS selector for the HTML fragment to extract (when responseType is html-fragment)")
    });
  • src/index.ts:85-119 (registration)
    MCP tool registration object defining name, description, and input schema for 'fetch-url', added to TOOLS array used in ListTools handler.
    {
      name: "fetch-url",
      description: "Fetch content from a URL",
      inputSchema: {
        type: "object",
        properties: {
          url: { type: "string", description: "URL to fetch" },
          method: { 
            type: "string", 
            enum: ["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "PATCH"], 
            default: "GET", 
            description: "HTTP method" 
          },
          headers: { 
            type: "object", 
            additionalProperties: { type: "string" }, 
            description: "HTTP headers" 
          },
          body: { type: "string", description: "Request body for POST/PUT/PATCH requests" },
          timeout: { type: "number", description: "Request timeout in milliseconds" },
          responseType: { 
            type: "string", 
            enum: ["text", "json", "binary", "html-fragment"], 
            default: "text", 
            description: "How to parse the response" 
          },
          followRedirects: { 
            type: "boolean", 
            default: true, 
            description: "Whether to follow redirects" 
          }
        },
        required: ["url"]
      }
    },
  • src/index.ts:159-160 (registration)
    Dispatch case in the CallToolRequestSchema handler that invokes the fetch-url handler after argument validation.
    case "fetch-url":
      return handleFetchUrl(FetchUrlArgsSchema.parse(args));
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. 'Fetch content from a URL' implies a read operation, but it lacks details on error handling (e.g., timeouts, network failures), authentication needs, rate limits, or what 'content' entails (e.g., raw response, parsed data). For a tool with 7 parameters and no annotations, this is a significant gap in transparency.

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 without unnecessary words. It avoids redundancy and wastes no space, making it easy for an AI agent to parse quickly. Every word earns its place by directly conveying the tool's function.

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 (7 parameters, no annotations, no output schema), the description is incomplete. It doesn't address behavioral aspects like error handling or response format, and with no output schema, it fails to explain what 'content' means in the return value. For a general-purpose HTTP client tool, more context is needed to guide effective usage.

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%, meaning all parameters are documented in the schema itself. The description adds no additional meaning beyond the schema, such as explaining parameter interactions (e.g., 'body' is only relevant for certain 'method' values) or usage tips. With high schema coverage, the baseline score of 3 is appropriate, as the description doesn't compensate but also doesn't detract.

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 'Fetch content from a URL' clearly states the verb ('fetch') and resource ('content from a URL'), making the purpose immediately understandable. It distinguishes from sibling tools like 'check-status' (which likely checks status without fetching content) and 'extract-html-fragment' (which processes HTML rather than fetching raw content). However, it doesn't specify the exact scope (e.g., HTTP/HTTPS only) or resource type (e.g., web pages, APIs), keeping it from a perfect score.

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 sibling tools like 'check-status' or 'extract-html-fragment', nor does it specify contexts such as fetching web pages versus API calls. Without this, an AI agent might struggle to choose between this tool and its siblings in appropriate scenarios.

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/mcollina/mcp-node-fetch'

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