Skip to main content
Glama
mukiwu
by mukiwu

analyze_compatibility

Analyze JavaScript/TypeScript project API compatibility risks and recommend polyfill solutions for target browsers.

Instructions

分析專案的 API 相容性風險,推薦 polyfill 方案

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
projectPathYes專案目錄路徑
browserslistConfigNobrowserslist 配置字串或檔案路徑
reportFormatNo報告格式markdown

Implementation Reference

  • src/server.ts:172-193 (registration)
    Tool registration including name, description, and input schema definition in the list of tools.
    name: 'analyze_compatibility',
    description: '分析專案的 API 相容性風險,推薦 polyfill 方案',
    inputSchema: {
      type: 'object',
      properties: {
        projectPath: {
          type: 'string',
          description: '專案目錄路徑',
        },
        browserslistConfig: {
          type: 'string',
          description: 'browserslist 配置字串或檔案路徑',
        },
        reportFormat: {
          type: 'string',
          description: '報告格式',
          enum: ['json', 'markdown', 'html'],
          default: 'markdown'
        }
      },
      required: ['projectPath'],
    },
  • Primary handler function for executing the analyze_compatibility tool: validates arguments, invokes CompatibilityAnalyzer.analyze(), formats the report, and returns the result.
    private async handleCompatibilityAnalysis(args: unknown) {
      try {
        const validatedArgs = this.validateCompatibilityArgs(args);
        const {
          projectPath,
          browserslistConfig,
          reportFormat = 'markdown'
        } = validatedArgs;
    
        // 預設的檔案模式
        const includePatterns = ['**/*.js', '**/*.ts', '**/*.jsx', '**/*.tsx'];
        const excludePatterns = ['node_modules/**', 'dist/**', 'build/**'];
    
        // 執行相容性分析
        const analysis = await this.compatibilityAnalyzer.analyze(
          projectPath,
          includePatterns,
          excludePatterns,
          browserslistConfig
        );
    
        // 格式化報告
        const report = formatCompatibilityReport(analysis, reportFormat);
    
        return {
          content: [
            {
              type: 'text',
              text: report,
            },
          ],
        };
      } catch (error) {
        const errorMessage = error instanceof ValidationError
          ? `參數驗證失敗: ${error.message}`
          : `分析失敗: ${error instanceof Error ? error.message : String(error)}`;
    
        return {
          content: [{ type: 'text', text: errorMessage }],
          isError: true,
        };
      }
  • Core analysis logic in CompatibilityAnalyzer.analyze(): parses browserslist, scans project for API usage, checks compatibility using CanIUseService, generates report with issues and polyfill recommendations.
    async analyze(
      projectPath: string,
      includePatterns: string[],
      excludePatterns: string[],
      browserslistConfig?: string
    ): Promise<CompatibilityAnalysis> {
      // 1. 解析 browserslist 配置,取得目標瀏覽器
      const { targetBrowsers, query } = this.parseBrowserslistConfig(
        projectPath,
        browserslistConfig
      );
    
      // 2. 解析專案程式碼
      const parsedFiles = await this.parser.parseProject(
        projectPath,
        includePatterns,
        excludePatterns
      );
    
      // 3. 收集所有使用的 API
      const apiUsageMap = this.collectApiUsage(parsedFiles);
    
      // 4. 轉換目標瀏覽器為 CanIUse 格式
      const browserVersions = this.convertBrowserVersions(targetBrowsers);
    
      // 5. 檢查每個 API 的相容性
      const issues: CompatibilityIssue[] = [];
      const fileAnalysis: FileCompatibilityResult[] = [];
    
      for (const [api, locations] of apiUsageMap.entries()) {
        const caniuseId = this.getCaniuseId(api);
        if (!caniuseId) continue;
    
        try {
          const compatibility = await this.canIUseService.checkCompatibility(
            caniuseId,
            browserVersions
          );
    
          if (compatibility.notSupported.length > 0 || compatibility.partialSupport.length > 0) {
            const issue = this.createIssue(api, caniuseId, locations, compatibility);
            issues.push(issue);
          }
        } catch (error) {
          // 忽略無法查詢的 API
          console.warn(`無法查詢 ${api} 的相容性:`, error);
        }
      }
    
      // 6. 按檔案分組問題
      for (const file of parsedFiles) {
        const fileIssues = issues.filter(issue =>
          issue.locations.some(loc => loc.file === file.filePath)
        );
        
        const apisUsed = Array.from(
          new Set(file.apiCalls.map(call => call.method ? `${call.api}.${call.method}` : call.api))
        );
    
        fileAnalysis.push({
          filePath: file.filePath,
          apisUsed,
          issues: fileIssues
        });
      }
    
      // 7. 生成 Polyfill 建議
      const polyfillRecommendations = this.generatePolyfillRecommendations(issues);
    
      // 8. 計算摘要
      const summary = this.generateSummary(apiUsageMap.size, issues);
    
      return {
        summary,
        targetBrowsers,
        browserslistQuery: query,
        issues,
        polyfillRecommendations,
        fileAnalysis
      };
    }
  • Input schema validation for tool parameters: projectPath (required), browserslistConfig, reportFormat.
    inputSchema: {
      type: 'object',
      properties: {
        projectPath: {
          type: 'string',
          description: '專案目錄路徑',
        },
        browserslistConfig: {
          type: 'string',
          description: 'browserslist 配置字串或檔案路徑',
        },
        reportFormat: {
          type: 'string',
          description: '報告格式',
          enum: ['json', 'markdown', 'html'],
          default: 'markdown'
        }
      },
      required: ['projectPath'],
    },
  • Helper function to format the compatibility analysis results into different report formats (markdown, json, html). Called by the main handler.
    export function formatCompatibilityReport(
      analysis: CompatibilityAnalysis,
      format: ReportFormat = 'markdown'
    ): string {
      switch (format) {
        case 'json':
          return JSON.stringify(analysis, null, 2);
        case 'html':
          return formatAsHtml(analysis);
        case 'text':
          return formatAsText(analysis);
        case 'markdown':
        default:
          return formatAsMarkdown(analysis);
      }
    }

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/mukiwu/dev-advisor-mcp'

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