Skip to main content
Glama

assert

Execute HTTP requests and validate responses with assertions, receiving pass/fail results for each check.

Instructions

Ejecuta un request y valida la respuesta con assertions. Retorna resultado pass/fail por cada assertion.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
methodYesHTTP method
urlYesURL del endpoint (soporta /relativa y {{variables}})
headersNoHeaders HTTP
bodyNoBody del request (JSON)
queryNoQuery parameters
authNoAutenticación
assertionsYesLista de assertions a validar contra la respuesta

Implementation Reference

  • The registerAssertTool function registers the 'assert' MCP tool. It takes a method, url, headers, body, query, auth, and an array of assertions. It executes the HTTP request, evaluates each assertion against the response, and returns a pass/fail summary.
    export function registerAssertTool(
      server: McpServer,
      storage: Storage,
      cache: ResponseCache,
    ): void {
      server.tool(
        'assert',
        'Ejecuta un request y valida la respuesta con assertions. Retorna resultado pass/fail por cada assertion.',
        {
          method: HttpMethodSchema.describe('HTTP method'),
          url: z.string().describe('URL del endpoint (soporta /relativa y {{variables}})'),
          headers: z.record(z.string()).optional().describe('Headers HTTP'),
          body: z.any().optional().describe('Body del request (JSON)'),
          query: z.record(z.string()).optional().describe('Query parameters'),
          auth: AuthSchema.optional().describe('Autenticación'),
          assertions: z
            .array(AssertionSchema)
            .describe('Lista de assertions a validar contra la respuesta'),
        },
        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,
              auth: params.auth,
            }
    
            const interpolated = interpolateRequest(config, variables)
            const response = await executeRequest(interpolated)
    
            const callId = makeCallId()
            await cache.save(callId, interpolated.method, interpolated.url, response)
    
            // Evaluate assertions
            const results = params.assertions.map((assertion) => {
              const result = evaluateAssertion(response, assertion)
              return { ...result, assertion }
            })
    
            const passed = results.filter((r) => r.pass).length
            const failed = results.filter((r) => !r.pass).length
            const allPassed = failed === 0
    
            const lines: string[] = [
              `${allPassed ? '✅ PASS' : '❌ FAIL'} — ${passed}/${results.length} assertions passed`,
              `${params.method} ${params.url} → ${response.status} ${response.statusText} (${response.timing.total_ms}ms)`,
              `call_id: ${callId}`,
              '',
            ]
    
            for (const r of results) {
              const icon = r.pass ? '✅' : '❌'
              lines.push(`${icon} ${r.message}`)
            }
    
            return {
              content: [{ type: 'text' as const, text: lines.join('\n') }],
              isError: !allPassed,
            }
          } catch (error) {
            const message = error instanceof Error ? error.message : String(error)
            return {
              content: [{ type: 'text' as const, text: `Error: ${message}` }],
              isError: true,
            }
          }
        },
      )
  • The evaluateAssertion function evaluates a single assertion against a response. It supports 10 operators: eq, neq, gt, gte, lt, lte, contains, not_contains, exists, and type.
    function evaluateAssertion(
      response: RequestResponse,
      assertion: { path: string; operator: string; expected?: unknown },
    ): { pass: boolean; message: string } {
      const actual = getByPath(response, assertion.path)
    
      switch (assertion.operator) {
        case 'eq':
          return {
            pass: actual === assertion.expected,
            message: actual === assertion.expected
              ? `${assertion.path} === ${JSON.stringify(assertion.expected)}`
              : `${assertion.path}: esperado ${JSON.stringify(assertion.expected)}, recibido ${JSON.stringify(actual)}`,
          }
    
        case 'neq':
          return {
            pass: actual !== assertion.expected,
            message: actual !== assertion.expected
              ? `${assertion.path} !== ${JSON.stringify(assertion.expected)}`
              : `${assertion.path}: no debería ser ${JSON.stringify(assertion.expected)}`,
          }
    
        case 'gt':
          return {
            pass: typeof actual === 'number' && actual > (assertion.expected as number),
            message: `${assertion.path}: ${actual} > ${assertion.expected} → ${typeof actual === 'number' && actual > (assertion.expected as number)}`,
          }
    
        case 'gte':
          return {
            pass: typeof actual === 'number' && actual >= (assertion.expected as number),
            message: `${assertion.path}: ${actual} >= ${assertion.expected} → ${typeof actual === 'number' && actual >= (assertion.expected as number)}`,
          }
    
        case 'lt':
          return {
            pass: typeof actual === 'number' && actual < (assertion.expected as number),
            message: `${assertion.path}: ${actual} < ${assertion.expected} → ${typeof actual === 'number' && actual < (assertion.expected as number)}`,
          }
    
        case 'lte':
          return {
            pass: typeof actual === 'number' && actual <= (assertion.expected as number),
            message: `${assertion.path}: ${actual} <= ${assertion.expected} → ${typeof actual === 'number' && actual <= (assertion.expected as number)}`,
          }
    
        case 'contains': {
          let pass = false
          if (typeof actual === 'string') {
            pass = actual.includes(String(assertion.expected))
          } else if (Array.isArray(actual)) {
            pass = actual.includes(assertion.expected)
          }
          return {
            pass,
            message: pass
              ? `${assertion.path} contiene ${JSON.stringify(assertion.expected)}`
              : `${assertion.path}: no contiene ${JSON.stringify(assertion.expected)}`,
          }
        }
    
        case 'not_contains': {
          let pass = true
          if (typeof actual === 'string') {
            pass = !actual.includes(String(assertion.expected))
          } else if (Array.isArray(actual)) {
            pass = !actual.includes(assertion.expected)
          }
          return {
            pass,
            message: pass
              ? `${assertion.path} no contiene ${JSON.stringify(assertion.expected)}`
              : `${assertion.path}: contiene ${JSON.stringify(assertion.expected)} (no debería)`,
          }
        }
    
        case 'exists':
          return {
            pass: actual !== undefined && actual !== null,
            message: actual !== undefined && actual !== null
              ? `${assertion.path} existe`
              : `${assertion.path}: no existe`,
          }
    
        case 'type':
          return {
            pass: typeof actual === assertion.expected,
            message: typeof actual === assertion.expected
              ? `${assertion.path} es tipo ${assertion.expected}`
              : `${assertion.path}: esperado tipo ${assertion.expected}, recibido ${typeof actual}`,
          }
    
        default:
          return { pass: false, message: `Operador desconocido: ${assertion.operator}` }
      }
    }
  • The AssertionSchema defines the Zod schema for each assertion object: path (JSONPath string), operator (enum of 10 operators), and optional expected value.
    const AssertionSchema = z.object({
      path: z
        .string()
        .describe(
          'JSONPath al valor a validar: "status", "body.data.id", "headers.content-type", "timing.total_ms"',
        ),
      operator: z
        .enum(['eq', 'neq', 'gt', 'gte', 'lt', 'lte', 'contains', 'not_contains', 'exists', 'type'])
        .describe(
          'Operador: eq (igual), neq (no igual), gt/gte/lt/lte (numéricos), contains/not_contains (strings/arrays), exists (campo existe), type (typeof)',
        ),
      expected: z.any().optional().describe('Valor esperado (no necesario para "exists")'),
    })
  • src/server.ts:66-66 (registration)
    The registration of the assert tool in the main server. registerAssertTool is called with server, storage, and responseCache.
    registerAssertTool(server, storage, responseCache)
Behavior2/5

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

With no annotations, the description must fully disclose behavioral traits. It mentions executing a request and returning pass/fail but fails to warn about potential side effects (e.g., mutable HTTP methods like POST, DELETE) or state that the request is actually sent. This could lead an agent to use it destructively without caution.

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 short sentence, which is efficient, but it lacks structure such as bullet points or separation of key points. It conveys the core idea without unnecessary words.

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, nested objects, no output schema), the description is insufficient. It does not explain how assertions work, the output format, or the implications of executing requests (e.g., costs, side effects). The agent would need to rely heavily on schema details alone.

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 coverage is 100% with already descriptive parameter descriptions. The tool description adds no extra semantic information beyond what the schema provides, meeting the baseline for high coverage.

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 tool executes a request and validates the response using assertions, returning pass/fail per assertion. This is specific and distinguishes it from sibling tools like 'request' (no assertions) and 'inspect_last_response' (inspects only).

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 offers no guidance on when to use this tool versus alternatives. It does not mention prerequisites, when not to use it, or mention any sibling tools, leaving the agent to infer appropriate usage from context.

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