Skip to main content
Glama

ai_search_stackoverflow

Search StackOverflow for technical questions and solutions. Returns search URLs to access programming answers through web fetching.

Instructions

💬 StackOverflow搜索 - 搜索技术问题和解决方案

【重要】此工具会返回StackOverflow搜索URL,Claude Code应该使用WebFetch工具访问该URL以获取真实搜索结果。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes搜索关键词或问题描述
tagsNo标签筛选(如:javascript,react)
sortNo排序方式,默认relevancerelevance

Implementation Reference

  • The handler for 'ai_search_stackoverflow' tool. Parses input arguments (query, tags, sort), constructs StackOverflow search URL, generates detailed markdown with search tips and WebFetch instructions, saves to file, and returns formatted text response.
    case 'ai_search_stackoverflow': {
      const rawQuery = normalizeString(args.query);
      const tagsInput = normalizeString(args.tags);
      const requestedSort = normalizeString(args.sort).toLowerCase();
    
      if (!rawQuery) {
        throw new Error('搜索关键词不能为空');
      }
    
      const sortNames = {
        relevance: '相关性',
        votes: '投票数',
        creation: '创建时间',
        activity: '活跃度'
      };
    
      const sortKey = pickKey(sortNames, requestedSort, 'relevance');
    
      let searchQuery = rawQuery;
      let tagList = [];
      if (tagsInput) {
        tagList = tagsInput
          .split(',')
          .map((t) => normalizeString(t))
          .filter(Boolean);
        if (tagList.length > 0) {
          searchQuery += ` ${tagList.map(t => `[${t}]`).join(' ')}`;
        }
      }
    
      const searchUrl = `https://stackoverflow.com/search?q=${encodeURIComponent(searchQuery)}&sort=${sortKey}`;
      const tagsDisplay = tagList.length > 0 ? tagList.join(', ') : '无';
    
      // StackOverflow 搜索技巧
      const tips = [
        `标签搜索: [javascript] ${rawQuery}`,
        `已回答问题: ${rawQuery} is:answer`,
        `已接受答案: ${rawQuery} isaccepted:yes`,
        `投票数筛选: ${rawQuery} score:5..`,
        `多个标签: [react] [hooks] ${rawQuery}`,
        `代码搜索: code:"${rawQuery}"`,
        `标题搜索: title:"${rawQuery}"`
      ];
    
      // 热门技术标签推荐
      const popularTags = [
        'javascript', 'python', 'java', 'react', 'node.js',
        'typescript', 'html', 'css', 'sql', 'docker'
      ];
    
      const detailsContent = `💬 StackOverflow 搜索\n\n` +
        `**搜索关键词**: ${rawQuery}\n` +
        `**标签筛选**: ${tagsDisplay}\n` +
        `**排序方式**: ${sortNames[sortKey]}\n\n` +
        `---\n\n` +
        `🔗 **搜索链接**: ${searchUrl}\n\n` +
        `⚠️ **请使用 WebFetch 工具获取搜索结果**:\n` +
        `\`\`\`javascript\n` +
        `WebFetch({\n` +
        `  url: "${searchUrl}",\n` +
        `  prompt: "提取前10个问题的标题、投票数、回答数、是否已解决和链接"\n` +
        `})\n` +
        `\`\`\`\n\n` +
        `---\n\n` +
        `💡 **高级搜索技巧**:\n` +
        tips.map(tip => `• ${tip}`).join('\n') +
        `\n\n🏷️ **热门技术标签**:\n` +
        popularTags.map(tag => `• [${tag}]`).join(' ') +
        `\n\n📊 **其他排序方式**:\n` +
        Object.keys(sortNames)
          .filter(s => s !== sortKey)
          .map((s) =>
            `• ${sortNames[s]}: https://stackoverflow.com/search?q=${encodeURIComponent(searchQuery)}&sort=${s}`
          )
          .join('\n');
    
      const filepath = await saveSearchResult('stackoverflow-search', rawQuery, detailsContent);
    
      return makeTextResponse(
        `💬 **StackOverflow搜索**\n\n` +
        `**关键词**: ${rawQuery}\n` +
        `**搜索链接**: ${searchUrl}\n\n` +
        `✅ 详细信息已保存至: ${filepath || '保存失败'}\n` +
        `💡 使用 WebFetch 工具访问搜索链接获取结果`
      );
    }
  • The tool definition including name, description, and input schema for 'ai_search_stackoverflow'.
    {
      name: 'ai_search_stackoverflow',
      description: '💬 StackOverflow搜索 - 搜索技术问题和解决方案\n\n【重要】此工具会返回StackOverflow搜索URL,Claude Code应该使用WebFetch工具访问该URL以获取真实搜索结果。',
      inputSchema: {
        type: 'object',
        properties: {
          query: { type: 'string', description: '搜索关键词或问题描述' },
          tags: { type: 'string', description: '标签筛选(如:javascript,react)' },
          sort: { type: 'string', enum: ['relevance', 'votes', 'creation', 'activity'], description: '排序方式,默认relevance', default: 'relevance' }
        },
        required: ['query']
      }
    },
  • Registration of all tools (including ai_search_stackoverflow) for the ListToolsRequestHandler.
    server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: AI_TOOLS,
    }));
  • Helper function used by the handler to save detailed search results to a markdown file.
    const saveSearchResult = async (toolName, query, details) => {
      try {
        const resultsDir = join(process.cwd(), '.search-results');
        if (!existsSync(resultsDir)) {
          await mkdir(resultsDir, { recursive: true });
        }
    
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
        const filename = `${toolName}-${timestamp}.md`;
        const filepath = join(resultsDir, filename);
    
        await writeFile(filepath, details, 'utf-8');
        return filepath;
      } catch (error) {
        console.error('Failed to save search result:', error);
        return null;
      }
    };
  • Helper function used to normalize string inputs by trimming whitespace.
    const normalizeString = (value) => (typeof value === 'string' ? value.trim() : '');
  • Helper function used to safely pick a key from a map with fallback, used for resolving sort option.
    const pickKey = (map, key, fallback) => {
      if (key && Object.prototype.hasOwnProperty.call(map, key)) {
        return key;
      }
      return fallback;
    };

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/adminhuan/smart-search-mcp'

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