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 [];
      }
    }

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