Skip to main content
Glama
tuskermanshu

Swagger MCP Server

by tuskermanshu

parse-swagger-lite

Parse Swagger/OpenAPI documents to extract basic information quickly, ideal for handling large API specifications with optional filtering and caching.

Instructions

Lightweight parsing of Swagger/OpenAPI document, faster but returns only basic information (suitable for large documents).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
urlYesSwagger/OpenAPI document URL
headersNoRequest headers
includeSchemasNoWhether to include schema definitions
includeDetailsNoWhether to include all details like request bodies, responses, etc.
skipValidationNoWhether to skip validation, used for handling non-fully compliant API documents
useCacheNoWhether to use cache
cacheTTLMinutesNoCache TTL in minutes
lazyLoadingNoWhether to use lazy loading for schema parsing
filterTagNoFilter operations by tag
pathPrefixNoFilter operations by path prefix

Implementation Reference

  • Registers the 'parse-swagger-lite' MCP tool on the server, using the shared schema and a handler that forces lazy loading in the execute method.
    server.tool(
      LITE_SWAGGER_PARSER_TOOL_NAME,
      LITE_SWAGGER_PARSER_TOOL_DESCRIPTION,
      this.schema.shape,
      async ({ 
        url, 
        headers = {}, 
        includeSchemas = false, 
        includeDetails = false,
        skipValidation = true,
        useCache = true,
        cacheTTLMinutes = 60,
        filterTag,
        pathPrefix
      }) => {
        return await this.execute({ 
          url, 
          headers, 
          includeSchemas, 
          includeDetails,
          skipValidation,
          useCache,
          cacheTTLMinutes,
          lazyLoading: true, // 强制使用懒加载
          filterTag,
          pathPrefix
        });
      }
    );
  • Core handler function that executes the Swagger parsing logic using OptimizedSwaggerApiParser, handles progress, filtering, schemas with lazy loading support, and formats the output.
    async execute({
      url,
      headers = {},
      includeSchemas = false,
      includeDetails = false,
      skipValidation = true,
      useCache = true,
      cacheTTLMinutes = 60,
      lazyLoading = false,
      filterTag,
      pathPrefix
    }: z.infer<typeof this.schema> & {
      cacheTTLMinutes?: number;
    }) {
      let progress = 0;
      let progressMessage = '';
      
      // 进度回调函数
      const progressCallback = (newProgress: number, message: string) => {
        progress = newProgress;
        progressMessage = message;
        console.log(`[Progress] ${Math.round(newProgress * 100)}%: ${message}`);
      };
      
      try {
        console.log(`[OptimizedSwaggerParserTool] 解析Swagger文档: ${url}`);
        console.log(`[OptimizedSwaggerParserTool] 缓存: ${useCache ? '启用' : '禁用'}, 懒加载: ${lazyLoading ? '启用' : '禁用'}`);
        
        // 创建解析器实例
        const parser = new OptimizedSwaggerApiParser({
          url,
          headers,
          skipValidation,
          useCache,
          cacheTTL: cacheTTLMinutes * 60 * 1000, // 转换为毫秒
          lazyLoading,
          progressCallback
        });
        
        // 解析API文档
        const api = await parser.fetchApi();
        
        // 获取API操作
        let operations;
        if (filterTag) {
          operations = await parser.getOperationsByTag(filterTag);
        } else if (pathPrefix) {
          operations = await parser.getOperationsByPathPrefix(pathPrefix);
        } else {
          operations = await parser.getAllOperations();
        }
        
        // 构建结果对象
        const result: any = {
          success: true,
          progress: progress,
          progressMessage: progressMessage,
          info: {
            title: api.info.title,
            version: api.info.version,
            description: api.info.description
          },
          operationsCount: operations.length,
          operations: operations.map(op => {
            // 基本操作信息
            const operation = {
              operationId: op.operationId,
              method: op.method,
              path: op.path,
              summary: op.summary,
              tags: op.tags
            };
            
            // 如果需要详细信息,则包含参数和响应
            if (includeDetails) {
              return {
                ...operation,
                parameters: op.parameters,
                requestBody: op.requestBody,
                responses: op.responses
              };
            }
            
            return operation;
          })
        };
        
        // 如果需要模式定义
        if (includeSchemas) {
          if (lazyLoading) {
            // 使用懒加载时,只获取必要的schema
            result.schemas = {};
            
            // 获取所有操作中引用的模式
            const referencedSchemas = new Set<string>();
            
            // 处理requestBody和responses中的引用
            for (const op of operations) {
              // 处理requestBody
              if (op.requestBody && typeof op.requestBody === 'object') {
                this.collectSchemaRefs(op.requestBody, referencedSchemas);
              }
              
              // 处理responses
              if (op.responses) {
                for (const response of Object.values(op.responses)) {
                  if (response && typeof response === 'object') {
                    this.collectSchemaRefs(response, referencedSchemas);
                  }
                }
              }
            }
            
            // 获取引用的模式
            for (const schemaName of referencedSchemas) {
              const schema = await parser.getSchema(schemaName);
              if (schema) {
                result.schemas[schemaName] = schema;
              }
            }
          } else {
            // 不使用懒加载时,获取所有模式
            result.schemas = await parser.getAllSchemas();
          }
        }
        
        console.log(`[OptimizedSwaggerParserTool] 解析完成,找到 ${operations.length} 个API操作`);
        
        // 返回结果
        return {
          content: [
            {
              type: 'text' as const,
              text: JSON.stringify(result, null, 2)
            }
          ]
        };
      } catch (error) {
        console.error(`[OptimizedSwaggerParserTool] 解析失败:`, error);
        
        // 返回错误结果
        return {
          content: [
            {
              type: 'text' as const,
              text: JSON.stringify({
                success: false,
                progress: progress,
                progressMessage: progressMessage,
                error: error instanceof Error ? error.message : String(error)
              }, null, 2)
            }
          ]
        };
      }
    }
  • Zod schema defining the input parameters for the parse-swagger-lite tool (shared with parse-swagger-optimized).
    schema = z.object({
      /**
       * Swagger/OpenAPI document URL
       */
      url: z.string().describe('Swagger/OpenAPI document URL'),
      
      /**
       * Request headers
       */
      headers: z.record(z.string()).optional().describe('Request headers'),
      
      /**
       * Whether to include schema definitions
       */
      includeSchemas: z.boolean().optional().describe('Whether to include schema definitions'),
      
      /**
       * Whether to include all details
       */
      includeDetails: z.boolean().optional().describe('Whether to include all details like request bodies, responses, etc.'),
      
      /**
       * Whether to skip validation
       */
      skipValidation: z.boolean().optional().describe('Whether to skip validation, used for handling non-fully compliant API documents'),
      
      /**
       * Whether to use cache
       */
      useCache: z.boolean().optional().describe('Whether to use cache'),
      
      /**
       * Cache TTL in minutes
       */
      cacheTTLMinutes: z.number().optional().describe('Cache TTL in minutes'),
      
      /**
       * Whether to use lazy loading for schema parsing
       */
      lazyLoading: z.boolean().optional().describe('Whether to use lazy loading for schema parsing'),
      
      /**
       * Filter operations by tag
       */
      filterTag: z.string().optional().describe('Filter operations by tag'),
      
      /**
       * Filter operations by path prefix
       */
      pathPrefix: z.string().optional().describe('Filter operations by path prefix'),
    });
  • Helper method to recursively collect schema references ($ref) from operation requestBody and responses for lazy schema loading.
    private collectSchemaRefs(obj: any, refs: Set<string>): void {
      if (!obj) return;
      
      // 处理直接引用
      if (obj.$ref && typeof obj.$ref === 'string') {
        const parts = obj.$ref.split('/');
        const schemaName = parts[parts.length - 1];
        refs.add(schemaName);
        return;
      }
      
      // 处理内容对象
      if (obj.content && typeof obj.content === 'object') {
        for (const mediaType of Object.values(obj.content)) {
          if (mediaType && typeof mediaType === 'object' && 'schema' in mediaType) {
            this.collectSchemaRefs((mediaType as any).schema, refs);
          }
        }
      }
      
      // 处理模式对象
      if (obj.schema) {
        this.collectSchemaRefs(obj.schema, refs);
      }
      
      // 处理数组项
      if (obj.items) {
        this.collectSchemaRefs(obj.items, refs);
      }
      
      // 处理嵌套对象
      if (typeof obj === 'object') {
        for (const value of Object.values(obj)) {
          if (value && typeof value === 'object') {
            this.collectSchemaRefs(value, refs);
          }
        }
      }
    }
  • Constants defining the tool name and description for 'parse-swagger-lite'.
    // Lite version tool names and descriptions
    const LITE_SWAGGER_PARSER_TOOL_NAME = 'parse-swagger-lite';
    const LITE_SWAGGER_PARSER_TOOL_DESCRIPTION = 'Lightweight parsing of Swagger/OpenAPI document, faster but returns only basic information (suitable for large documents).';
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions 'faster' (performance characteristic) and 'returns only basic information' (output limitation), which adds some behavioral context. However, it doesn't address important aspects like whether this is a read-only operation, potential rate limits, authentication requirements, error handling, or what 'basic information' specifically includes. For a parsing tool with 10 parameters, this is insufficient behavioral 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 extremely concise - a single sentence that efficiently communicates the tool's purpose, performance characteristics, and appropriate use cases. Every word earns its place with zero waste or redundancy. It's appropriately sized and front-loaded with the core functionality.

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 complexity (10 parameters, no annotations, no output schema), the description is somewhat incomplete. While it effectively communicates the tool's purpose and when to use it, it lacks details about what 'basic information' specifically includes in the output, error handling, authentication requirements, and performance trade-offs. For a parsing tool with this many configuration options, more context would be helpful despite the good schema coverage.

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 schema description coverage is 100%, meaning all 10 parameters are well-documented in the schema itself. The description doesn't add any parameter-specific information beyond what's in the schema. According to scoring rules, when schema_description_coverage is high (>80%), the baseline is 3 even with no param info in the description, which applies here.

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: 'Lightweight parsing of Swagger/OpenAPI document' with the specific verb 'parsing' and resource 'Swagger/OpenAPI document'. It distinguishes from siblings by mentioning 'faster but returns only basic information' and 'suitable for large documents', though it doesn't explicitly name the sibling 'parse-swagger' for comparison.

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 provides clear context for when to use this tool: 'faster but returns only basic information (suitable for large documents)'. This implies it should be used for performance with large documents when only basic info is needed. However, it doesn't explicitly state when NOT to use it or name alternatives like 'parse-swagger' for when more detailed parsing is required.

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

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