Skip to main content
Glama
tuskermanshu

Swagger MCP Server

by tuskermanshu

parse-swagger

Extract API operation details from Swagger/OpenAPI documents to generate TypeScript types and client code for frameworks like Axios, Fetch, and React Query.

Instructions

Parse Swagger/OpenAPI document and return API operation information.

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.

Implementation Reference

  • Core handler function that executes the Swagger parsing logic: fetches the document, extracts operations, optionally includes schemas and details, handles errors, and returns formatted JSON result.
    async execute({
      url,
      headers = {},
      includeSchemas = false,
      includeDetails = false
    }: z.infer<typeof this.schema>) {
      try {
        console.log(`[SwaggerParserTool] 解析Swagger文档: ${url}`);
        
        // 创建解析器实例
        const parser = new OptimizedSwaggerApiParser({ 
          url, 
          headers, 
          useCache: true, 
          skipValidation: true 
        });
        
        // 解析API文档
        const api = await parser.fetchApi();
        
        // 获取API操作
        const operations = await parser.getAllOperations();
        
        // 构建结果对象
        const result: any = {
          success: true,
          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) {
          result.schemas = await parser.getAllSchemas();
        }
        
        console.log(`[SwaggerParserTool] 解析完成,找到 ${operations.length} 个API操作`);
        
        // 返回结果
        return {
          content: [
            {
              type: 'text' as const,
              text: JSON.stringify(result, null, 2)
            }
          ]
        };
      } catch (error) {
        console.error(`[SwaggerParserTool] 解析失败:`, error);
        
        // 返回错误结果
        return {
          content: [
            {
              type: 'text' as const,
              text: JSON.stringify({
                success: false,
                error: error instanceof Error ? error.message : String(error)
              }, null, 2)
            }
          ]
        };
      }
    }
  • Zod schema defining input parameters for the parse-swagger tool: url (required), headers (optional), includeSchemas (optional), includeDetails (optional).
    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.')
    });
  • Method to register the parse-swagger tool on the MCP server using server.tool(name, description, schema, handler).
    register(server: McpServer) {
      server.tool(
        this.name,
        this.description,
        this.schema.shape,
        async ({ url, headers = {}, includeSchemas = false, includeDetails = false }) => {
          return await this.execute({ url, headers, includeSchemas, includeDetails });
        }
      );
    }
  • Instantiates SwaggerParserTool (parse-swagger) and calls its register method as part of registering all tools on the MCP server.
    const tools = [
      new SwaggerParserTool(),
      new OptimizedSwaggerParserTool(),
      new TypeScriptTypesGeneratorTool(),
      new ApiClientGeneratorTool(),
      new FileWriterTool(),
    ];
    
    for (const tool of tools) {
      tool.register(server);
      console.log(`✅ 已注册工具: ${tool.name}`);
    }

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