Skip to main content
Glama

search_code

Search indexed codebases using semantic queries to find relevant code snippets and project files. Filter results by specific project paths for targeted retrieval.

Instructions

Recherche sémantique dans le code indexé avec options RAG

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesRequête de recherche sémantique
project_filterNoFiltrer par chemin de projet spécifique

Implementation Reference

  • Main handler function executing the search_code tool logic: validates query, loads RAG configuration, sets embedding provider, performs semantic search, and formats output.
    export const searchCodeHandler = async (args) => {
        if (!args.query || typeof args.query !== 'string') {
            throw new Error("The 'query' parameter is required and must be a string");
        }
        // Charger la configuration
        const configManager = getRagConfigManager();
        const defaults = configManager.getDefaults();
        const searchDefaults = configManager.getSearchDefaults();
        // Utiliser uniquement les valeurs par défaut de la configuration
        const embedding_provider = defaults.embedding_provider;
        const embedding_model = defaults.embedding_model;
        const limit = configManager.applyLimits('search_limit', searchDefaults.limit);
        const threshold = configManager.applyLimits('search_threshold', searchDefaults.threshold);
        const format_output = searchDefaults.format;
        // Configurer le fournisseur d'embeddings
        setEmbeddingProvider(embedding_provider, embedding_model);
        const options = {
            projectFilter: args.project_filter,
            limit: limit,
            threshold: threshold
        };
        try {
            const searchResult = await searchCode(args.query, options);
            // Formater la sortie si demandé
            if (format_output !== false) {
                const formatted = `Recherche RAG: "${args.query}"\n` +
                    `Configuration: provider=${embedding_provider}, model=${embedding_model}\n` +
                    `Résultats: ${searchResult.totalResults}\n` +
                    `Temps d'exécution: ${searchResult.stats?.executionTime || 0}ms\n` +
                    `Projets scannés: ${searchResult.stats?.projectsScanned || 0}\n` +
                    `Limite: ${limit}, Seuil: ${threshold}\n\n` +
                    searchResult.results.map((r, i) => `${i + 1}. ${r.filePath} (score: ${(r.score * 100).toFixed(2)}%)\n` +
                        `   Projet: ${r.metadata.projectPath}\n` +
                        `   Contenu: ${r.content.substring(0, 100)}...`).join('\n\n');
                return { content: [{ type: "text", text: formatted }] };
            }
            return {
                content: [{
                        type: "text",
                        text: JSON.stringify({
                            ...searchResult,
                            config_used: {
                                embedding_provider,
                                embedding_model,
                                limit,
                                threshold,
                                format_output
                            }
                        }, null, 2)
                    }]
            };
        }
        catch (error) {
            console.error("Error in search_code tool:", error);
            throw error;
        }
    };
  • Tool definition including name, description, and input schema for search_code.
    export const searchCodeTool = {
        name: "search_code",
        description: "Recherche sémantique dans le code indexé avec options RAG",
        inputSchema: {
            type: "object",
            properties: {
                query: {
                    type: "string",
                    description: "Requête de recherche sémantique"
                },
                project_filter: {
                    type: "string",
                    description: "Filtrer par chemin de projet spécifique"
                }
            },
            required: ["query"]
        },
    };
  • getExpectedTools function lists 'search_code' among expected auto-registered RAG tools.
    export function getExpectedTools() {
        return [
            // Outils Graph (9 outils)
            'create_entities',
            'create_relations',
            'add_observations',
            'delete_entities',
            'delete_observations',
            'delete_relations',
            'read_graph',
            'search_nodes',
            'open_nodes',
            // Outils RAG (5 outils - avec injection_rag comme outil principal)
            'injection_rag', // Nouvel outil principal
            'index_project', // Alias déprécié (rétrocompatibilité)
            'search_code',
            'manage_projects',
            'update_project'
        ];
  • Core helper function searchCode that performs the semantic search via vector store and structures the results with stats.
    export async function searchCode(query, options = {}) {
        const startTime = Date.now();
        try {
            const results = await semanticSearch(query, options);
            const endTime = Date.now();
            // Compter les projets uniques dans les résultats
            const uniqueProjects = new Set(results.map(r => r.metadata.projectPath));
            return {
                query,
                results,
                totalResults: results.length,
                stats: {
                    executionTime: endTime - startTime,
                    projectsScanned: uniqueProjects.size,
                },
            };
        }
        catch (error) {
            console.error("Error in searchCode:", 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 'semantic search' and 'RAG options' but doesn't disclose critical behavioral traits: whether this is read-only or has side effects, what the output format looks like, if there are rate limits, authentication needs, or how results are returned (e.g., pagination). The description is too vague to inform safe and effective use.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence in French that directly states the tool's purpose. It's appropriately sized and front-loaded with key information. However, it could be slightly more structured by separating the core function from the RAG feature.

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 search tool with RAG options, no annotations, and no output schema, the description is incomplete. It lacks details on behavioral traits, output format, and usage guidelines. For a tool that likely returns complex results, more context is needed to ensure the agent can interpret and use it correctly.

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 'project_filter') with descriptions. The tool description adds no additional meaning beyond what's in the schema—it doesn't explain parameter interactions, default behaviors, or examples. Baseline 3 is appropriate when schema does the heavy lifting.

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

Purpose4/5

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

The description clearly states the tool performs 'semantic search in indexed code with RAG options', which specifies the verb (search), resource (indexed code), and method (semantic with RAG). It distinguishes from siblings like 'search_nodes' by focusing on code rather than general nodes. However, it doesn't explicitly differentiate from other search tools beyond the resource type.

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?

The description provides no guidance on when to use this tool versus alternatives like 'search_nodes' or 'injection_rag'. It mentions RAG options but doesn't explain when semantic search with RAG is preferred over other methods. No exclusions, prerequisites, or contextual advice are given.

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/ali-48/rag-mcp-server'

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