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);
      }
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions analysis and recommendations but doesn't describe what the tool actually does (e.g., scans code, generates reports, requires internet access) or any behavioral traits like performance impact, error handling, or output format details. This leaves significant gaps in understanding the tool's operation.

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 in Chinese that directly states the tool's function without any fluff. It's front-loaded and wastes no words, making it efficient for quick understanding.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (analyzing API compatibility with 3 parameters) and lack of annotations and output schema, the description is insufficient. It doesn't explain what the analysis entails, what the recommendations include, or how results are returned, leaving the agent with incomplete information for effective use.

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, clearly documenting all three parameters. The description adds no additional semantic context beyond what's in the schema, such as explaining how 'projectPath' is used or what 'browserslistConfig' entails. Baseline 3 is appropriate since the schema does the heavy lifting.

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: analyzing API compatibility risks and recommending polyfill solutions for a project. It specifies the verb 'analyze' and the resource 'API compatibility risks,' but doesn't explicitly differentiate from sibling tools like 'analyze_modernization' or 'check_browser_support,' which might have overlapping functionality.

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. It doesn't mention any prerequisites, exclusions, or comparisons with sibling tools such as 'check_browser_support' or 'recommend_api_combination,' leaving the agent to infer usage context.

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

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