Skip to main content
Glama
amrsa1

Swagger MCP Server

by amrsa1

validate_api_response

Validate API responses against Swagger/OpenAPI schemas to ensure compliance with documented specifications.

Instructions

Validate an API response against the schema from Swagger documentation

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesThe endpoint path
methodYesThe HTTP method
statusCodeYesThe HTTP status code
responseBodyYesThe response body to validate

Implementation Reference

  • The core handler function that validates the API response body against the expected schema from Swagger documentation for the specified endpoint and status code.
    function validateApiResponse(path, method, statusCode, responseBody) {
      if (!path) {
        throw new Error('Path is required for API response validation');
      }
      if (!method) {
        throw new Error('Method is required for API response validation');
      }
      if (statusCode === undefined || statusCode === null) {
        throw new Error('Status code is required for API response validation');
      }
      if (responseBody === undefined) {
        throw new Error('Response body is required for API response validation');
      }
      
      if (!swaggerDoc) {
        throw new Error('Swagger documentation not loaded. Call fetch_swagger_info first.');
      }
      
      try {
        const endpoints = swaggerDoc.paths || {};
        method = method.toLowerCase();
        
        if (!endpoints[path] || !endpoints[path][method]) {
          throw new Error(`Endpoint ${method.toUpperCase()} ${path} not found in the Swagger documentation`);
        }
        
        const endpoint = endpoints[path][method];
        const responses = endpoint.responses || {};
        const responseSpec = responses[statusCode] || responses['default'];
        
        if (!responseSpec) {
          return {
            valid: false,
            errors: [`No schema defined for status code ${statusCode} in Swagger documentation`]
          };
        }
        
    
        const issues = [];
        
        if (responseSpec.schema) {
          try {
            if (responseSpec.schema.type === 'object' && typeof responseBody !== 'object') {
              issues.push(`Expected response to be an object, but got ${typeof responseBody}`);
            } else if (responseSpec.schema.type === 'array' && !Array.isArray(responseBody)) {
              issues.push(`Expected response to be an array, but got ${typeof responseBody}`);
            }
            
            issues.push('Note: Full schema validation requires a JSON Schema validator library');
          } catch (schemaError) {
            issues.push(`Schema validation error: ${schemaError.message}`);
          }
        }
        
        return {
          valid: issues.length === 0,
          errors: issues,
          schema: responseSpec.schema || null,
          expectedStatusCodes: Object.keys(responses),
          actualStatusCode: statusCode,
          responseSpec: responseSpec
        };
      } catch (error) {
        log.error(`Error validating API response: ${error.message}`);
        throw new Error(`Response validation failed: ${error.message}`);
      }
    }
  • Input schema defining the parameters for the validate_api_response tool: path, method, statusCode, and responseBody.
    inputSchema: {
      type: "object",
      properties: {
        path: { 
          type: "string", 
          description: "The endpoint path" 
        },
        method: { 
          type: "string", 
          description: "The HTTP method" 
        },
        statusCode: { 
          type: "number", 
          description: "The HTTP status code" 
        },
        responseBody: { 
          type: "object", 
          description: "The response body to validate"
        }
      },
      required: ["path", "method", "statusCode", "responseBody"],
    },
  • src/server.js:226-251 (registration)
    Registration of the validate_api_response tool in the tools array used by the MCP server capabilities.
    {
      name: "validate_api_response",
      description: "Validate an API response against the schema from Swagger documentation",
      inputSchema: {
        type: "object",
        properties: {
          path: { 
            type: "string", 
            description: "The endpoint path" 
          },
          method: { 
            type: "string", 
            description: "The HTTP method" 
          },
          statusCode: { 
            type: "number", 
            description: "The HTTP status code" 
          },
          responseBody: { 
            type: "object", 
            description: "The response body to validate"
          }
        },
        required: ["path", "method", "statusCode", "responseBody"],
      },
    }
  • The switch case in the CallToolRequestSchema handler that processes calls to validate_api_response and invokes the validateApiResponse function.
    case "validate_api_response": {
      const path = request.params.arguments?.path;
      const method = request.params.arguments?.method;
      const statusCode = request.params.arguments?.statusCode;
      const responseBody = request.params.arguments?.responseBody;
      
      const missingParams = [];
      if (!path) missingParams.push('path');
      if (!method) missingParams.push('method');
      if (statusCode === undefined) missingParams.push('statusCode');
      if (responseBody === undefined) missingParams.push('responseBody');
      
      if (missingParams.length > 0) {
        const errorMessage = `Missing required parameters for API response validation: ${missingParams.join(', ')}`;
        log.error(errorMessage);
        throw new Error(errorMessage);
      }
    
      try {
        log.info(`Validating response for ${method.toUpperCase()} ${path} with status ${statusCode}`);
        let parsedBody = responseBody;
        if (typeof responseBody === 'string') {
          try {
            parsedBody = JSON.parse(responseBody);
            log.info('Successfully parsed response body string as JSON');
          } catch (parseError) {
            log.warning(`Response body is a string but not valid JSON: ${parseError.message}`);
          }
        }
        
        const result = validateApiResponse(path, method, statusCode, parsedBody);
        
        if (result.valid) {
          log.success('Response validation passed');
        } else {
          log.warning(`Response validation found ${result.errors.length} issues`);
          result.errors.forEach(error => log.debug(`Validation issue: ${error}`));
        }
        
        return {
          content: [{ 
            type: "text", 
            text: JSON.stringify(result)
          }],
          isError: false,
        };
      } catch (error) {
        log.error(`Failed to validate API response: ${error.message}`);
        throw new Error(`Failed to validate API response: ${error.message}`);
      }
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

B3.1/5.0
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. It states the tool validates responses but doesn't explain how validation works (e.g., returns validation errors, success/failure status), what happens on failure, or any side effects. For a validation tool with zero annotation coverage, 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 directly states the tool's purpose without unnecessary words. It's front-loaded and wastes no space, making it easy to parse quickly.

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?

Given the tool's moderate complexity (4 parameters, validation logic) and lack of annotations or output schema, the description is minimally adequate. It covers the basic purpose but fails to provide critical context like validation outcomes, error handling, or integration with sibling tools, leaving gaps for an AI agent.

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, clearly documenting all four parameters (path, method, statusCode, responseBody). The description adds no additional parameter semantics beyond what the schema provides, such as format examples or constraints. Baseline 3 is appropriate when the schema does the heavy lifting.

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 tool's purpose: 'Validate an API response against the schema from Swagger documentation'. It specifies the verb 'validate' and the resource 'API response', making it understandable. However, it doesn't explicitly differentiate from sibling tools like 'execute_api_request' or 'fetch_swagger_info', which might handle related but distinct operations.

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 prerequisites (e.g., needing Swagger documentation loaded), context (e.g., after an API call), or exclusions. With siblings like 'execute_api_request' and 'fetch_swagger_info', this lack of differentiation leaves usage ambiguous.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.