Skip to main content
Glama

request

Execute HTTP requests with relative URL resolution, variable interpolation, authentication, and adjustable verbosity to control token usage.

Instructions

Ejecuta un HTTP request. URLs relativas (/path) usan BASE_URL del entorno activo. Soporta {{variables}}. La respuesta se comprime por defecto (verbosity=normal) para ahorrar tokens; usa verbosity=full o inspect_last_response si necesitas la respuesta completa.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
methodYesHTTP method
urlYesURL del endpoint. Si empieza con / se antepone BASE_URL del entorno activo. Soporta {{variables}}.
headersNoHeaders HTTP como key-value pairs
bodyNoBody del request (JSON). Soporta {{variables}}
queryNoQuery parameters como key-value pairs
timeoutNoTimeout en milisegundos (default: 30000)
authNoConfiguración de autenticación
verbosityNoControls response detail to save context tokens. Default: 'normal'. - 'minimal': Only status, method, url, elapsed_ms, and first 200 chars of body. USE FOR: health checks (/health, /ping), status polling loops, fire-and-forget POST/DELETE, waiting for a job to complete, or when you only care whether the call succeeded. SAVES: ~95% tokens vs full. - 'normal' (DEFAULT): Filtered headers (omits Date, Server, CF-*, Set-Cookie, etc.) + body truncated to max_body_bytes with 'body_truncated' flag. USE FOR: most debugging — CRUDs, checking error messages, API contract exploration. SAVES: ~75% tokens vs full. - 'full': Complete response untouched. USE FOR: debugging CORS/cache/auth headers, large bodies you must inspect completely, or when the user asks to see everything. NO SAVINGS. If a response is truncated and you need more, prefer inspect_last_response({call_id}) over re-running with 'full'.
only_fieldsNoCheap alternative to 'full' when you know exactly what you need from the body. Returns only these dot-paths. Supports array index and wildcard. Examples: ["data.id"], ["user.email", "user.role"], ["items[*].id", "meta.total"]. Often saves >95% vs full while keeping the fields you care about.
max_body_bytesNoMax body size in bytes for verbosity='normal' (default: 2048). Ignored for minimal/full.

Implementation Reference

  • The async handler function that executes the 'request' tool logic: resolves URL, interpolates variables, executes HTTP request, caches response, compresses output.
        async (params) => {
          try {
            const variables = await storage.getActiveVariables()
            const resolvedUrl = resolveUrl(params.url, variables)
    
            const config: RequestConfig = {
              method: params.method,
              url: resolvedUrl,
              headers: params.headers,
              body: params.body,
              query: params.query,
              timeout: params.timeout,
              auth: params.auth,
            }
    
            const interpolated = interpolateRequest(config, variables)
            const response = await executeRequest(interpolated)
    
            const callId = makeCallId()
            // Guarda la response full para poder recuperarla con inspect_last_response
            await cache.save(callId, interpolated.method, interpolated.url, response)
    
            const compressed = compressResponse(response, {
              verbosity: params.verbosity,
              only_fields: params.only_fields,
              max_body_bytes: params.max_body_bytes,
              request_method: interpolated.method,
              request_url: interpolated.url,
              call_id: callId,
            })
    
            return {
              content: [
                {
                  type: 'text' as const,
                  text: JSON.stringify(compressed, null, 2),
                },
              ],
            }
          } catch (error) {
            const message = error instanceof Error ? error.message : String(error)
            return {
              content: [{ type: 'text' as const, text: `Error: ${message}` }],
              isError: true,
            }
          }
        },
      )
    }
  • Zod schema definitions for the 'request' tool parameters: method, url, headers, body, query, timeout, auth, and verbosity options.
    {
      method: HttpMethodSchema.describe('HTTP method'),
      url: z
        .string()
        .describe(
          'URL del endpoint. Si empieza con / se antepone BASE_URL del entorno activo. Soporta {{variables}}.',
        ),
      headers: z
        .record(z.string())
        .optional()
        .describe('Headers HTTP como key-value pairs'),
      body: z.any().optional().describe('Body del request (JSON). Soporta {{variables}}'),
      query: z
        .record(z.string())
        .optional()
        .describe('Query parameters como key-value pairs'),
      timeout: z.number().optional().describe('Timeout en milisegundos (default: 30000)'),
      auth: z
        .object(AuthSchemaShape)
        .optional()
        .describe('Configuración de autenticación'),
      ...VerbosityShape,
    },
  • The registerRequestTool function that registers the 'request' tool on the MCP server via server.tool().
    export function registerRequestTool(
      server: McpServer,
      storage: Storage,
      cache: ResponseCache,
    ): void {
      server.tool(
        'request',
        'Ejecuta un HTTP request. URLs relativas (/path) usan BASE_URL del entorno activo. Soporta {{variables}}. La respuesta se comprime por defecto (verbosity=normal) para ahorrar tokens; usa verbosity=full o inspect_last_response si necesitas la respuesta completa.',
        {
          method: HttpMethodSchema.describe('HTTP method'),
          url: z
            .string()
            .describe(
              'URL del endpoint. Si empieza con / se antepone BASE_URL del entorno activo. Soporta {{variables}}.',
            ),
          headers: z
            .record(z.string())
            .optional()
            .describe('Headers HTTP como key-value pairs'),
          body: z.any().optional().describe('Body del request (JSON). Soporta {{variables}}'),
          query: z
            .record(z.string())
            .optional()
            .describe('Query parameters como key-value pairs'),
          timeout: z.number().optional().describe('Timeout en milisegundos (default: 30000)'),
          auth: z
            .object(AuthSchemaShape)
            .optional()
            .describe('Configuración de autenticación'),
          ...VerbosityShape,
        },
        async (params) => {
          try {
            const variables = await storage.getActiveVariables()
            const resolvedUrl = resolveUrl(params.url, variables)
    
            const config: RequestConfig = {
              method: params.method,
              url: resolvedUrl,
              headers: params.headers,
              body: params.body,
              query: params.query,
              timeout: params.timeout,
              auth: params.auth,
            }
    
            const interpolated = interpolateRequest(config, variables)
            const response = await executeRequest(interpolated)
    
            const callId = makeCallId()
            // Guarda la response full para poder recuperarla con inspect_last_response
            await cache.save(callId, interpolated.method, interpolated.url, response)
    
            const compressed = compressResponse(response, {
              verbosity: params.verbosity,
              only_fields: params.only_fields,
              max_body_bytes: params.max_body_bytes,
              request_method: interpolated.method,
              request_url: interpolated.url,
              call_id: callId,
            })
    
            return {
              content: [
                {
                  type: 'text' as const,
                  text: JSON.stringify(compressed, null, 2),
                },
              ],
            }
          } catch (error) {
            const message = error instanceof Error ? error.message : String(error)
            return {
              content: [{ type: 'text' as const, text: `Error: ${message}` }],
              isError: true,
            }
          }
        },
      )
    }
  • src/server.ts:62-62 (registration)
    Invocation of registerRequestTool in the server setup, wiring storage and response cache dependencies.
    registerRequestTool(server, storage, responseCache)
  • The executeRequest helper function that performs the actual HTTP fetch, handles auth, body serialization, timeout, and returns structured response.
    export async function executeRequest(config: RequestConfig): Promise<RequestResponse> {
      const timeout = config.timeout ?? DEFAULT_TIMEOUT
    
      // Construir URL con query params
      const url = buildUrl(config.url, config.query)
    
      // Preparar headers — Accept: application/json por defecto
      let headers: Record<string, string> = {
        Accept: 'application/json',
        ...config.headers,
      }
    
      // Aplicar auth
      if (config.auth) {
        headers = applyAuth(headers, config.auth)
      }
    
      // Preparar body
      let body: string | undefined
      if (config.body !== undefined && config.body !== null) {
        if (typeof config.body === 'string') {
          body = config.body
        } else {
          body = JSON.stringify(config.body)
          // Solo añadir Content-Type si no está definido
          if (!headers['Content-Type'] && !headers['content-type']) {
            headers['Content-Type'] = 'application/json'
          }
        }
      }
    
      // AbortController para timeout
      const controller = new AbortController()
      const timeoutId = setTimeout(() => controller.abort(), timeout)
    
      // Medir timing
      const startTime = performance.now()
    
      try {
        const response = await fetch(url, {
          method: config.method,
          headers,
          body,
          signal: controller.signal,
        })
    
        const endTime = performance.now()
        const totalMs = Math.round((endTime - startTime) * 100) / 100
    
        // Parsear response body
        const responseText = await response.text()
        let responseBody: unknown
        try {
          responseBody = JSON.parse(responseText)
        } catch {
          responseBody = responseText
        }
    
        // Convertir headers a Record
        const responseHeaders: Record<string, string> = {}
        response.headers.forEach((value, key) => {
          responseHeaders[key] = value
        })
    
        // Calcular tamaño
        const sizeBytes =
          Number(response.headers.get('content-length')) ||
          Buffer.byteLength(responseText, 'utf-8')
    
        return {
          status: response.status,
          statusText: response.statusText,
          headers: responseHeaders,
          body: responseBody,
          timing: { total_ms: totalMs },
          size_bytes: sizeBytes,
        }
      } catch (error) {
        if (error instanceof Error && error.name === 'AbortError') {
          throw new Error(`Request timeout: superado el límite de ${timeout}ms`)
        }
        throw error
      } finally {
        clearTimeout(timeoutId)
      }
    }
Behavior4/5

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

With no annotations, the description carries full burden. It discloses that responses are compressed by default (verbosity=normal) to save tokens, supports {{variables}}, and relative URLs use BASE_URL. These are key behavioral traits.

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 a single concise paragraph covering key details without unnecessary repetition. It is front-loaded with the core action. Could be slightly more structured with bullet points, but it's efficient.

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

Completeness4/5

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

Given 10 parameters with 100% schema coverage and no output schema, the description plus schema provide adequate guidance for usage. It hints at response behavior (compressed by default) and points to inspect_last_response for full data, covering completeness needs.

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 explains parameters thoroughly. The description adds context about compression and inspect_last_response but does not significantly expand parameter meaning beyond schema descriptions like verbosity examples.

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 'Ejecuta un HTTP request' (executes an HTTP request), specifying the verb and resource. It distinguishes from sibling tools like inspect_last_response by mentioning it as an alternative for full responses.

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

Usage Guidelines4/5

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

Provides explicit guidance on verbosity levels and when to use inspect_last_response instead of re-running with full verbosity. However, lacks explicit comparisons with siblings like api_endpoint_detail, though the context makes the primary use case clear.

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/cocaxcode/api-testing-mcp'

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