Skip to main content
Glama
amrsa1

Swagger MCP Server

by amrsa1

fetch_swagger_info

Retrieve API endpoint details from Swagger/OpenAPI documentation to understand available operations and parameters.

Instructions

Fetch Swagger/OpenAPI documentation to discover available API endpoints

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
urlNoURL to the swagger.json or swagger.yaml file. If not provided, will try to use the base URL with common Swagger paths.

Implementation Reference

  • The handler function for the 'fetch_swagger_info' tool within the CallToolRequestSchema handler's switch statement. It calls fetchSwaggerDoc with the provided or configured URL and returns a JSON summary of the API documentation including title, version, paths count, etc.
    case "fetch_swagger_info": {
      const url = request.params.arguments?.url;
      
      try {
        const result = await fetchSwaggerDoc(API_DOCS_URL || url);
        return {
          content: [{ 
            type: "text", 
            text: JSON.stringify({
              title: result.info?.title || 'API Documentation',
              version: result.info?.version || 'Unknown',
              description: result.info?.description || 'No description available',
              swaggerVersion: result.swagger || result.openapi || 'Unknown',
              servers: result.servers || [{ url: API_BASE_URL }],
              pathCount: Object.keys(result.paths || {}).length,
              tagCount: (result.tags || []).length,
              docsUrl: swaggerUrl
            })
          }],
          isError: false,
        };
      } catch (error) {
        throw new Error(`Failed to fetch Swagger info: ${error.message}`);
      }
    }
  • The core helper function that implements the logic to fetch Swagger/OpenAPI documentation. Supports explicit URL, configured API_DOCS_URL, or auto-discovery from common paths on API_BASE_URL. Handles authentication and sets global swaggerDoc.
    async function fetchSwaggerDoc(url = null) {
      try {
        if (url) {
          const isFullUrl = url.startsWith('http://') || url.startsWith('https://');
          let effectiveUrl = url;
          
          if (!isFullUrl && API_BASE_URL) {
            log.info(`Path-only URL provided, appending to API_BASE_URL`);
            effectiveUrl = buildUrl(url);
            log.api('GET', effectiveUrl);
          } else {
            log.api('GET', url);        
            try {
              const parsedUrl = new URL(url);
              const urlBase = `${parsedUrl.protocol}//${parsedUrl.host}`;
              
              if (API_BASE_URL && urlBase !== API_BASE_URL) {
                log.warning(`URL base ${urlBase} differs from configured API_BASE_URL ${API_BASE_URL}`);
                log.warning('This URL will be used for Swagger docs only, other operations will still use configured API_BASE_URL');
              }
            } catch (e) {
              log.warning(`Invalid URL format: ${url}`);
            }
          }
          
          const response = await fetch(effectiveUrl, {
            method: 'GET',
            headers: {
              'Accept': 'application/json',
              ...getAuthHeader(true)
            }
          });
          
          if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`Failed to fetch Swagger doc: ${response.status} ${errorText}`);
          }
          
          const doc = await response.json();
          swaggerDoc = doc;
          swaggerUrl = effectiveUrl;
          
          log.success(`Successfully fetched Swagger documentation from ${effectiveUrl}`);
          
          return doc;
        }
        
        if (API_DOCS_URL) {
          log.info(`Trying configured docs URL: ${API_DOCS_URL}`);
          try {
            const response = await fetch(API_DOCS_URL, {
              method: 'GET',
              headers: {
                'Accept': 'application/json',
                ...getAuthHeader()
              }
            });
            
            if (response.ok) {
              const doc = await response.json();
              swaggerDoc = doc;
              swaggerUrl = API_DOCS_URL;
              
              log.success(`Successfully fetched Swagger documentation from ${API_DOCS_URL}`);
              
              return doc;
            } else {
              log.debug(`Failed to fetch from configured docs URL: ${response.status} ${response.statusText}`);
              
              if (!API_DOCS_URL.endsWith('.json')) {
                const jsonUrl = `${API_DOCS_URL}.json`;
                log.debug(`Trying with .json extension: ${jsonUrl}`);
                const jsonResponse = await fetch(jsonUrl, {
                  method: 'GET',
                  headers: {
                    'Accept': 'application/json',
                    ...getAuthHeader()
                  }
                });
                
                if (jsonResponse.ok) {
                  const doc = await jsonResponse.json();
                  swaggerDoc = doc;
                  swaggerUrl = jsonUrl;
                  
                  log.success(`Successfully fetched Swagger documentation from ${jsonUrl}`);
                  
                  return doc;
                }
              }
            }
          } catch (error) {
            log.debug(`Error fetching from configured docs URL: ${error.message}`);
          }
        }
        
        if (!API_BASE_URL) {
          throw new Error('No API_BASE_URL configured and no explicit Swagger URL provided');
        }
        
        const commonPaths = [
          '/api-docs',
          '/api-docs.json',
          '/api-docs/swagger.json',
          '/api-docs/v1/swagger.json',
          '/swagger',
          '/swagger.json',
          '/swagger/v1/swagger.json',
          '/swagger-ui',
          '/swagger-ui.json',
          '/swagger-ui/swagger.json',
          '/openapi',
          '/openapi.json',
          '/docs',
          '/docs.json',
          '/docs/swagger.json'
        ];
        
        log.info(`Auto-discovering Swagger docs from ${commonPaths.length} common paths...`);
        
        let attemptCount = 0;
        
        for (const path of commonPaths) {
          const testUrl = buildUrl(path);
          attemptCount++;
          
          try {
            const response = await fetch(testUrl, { 
              method: 'GET',
              headers: {
                'Accept': 'application/json',
                ...getAuthHeader()
              }
            });
            
            if (response.ok) {
              const contentType = response.headers.get('content-type');
              if (contentType && contentType.includes('application/json')) {
                const doc = await response.json();
                swaggerDoc = doc;
                swaggerUrl = testUrl;
                
                log.success(`Successfully fetched Swagger documentation from ${testUrl}`);
                
                return doc;
              } else {
                log.debug(`Found path ${testUrl} but content type is not JSON: ${contentType}`);
              }
            }
          } catch (e) {
            if (attemptCount <= 3) {
              log.debug(`Failed to fetch from ${testUrl}: ${e.message}`);
            }
          }
        }
        
        log.debug(`Attempted ${attemptCount} common paths for Swagger documentation`);
        
        throw new Error('Could not find Swagger documentation at any common paths. Please provide explicit URL.');
      } catch (error) {
        log.error(`Error fetching Swagger documentation: ${error.message}`);
        throw new Error(`Failed to fetch Swagger documentation: ${error.message}`);
      }
    }
  • src/server.js:155-168 (registration)
    Registration of the 'fetch_swagger_info' tool in the tools array, which is used to build the server capabilities object passed to the MCP Server constructor.
    {
      name: "fetch_swagger_info",
      description: "Fetch Swagger/OpenAPI documentation to discover available API endpoints",
      inputSchema: {
        type: "object",
        properties: {
          url: { 
            type: "string", 
            description: "URL to the swagger.json or swagger.yaml file. If not provided, will try to use the base URL with common Swagger paths." 
          }
        },
        required: [],
      },
    },
  • Input schema for the 'fetch_swagger_info' tool, defining an optional 'url' parameter.
    inputSchema: {
      type: "object",
      properties: {
        url: { 
          type: "string", 
          description: "URL to the swagger.json or swagger.yaml file. If not provided, will try to use the base URL with common Swagger paths." 
        }
      },
      required: [],
    },

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

C2.9/5.0
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states what the tool does but doesn't describe how it behaves—such as whether it makes network requests, handles errors, returns structured data, or has any side effects. This leaves significant gaps for an agent to understand the tool's operation.

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, clear sentence that efficiently conveys the tool's purpose without any wasted words. It's appropriately sized and front-loaded, making it easy for an agent to parse 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 lack of annotations and output schema, the description is incomplete for a tool that likely returns complex API documentation. It doesn't explain what the output looks like (e.g., JSON/YAML structure), potential errors, or how it interacts with sibling tools, 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, so the schema already documents the single parameter ('url') adequately. The description adds no additional meaning or context about the parameter beyond what's in the schema, such as examples or constraints, but this is acceptable given the high schema coverage.

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 with a specific verb ('fetch') and resource ('Swagger/OpenAPI documentation'), and indicates what it's used for ('to discover available API endpoints'). However, it doesn't explicitly differentiate this from sibling tools like 'list_endpoints' or 'get_endpoint_details', which might have overlapping functionality.

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 like 'list_endpoints' or 'get_endpoint_details'. It mentions the purpose but doesn't specify scenarios, prerequisites, or exclusions that would help an agent choose between these related tools.

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