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}`);
    }
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 mentions parsing and returning information but doesn't describe important behaviors like error handling (e.g., invalid URLs, malformed documents), performance characteristics, or whether it makes network requests (implied by URL parameter but not explicit). For a tool with no annotation coverage, this leaves significant gaps in understanding how it operates.

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 core functionality. It's front-loaded with the essential information and contains no unnecessary words or redundant explanations. Every word earns its place in this minimal but complete statement of purpose.

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 (4 parameters including nested objects, no output schema, no annotations), the description is adequate but incomplete. It explains what the tool does at a high level but lacks details about output format, error conditions, or behavioral characteristics. The description would benefit from additional context about what 'API operation information' includes and how it's structured.

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, providing clear documentation for all four parameters. The description adds no additional parameter semantics 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: 'Parse Swagger/OpenAPI document and return API operation information.' It specifies the verb (parse), resource (Swagger/OpenAPI document), and output (API operation information). However, it doesn't explicitly differentiate from sibling tools like 'parse-swagger-lite' or 'parse-swagger-optimized', which prevents a perfect score.

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. With multiple sibling tools like 'parse-swagger-lite' and 'parse-swagger-optimized', there's no indication of differences in functionality, performance, or use cases. The description only states what the tool does, not when it should be selected over other options.

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