Skip to main content
Glama
amrsa1

Swagger MCP Server

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: [],
    },
Behavior3/5

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

With no annotations provided, the description carries the full burden. It describes the core behavior (fetching documentation for discovery) but lacks details about error handling, authentication requirements, rate limits, or what format the fetched documentation is returned in. The description doesn't contradict any annotations, but provides only basic behavioral context.

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 immediately states the tool's purpose without unnecessary words. It's appropriately sized for a simple tool with one parameter and front-loads the essential information about what the tool does.

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 (fetching documentation from URLs), no annotations, and no output schema, the description is adequate but incomplete. It explains what the tool does but lacks information about return format, error conditions, or authentication requirements that would help an agent use it effectively.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description doesn't mention parameters directly, but the single parameter has 100% schema description coverage that clearly explains its purpose and default behavior. With only one well-documented parameter, the description doesn't need to add parameter semantics, earning a baseline score above minimum viable.

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 verb 'fetch' and the resource 'Swagger/OpenAPI documentation', specifying the action of retrieving API endpoint discovery information. It distinguishes from siblings like 'execute_api_request' (which performs API calls) and 'list_endpoints' (which might list already-discovered endpoints) by focusing on documentation discovery.

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?

The description implies usage context ('to discover available API endpoints'), suggesting this tool should be used when exploring an API's capabilities. However, it doesn't explicitly state when NOT to use it or name specific alternatives among the siblings, though the purpose differentiation provides some guidance.

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