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

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

With no annotations provided, the description carries full burden and does well by disclosing key behavioral traits: it returns URLs rather than actual content, requires a secondary tool (WebFetch) for full functionality, and implies this is a search/read operation. It doesn't mention rate limits, authentication needs, or error handling, but provides sufficient context for basic usage.

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 and front-loaded: two sentences that each earn their place. The first establishes purpose, the second provides critical usage guidance. No wasted words, with emoji and formatting that enhance readability without adding fluff.

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

Completeness4/5

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

Given the tool's moderate complexity (search with 3 parameters), no annotations, and no output schema, the description does well by explaining the critical behavioral aspect (returns URLs requiring WebFetch). It could be more complete by mentioning what the URL output format looks like or error scenarios, but covers the essential workflow adequately.

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?

With 100% schema description coverage, the baseline is 3. The description adds no additional parameter information beyond what's already in the schema (query, tags, sort parameters are fully documented in schema). The description focuses on the tool's behavioral output rather than parameter semantics.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/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 with specific verb ('搜索' meaning 'search') and resource ('StackOverflow'), explicitly distinguishing it from sibling tools by naming the specific platform. It provides both Chinese and English context ('StackOverflow搜索 - 搜索技术问题和解决方案') which enhances clarity.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit guidance on when to use this tool versus alternatives: it specifies that this tool returns StackOverflow search URLs and that Claude Code should use WebFetch to access the actual results. This creates a clear workflow distinction from other search tools in the sibling list.

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

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