Skip to main content
Glama

rag_search

Search your personal document corpus to find relevant information from notes, files, and web content for developer operational tasks.

Instructions

Поиск по личному корпусу документов

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesПоисковый запрос
limitNoМаксимальное количество результатов

Implementation Reference

  • Primary handler for rag_search tool: orchestrates the search using SQLiteClient.search with query and limit parameters.
    async search(query: string, limit: number = 5): Promise<SearchResult[]> {
      try {
        console.log(`🔍 Поиск: "${query}" (лимит: ${limit})`);
        
        // Получаем SQLiteClient из пула соединений
        const sqliteClient = await this.connectionPool.getSQLiteClient();
        
        // Выполняем поиск через SQLite
        const results = await sqliteClient.search(query, { limit });
        
        if (results.isErr()) {
          throw new Error(`Ошибка поиска: ${results.error.message}`);
        }
        
        console.log(`✅ Найдено результатов: ${results.value.length}`);
        return results.value;
      } catch (error) {
        console.error('Ошибка поиска:', error);
        throw new Error(`Ошибка поиска: ${error}`);
      }
    }
  • Core RAG search implementation using SQLite FTS5 full-text search with keyword fallback, snippets, and highlights.
    async search(query: string, options: SearchOptions = {}): Promise<Result<SearchResult[], SQLiteError>> {
      const {
        limit = 10,
        offset = 0,
        includeSnippets = true,
        highlightTerms = true,
        minScore = 0.1
      } = options;
    
      try {
        // Try FTS search first
        let results = await this.performFTSSearch(query, limit, offset);
        
        if (results.length === 0) {
          // Fallback to simple search
          results = await this.performSimpleSearch(query, limit, offset);
        }
        
        // Filter by minimum score
        const filteredResults = results.filter(r => r.score >= minScore);
        
        // Add snippets and highlights if requested
        if (includeSnippets || highlightTerms) {
          filteredResults.forEach(result => {
            if (includeSnippets) {
              result.snippet = this.generateSnippet(result.text, query, 200);
            }
            if (highlightTerms) {
              result.highlights = this.extractHighlights(result.text, query);
            }
          });
        }
        
        this.metrics.recordOperation('search');
        this.logger.info('Search completed', { query, resultsCount: filteredResults.length });
        
        return ok(filteredResults);
      } catch (error) {
        this.metrics.recordError('search');
        return err(new SQLiteError(
          `Search failed: ${error instanceof Error ? error.message : String(error)}`,
          'SEARCH_ERROR',
          undefined,
          error instanceof Error ? error : undefined
        ));
      }
    }
  • MCP server tool call dispatcher: handles 'rag_search' by invoking RAGService.search.
    case 'rag_search':
      return {
        content: await this.ragService.search(args.query as string, (args.limit as number) || 5)
      };
  • Input schema definition for rag_search tool in MCP ListTools response.
    name: 'rag_search',
    description: 'Поиск по личному корпусу документов',
    inputSchema: {
      type: 'object',
      properties: {
        query: {
          type: 'string',
          description: 'Поисковый запрос',
        },
        limit: {
          type: 'number',
          description: 'Максимальное количество результатов',
          default: 5,
        },
      },
      required: ['query'],
    },
  • src/server.ts:178-227 (registration)
    Registration of CallToolRequestSchema handler including rag_search case in main MCP server.
    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      const { name, arguments: args } = request.params;
    
      if (!args) {
        throw new Error('Аргументы не предоставлены');
      }
    
      try {
        switch (name) {
          case 'rag_search':
            return {
              content: await this.ragService.search(args.query as string, (args.limit as number) || 5)
            };
    
          case 'rag_add_document':
            await this.ragService.addDocument(args.uri as string, args.content as string, args.title as string);
            return { content: 'Документ добавлен' };
    
          case 'file_read':
            return {
              content: await this.fileService.readFile(args.path as string)
            };
    
          case 'file_write':
            await this.fileService.writeFile(args.path as string, args.content as string);
            return { content: 'Файл записан' };
    
          case 'web_fetch':
            return {
              content: await this.webService.fetchPage(args.url as string)
            };
    
          case 'task_create':
            return {
              content: await this.taskService.createTask(args.title as string, args.project as string, args.due as string)
            };
    
          case 'task_list':
            return {
              content: await this.taskService.listTasks(args.project as string, args.status as string)
            };
    
          default:
            throw new Error(`Неизвестный инструмент: ${name}`);
        }
      } catch (error) {
        console.error(`Ошибка выполнения инструмента ${name}:`, error);
        throw error;
      }
    });
Behavior2/5

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

No annotations are provided, so the description carries full burden. It mentions 'поиск' (search) which implies read-only behavior, but doesn't disclose any behavioral traits like whether it performs semantic/vector search, how results are ranked, if there are rate limits, authentication requirements, or what the return format looks like. The description adds minimal value beyond the basic action.

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 phrase in Russian that directly states the tool's function. It's appropriately sized and front-loaded with zero wasted words, making it easy to parse quickly.

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 complexity of a RAG search tool (which typically involves semantic retrieval and possibly generation), no annotations, no output schema, and sibling tools that might overlap (like web_fetch), the description is insufficient. It doesn't explain what 'личный корпус документов' (personal document corpus) entails, how documents are indexed, or what the search returns, leaving significant gaps for an AI agent.

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?

Schema description coverage is 100%, so the schema already documents both parameters (query and limit) adequately. The description doesn't add any meaning beyond what the schema provides (e.g., it doesn't explain what type of queries work best, what the limit applies to, or format expectations). Baseline 3 is appropriate when the schema does the heavy lifting.

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

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description 'Поиск по личному корпусу документов' (Search through personal document corpus) states the general purpose (searching documents) but is vague about the specific mechanism (RAG-based search). It distinguishes from obvious non-search siblings like file_write or task_create, but doesn't clearly differentiate from potential search alternatives like web_fetch.

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?

No guidance is provided about when to use this tool versus alternatives. The description doesn't mention when this tool is appropriate (e.g., for semantic search over personal documents) or when other tools might be better (e.g., file_read for direct file access, web_fetch for web content).

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/Galiusbro/MCP'

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