Skip to main content
Glama
amrsa1

Swagger MCP Server

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}`);
      }
    }
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 what the tool does but doesn't describe how it behaves: e.g., whether it returns validation results, errors, or passes/fails; if it requires pre-loaded Swagger docs; or any performance or rate-limiting considerations. This leaves significant gaps for a validation tool.

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 appropriately sized and front-loaded, making it easy to understand quickly.

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 (validating API responses against schemas) and lack of annotations and output schema, the description is incomplete. It doesn't explain what the tool returns (e.g., validation results, errors), how it accesses Swagger documentation, or any behavioral traits, leaving the agent with insufficient context for effective use.

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, with all parameters documented. The description doesn't add any meaning beyond what the schema provides (e.g., it doesn't explain parameter relationships or validation specifics). With high schema coverage, the baseline is 3, as 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 resource ('API response'), but doesn't explicitly differentiate from sibling tools like 'execute_api_request' or 'fetch_swagger_info' that might handle related but different 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), when not to use it, or how it relates to siblings like 'execute_api_request' (which might produce responses to validate) or 'fetch_swagger_info' (which might provide schemas).

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/amrsa1/swagger-mcp'

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