Skip to main content
Glama
tuskermanshu

Swagger MCP Server

by tuskermanshu

generate-typescript-types-optimized

Generate TypeScript type definitions from Swagger/OpenAPI documents with caching support and optimized handling for large specifications.

Instructions

Generate TypeScript type definitions from Swagger/OpenAPI document with optimized options for caching and large document support.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
swaggerUrlYesSwagger/OpenAPI document URL
outputDirNoOutput directory
overwriteNoWhether to overwrite existing files
filePrefixNoFile prefix
fileSuffixNoFile suffix
useNamespaceNoWhether to use namespace for wrapping types
namespaceNoNamespace name
generateEnumsNoWhether to generate enum types
strictTypesNoWhether to use strict types
excludeSchemasNoArray of schema names to exclude
includeSchemasNoArray of schema names to include
generateIndexNoWhether to generate an index file
headersNoRequest headers
useCacheNoWhether to use cache
cacheTTLMinutesNoCache TTL in minutes
skipValidationNoWhether to skip validation
lazyLoadingNoWhether to use lazy loading

Implementation Reference

  • Core handler function that executes the TypeScript types generation, manages progress reporting, handles the generator instance, processes results, and formats the MCP response content.
    async execute(params: z.infer<typeof this.schema>) {
      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(`[TypeScriptTypesGeneratorTool] 开始生成TypeScript类型: ${params.swaggerUrl}`);
        console.log(`[TypeScriptTypesGeneratorTool] 缓存: ${params.useCache ? '启用' : '禁用'}, 懒加载: ${params.lazyLoading ? '启用' : '禁用'}`);
        
        // 创建生成器实例
        const generator = new TypeScriptTypesGenerator();
        
        // 执行生成
        const result = await generator.generate({
          ...params,
          progressCallback
        } as TypeScriptTypesGeneratorOptions);
        
        // 处理结果
        if (result.success) {
          console.log(`[TypeScriptTypesGeneratorTool] 类型生成成功,生成了 ${result.files.length} 个文件`);
          
          return {
            content: [
              {
                type: 'text' as const,
                text: JSON.stringify({
                  success: true,
                  files: result.files,
                  warnings: result.warnings,
                  progress: 1.0,
                  progressMessage: '完成'
                }, null, 2)
              }
            ]
          };
        } else {
          console.error(`[TypeScriptTypesGeneratorTool] 类型生成失败: ${result.error}`);
          
          return {
            content: [
              {
                type: 'text' as const,
                text: JSON.stringify({
                  success: false,
                  error: result.error,
                  progress: progress,
                  progressMessage: progressMessage
                }, null, 2)
              }
            ]
          };
        }
      } catch (error) {
        console.error(`[TypeScriptTypesGeneratorTool] 执行异常:`, error);
        
        // 返回错误结果
        return {
          content: [
            {
              type: 'text' as const,
              text: JSON.stringify({
                success: false,
                error: error instanceof Error ? error.message : String(error),
                progress: progress,
                progressMessage: progressMessage
              }, null, 2)
            }
          ]
        };
      }
    }
  • MCP server.tool() registration specifically for the 'generate-typescript-types-optimized' tool, applying optimized default parameters before delegating to the execute handler.
    // 注册优化版工具
    server.tool(
      TS_TYPES_GENERATOR_OPTIMIZED_TOOL_NAME,
      TS_TYPES_GENERATOR_OPTIMIZED_TOOL_DESCRIPTION,
      this.schema.shape,
      async (params) => {
        // 默认启用性能优化选项
        const options = {
          ...params,
          useCache: params.useCache !== false,
          skipValidation: params.skipValidation !== false,
          lazyLoading: params.lazyLoading !== false
        };
        return await this.execute(options);
      }
    );
  • Zod schema defining the input parameters for the tool, including swaggerUrl, output options, filtering, and optimization flags like useCache, skipValidation, lazyLoading.
    schema = z.object({
      /**
       * Swagger/OpenAPI document URL
       */
      swaggerUrl: z.string().describe('Swagger/OpenAPI document URL'),
      
      /**
       * Output directory
       */
      outputDir: z.string().optional().describe('Output directory'),
      
      /**
       * Whether to overwrite existing files
       */
      overwrite: z.boolean().optional().describe('Whether to overwrite existing files'),
      
      /**
       * File prefix
       */
      filePrefix: z.string().optional().describe('File prefix'),
      
      /**
       * File suffix
       */
      fileSuffix: z.string().optional().describe('File suffix'),
      
      /**
       * Whether to use namespace
       */
      useNamespace: z.boolean().optional().describe('Whether to use namespace for wrapping types'),
      
      /**
       * Namespace name
       */
      namespace: z.string().optional().describe('Namespace name'),
      
      /**
       * Whether to generate enums
       */
      generateEnums: z.boolean().optional().describe('Whether to generate enum types'),
      
      /**
       * Whether to use strict types
       */
      strictTypes: z.boolean().optional().describe('Whether to use strict types'),
      
      /**
       * Excluded schema names
       */
      excludeSchemas: z.array(z.string()).optional().describe('Array of schema names to exclude'),
      
      /**
       * Included schema names
       */
      includeSchemas: z.array(z.string()).optional().describe('Array of schema names to include'),
      
      /**
       * Whether to generate index file
       */
      generateIndex: z.boolean().optional().describe('Whether to generate an index file'),
      
      /**
       * Request headers
       */
      headers: z.record(z.string()).optional().describe('Request headers'),
      
      /**
       * 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 skip validation
       */
      skipValidation: z.boolean().optional().describe('Whether to skip validation'),
      
      /**
       * Whether to use lazy loading
       */
      lazyLoading: z.boolean().optional().describe('Whether to use lazy loading')
    });
  • Constants defining the tool name and description for the optimized version.
    const TS_TYPES_GENERATOR_OPTIMIZED_TOOL_NAME = 'generate-typescript-types-optimized';
    const TS_TYPES_GENERATOR_OPTIMIZED_TOOL_DESCRIPTION = 'Generate TypeScript type definitions from Swagger/OpenAPI document with optimized options for caching and large document support.';
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. It mentions 'optimized options for caching and large document support', which hints at performance behaviors, but doesn't disclose critical traits like whether this is a read-only or mutation operation (e.g., file writing), error handling, rate limits, or authentication needs. For a tool with 17 parameters and no annotations, this is a significant gap in 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, well-structured sentence that efficiently conveys the core purpose and key differentiators ('optimized options for caching and large document support'). It is front-loaded with the main action and avoids unnecessary details, making it appropriately concise for the tool's complexity.

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 high parameter count (17), no annotations, and no output schema, the description is incomplete. It covers the basic purpose and hints at optimizations but lacks details on behavioral traits, output format, or error handling. The schema handles parameter documentation well, but the description doesn't compensate for the missing annotation and output context, making it only minimally adequate.

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?

Schema description coverage is 100%, so the schema already documents all 17 parameters thoroughly. The description adds no parameter-specific information beyond the general 'optimized options for caching and large document support', which loosely relates to parameters like 'useCache' and 'cacheTTLMinutes'. With high schema coverage, the baseline is 3, as the description provides minimal additional semantic value.

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: 'Generate TypeScript type definitions from Swagger/OpenAPI document' with the specific verb 'generate' and resource 'TypeScript type definitions'. It distinguishes from the sibling 'generate-typescript-types' by mentioning 'optimized options for caching and large document support', though it doesn't explicitly contrast with all siblings like 'generate-api-client'.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage context through 'optimized options for caching and large document support', suggesting this tool is preferred for performance or scalability needs. However, it lacks explicit guidance on when to use this versus alternatives like 'generate-typescript-types' (non-optimized) or 'generate-api-client', and doesn't mention prerequisites or exclusions.

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