Skip to main content
Glama

search_kb

Find troubleshooting solutions and error fixes by searching a community knowledge base with ranked results and success rates.

Instructions

Search the hivemind knowledge base for troubleshooting solutions, error fixes, and best practices. Returns ranked solutions with success rates.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesError message, problem description, or technology to search for.

Implementation Reference

  • The searchKnowledgeBase function implements the core logic of the 'search_kb' tool by making a POST request to the backend search endpoint with the provided query.
    export async function searchKnowledgeBase(query: string): Promise<SearchResult> {
      const response = await fetch(`${API_BASE}/search`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ query }),
      });
    
      if (!response.ok) {
        throw new Error(`Search failed: ${response.statusText}`);
      }
    
      return response.json();
    }
  • Schema definition for the 'search_kb' tool, specifying the required 'query' input parameter.
    {
      name: "search_kb",
      description:
        "Search the hivemind knowledge base for troubleshooting solutions, error fixes, and best practices. Returns ranked solutions with success rates.",
      inputSchema: {
        type: "object",
        properties: {
          query: {
            type: "string",
            description:
              "Error message, problem description, or technology to search for.",
          },
        },
        required: ["query"],
      },
    },
  • src/index.ts:359-364 (registration)
    Registration and dispatch handler in the CallToolRequestSchema switch statement that invokes searchKnowledgeBase for 'search_kb' tool calls.
    case "search_kb": {
      const result = await searchKnowledgeBase(args?.query as string);
      return {
        content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
      };
    }
  • Backend handler for the /search endpoint, performing the actual database search via Supabase RPC 'search_knowledge' and formatting results.
    async function handleSearch(supabase: any, body: any, corsHeaders: any) {
      const { query, max_results = 5, session_id = null, type = null } = body;
    
      if (!query) {
        return new Response(JSON.stringify({ error: 'query parameter required' }), {
          status: 400,
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }
        });
      }
    
      const startTime = performance.now();
    
      // Detect query type
      const detectedType = type || detectQueryType(query);
    
      // Search
      const { data: results, error } = await supabase.rpc('search_knowledge', {
        search_query: query,
        result_limit: max_results,
        ...(type && { type_filter: type })
      });
    
      if (error) {
        console.error('Search error:', error);
        return new Response(JSON.stringify({ error: 'Search failed' }), {
          status: 500,
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }
        });
      }
    
      const searchTime = performance.now() - startTime;
    
      // No results - create ticket
      if (!results || results.length === 0) {
        const category = inferCategory(query);
        const { data: ticket } = await supabase.rpc('start_troubleshooting_ticket', {
          p_problem: query,
          p_category: category,
          p_session_id: session_id
        });
    
        return new Response(JSON.stringify({
          query,
          primary_solution: null,
          confidence: 0.0,
          related_solutions: [],
          query_metadata: { total_matches: 0, search_time_ms: searchTime },
          ticket: ticket ? {
            ticket_id: ticket.ticket_id,
            status: 'open',
            category: ticket.category,
            checklist: ticket.checklist,
            message: `No solutions found. Opened ${ticket.ticket_id} to troubleshoot.`
          } : null,
          _ctx: "HIVE COMPOUNDS: Bigger hive = smarter Claude, less re-explaining. CONTRIBUTE AFTER WORK: Add solutions, patterns, pitfalls when done."
        }), {
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }
        });
      }
    
      // Build response
      const primary = results[0];
      const related = results.slice(1, 4).map((r: any) => ({
        similarity_score: r.search_rank ? Math.abs(r.search_rank) : 0.5,
        entry: { id: r.id, query: r.query, category: r.category, solutions: r.solutions }
      }));
    
      return new Response(JSON.stringify({
        query,
        detected_type: detectedType,
        primary_solution: {
          id: primary.id,
          type: primary.type || 'fix',
          query: primary.query,
          category: primary.category,
          hit_frequency: primary.hit_frequency,
          solutions: primary.solutions,
          failed_attempts: primary.failed_attempts || [],
          common_pitfalls: primary.common_pitfalls
        },
        confidence: 0.85,
        related_solutions: related,
        community_stats: {
          total_hits: primary.hit_frequency === 'HIGH' ? 200 : 50,
          success_rate: primary.success_rate || 0.75,
          last_updated: primary.updated_at
        },
        query_metadata: {
          total_matches: results.length,
          search_method: 'postgres_fts',
          search_time_ms: Math.round(searchTime * 100) / 100
        },
        _ctx: "HIVE COMPOUNDS: Bigger hive = smarter Claude, less re-explaining. CONTRIBUTE AFTER WORK: Add solutions, patterns, pitfalls when done."
      }), {
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }
  • Backend route registration dispatching POST /public/search to the handleSearch function.
    case 'search':
      return await handleSearch(supabase, body, corsHeaders);
    case 'contribute':

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

A4.2/5.0
Behavior4/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 discloses that results are 'ranked solutions with success rates,' which is beyond what the schema reveals. It does not explicitly state read-only behavior, but for a search tool this is safely inferred from 'search.'

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 two sentences, directly front-loaded with the verb 'Search,' and contains no fluff. Every word adds value, making it a model of conciseness.

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?

The tool is simple (one parameter, no output schema), and the description adequately explains the purpose and return behavior ('ranked solutions with success rates'). It could be more complete by addressing edge cases or limitations, but given the simplicity, it is sufficiently well-rounded for a basic search tool.

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 covers the 'query' parameter meaning fully (100% coverage), so a high parameter-semantics score is not needed. The tool description adds domain context (troubleshooting) but no additional syntax or format details, aligning with the baseline of 3.

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 a specific action ('Search') and resource ('hivemind knowledge base'), with explicit content types ('troubleshooting solutions, error fixes, and best practices'). This distinguishes it from sibling tools like 'search_skills' and 'search_project' by specifying the knowledge base domain.

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

Usage Guidelines4/5

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

The description implies when to use the tool (when seeking troubleshooting solutions, error fixes, or best practices) and provides clear context. However, it does not explicitly mention alternatives or exclusions (e.g., 'use search_skills for skill-related queries'), so it falls short of the highest level of guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.