Skip to main content
Glama
mukiwu
by mukiwu

search_mdn

Search MDN Web Docs for API documentation, usage examples, deprecation status, and browser compatibility information to support JavaScript/TypeScript development.

Instructions

搜尋 MDN Web Docs 文件,取得最新的 API 資訊、用法說明、棄用狀態和瀏覽器相容性

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes搜尋關鍵字,如 "fetch", "Promise", "Array.prototype.includes"
limitNo返回結果數量 (預設: 5)
localeNo語言 (預設: en-US,可用: zh-TW, zh-CN)en-US

Implementation Reference

  • The primary handler function for executing the 'search_mdn' tool. It validates input arguments (query, limit, locale), instantiates MDNService with the specified locale, calls mdnService.search(), processes results including fetching detailed info for the top result, formats a markdown report with summaries, compatibility, etc., and returns the content.
    private async handleMDNSearch(args: unknown) {
      try {
        if (!args || typeof args !== 'object') {
          throw new ValidationError('參數格式錯誤');
        }
    
        const { query, limit = 5, locale = 'en-US' } = args as Record<string, unknown>;
    
        if (typeof query !== 'string' || !query.trim()) {
          throw new ValidationError('query 為必填欄位,請提供搜尋關鍵字');
        }
    
        // 建立服務實例(支援不同語言)
        const mdnService = new MDNService(locale as string);
    
        // 搜尋 MDN
        const searchResults = await mdnService.search(query, limit as number);
    
        if (searchResults.length === 0) {
          return {
            content: [{
              type: 'text',
              text: `🔍 MDN 搜尋結果\n\n找不到與 "${query}" 相關的文件。\n\n建議:\n- 嘗試使用英文關鍵字\n- 使用更具體的 API 名稱(如 "Array.prototype.map")`
            }]
          };
        }
    
        // 格式化結果
        let report = `# 🔍 MDN 搜尋結果: "${query}"\n\n`;
        report += `找到 ${searchResults.length} 個相關文件:\n\n`;
    
        for (const result of searchResults) {
          report += `## ${result.title}\n`;
          report += `📖 ${result.summary}\n`;
          report += `🔗 ${result.url}\n\n`;
        }
    
        // 嘗試取得第一個結果的詳細資訊
        if (searchResults.length > 0) {
          const detailed = await mdnService.getAPIInfo(searchResults[0].slug);
    
          if (detailed) {
            report += `---\n\n## 📋 詳細資訊: ${detailed.title}\n\n`;
    
            if (detailed.deprecated) {
              report += `⚠️ **此 API 已被棄用**\n\n`;
            }
    
            if (detailed.experimental) {
              report += `🧪 **此 API 為實驗性功能**\n\n`;
            }
    
            if (detailed.summary) {
              report += `### 說明\n${detailed.summary}\n\n`;
            }
    
            if (detailed.syntax) {
              report += `### 語法\n\`\`\`javascript\n${detailed.syntax}\n\`\`\`\n\n`;
            }
    
            if (detailed.browserCompat) {
              report += `### 瀏覽器相容性\n`;
              const compat = detailed.browserCompat;
              if (compat.chrome) report += `- Chrome: ${compat.chrome}\n`;
              if (compat.firefox) report += `- Firefox: ${compat.firefox}\n`;
              if (compat.safari) report += `- Safari: ${compat.safari}\n`;
              if (compat.edge) report += `- Edge: ${compat.edge}\n`;
              if (compat.nodejs) report += `- Node.js: ${compat.nodejs}\n`;
              report += '\n';
            }
    
            report += `🔗 完整文件: ${detailed.url}\n`;
          }
        }
    
        return {
          content: [{
            type: 'text',
            text: report
          }]
        };
    
      } catch (error) {
        const errorMessage = error instanceof ValidationError
          ? `參數驗證失敗: ${error.message}`
          : `MDN 搜尋失敗: ${error instanceof Error ? error.message : String(error)}`;
    
        return {
          content: [{ type: 'text', text: errorMessage }],
          isError: true,
        };
      }
    }
  • src/server.ts:195-217 (registration)
    Tool registration in the ListToolsRequestSchema handler, defining the name, description, and input schema for 'search_mdn'.
    {
      name: 'search_mdn',
      description: '搜尋 MDN Web Docs 文件,取得最新的 API 資訊、用法說明、棄用狀態和瀏覽器相容性',
      inputSchema: {
        type: 'object',
        properties: {
          query: {
            type: 'string',
            description: '搜尋關鍵字,如 "fetch", "Promise", "Array.prototype.includes"',
          },
          limit: {
            type: 'number',
            description: '返回結果數量 (預設: 5)',
            default: 5
          },
          locale: {
            type: 'string',
            description: '語言 (預設: en-US,可用: zh-TW, zh-CN)',
            default: 'en-US'
          }
        },
        required: ['query'],
      },
  • Input schema definition for the search_mdn tool, specifying parameters: query (required string), limit (number, default 5), locale (string, default 'en-US').
    inputSchema: {
      type: 'object',
      properties: {
        query: {
          type: 'string',
          description: '搜尋關鍵字,如 "fetch", "Promise", "Array.prototype.includes"',
        },
        limit: {
          type: 'number',
          description: '返回結果數量 (預設: 5)',
          default: 5
        },
        locale: {
          type: 'string',
          description: '語言 (預設: en-US,可用: zh-TW, zh-CN)',
          default: 'en-US'
        }
      },
      required: ['query'],
    },
  • Core search functionality in MDNService class that queries the MDN API (/api/v1/search), parses results into MDNSearchResult objects with title, slug, summary, URL, etc.
    async search(query: string, limit: number = 10): Promise<MDNSearchResult[]> {
      try {
        const url = `${this.apiUrl}/search?q=${encodeURIComponent(query)}&locale=${this.locale}&size=${limit}`;
    
        const response = await fetch(url, {
          headers: {
            'Accept': 'application/json',
            'User-Agent': 'DevAdvisor-MCP/1.0'
          }
        });
    
        if (!response.ok) {
          throw new Error(`MDN API 回應錯誤: ${response.status}`);
        }
    
        const data = await response.json();
    
        return (data.documents || []).map((doc: any) => ({
          title: doc.title,
          slug: doc.slug,
          locale: doc.locale,
          summary: doc.summary || '',
          url: `${this.baseUrl}/${doc.locale}/docs/${doc.slug}`,
          score: doc.score || 0,
          highlight: doc.highlight
        }));
      } catch (error) {
        console.error('MDN 搜尋失敗:', error);
        return [];
      }
    }
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 what information is retrieved (API info, usage, deprecation, compatibility) but lacks details on behavioral traits like rate limits, authentication needs, response format, or error handling. This is a significant gap for a tool with no annotation coverage.

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, efficient sentence that front-loads the core purpose without unnecessary words. It clearly communicates the tool's function and the types of information retrieved, making it appropriately sized and well-structured.

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 lack of annotations and output schema, the description is incomplete. It doesn't explain the return values, error conditions, or behavioral constraints, which are crucial for a search tool. While the purpose is clear, the description fails to provide enough context for effective tool invocation.

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 schema description coverage is 100%, so the schema already documents all parameters (query, limit, locale) with their descriptions and defaults. The description adds no additional meaning beyond what the schema provides, such as examples of query usage or locale implications, resulting in a baseline score of 3.

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: searching MDN Web Docs to obtain API information, usage instructions, deprecation status, and browser compatibility. It specifies the resource (MDN Web Docs) and the types of information retrieved, though it doesn't explicitly differentiate from sibling tools like 'analyze_compatibility' or 'check_browser_support'.

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 sibling tools or contexts where other tools might be more appropriate, such as using 'analyze_compatibility' for deeper compatibility analysis or 'list_api_categories' for browsing categories instead of searching.

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