Skip to main content
Glama

injection_rag

Analyzes entire code projects and automatically prepares and injects data for RAG systems by processing source files and integrating with knowledge graphs.

Instructions

Analyse du projet complet + prépare et injecte les données automatiquement (Phase 0 → RAG)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
project_pathYesChemin absolu vers le projet à analyser et injecter
file_patternsNoPatterns de fichiers à inclure (ex: ['**/*.py', '**/*.js'])
recursiveNoParcourir les sous-dossiers récursivement
log_levelNoNiveau de logs (INFO, DEBUG, ERROR)INFO
enable_graph_integrationNoActiver l'intégration automatique avec le graphe de connaissances

Implementation Reference

  • Main execution handler for 'injection_rag' tool. Performs permission checks (Phase 0), graph integration (Phase 1), loads RAG config, sets embedding provider, and indexes the project (Phase 2) using indexProject.
    export const injectionRagHandler = async (args) => {
        const logger = InjectionLogger.getInstance();
        if (!args.project_path || typeof args.project_path !== 'string') {
            const error = "Le paramètre 'project_path' est requis et doit être une chaîne de caractères";
            logger.error(error);
            throw new Error(error);
        }
        // Configurer le niveau de logs
        const logLevel = args.log_level || LogLevel.INFO;
        logger.setLogLevel(logLevel);
        logger.info("🚀 Démarrage de l'injection RAG", {
            version: "v1.0.0",
            project_path: args.project_path,
            log_level: logLevel
        });
        // Phase 0 : Vérification des permissions
        logger.info("🔍 Phase 0 - Vérification des permissions et sécurité");
        try {
            const fs = await import('fs');
            const path = await import('path');
            // Vérifier que le chemin existe
            if (!fs.existsSync(args.project_path)) {
                const error = `Le chemin du projet n'existe pas: ${args.project_path}`;
                logger.error(error);
                throw new Error(error);
            }
            // Vérifier les permissions d'écriture (pour les logs et métadonnées)
            const testWritePath = path.join(args.project_path, ".rag-test-permission");
            try {
                fs.writeFileSync(testWritePath, "test");
                fs.unlinkSync(testWritePath);
                logger.debug("✅ Permissions d'écriture vérifiées");
            }
            catch (error) {
                logger.warn("⚠️  Permissions d'écriture limitées, continuation en mode lecture seule");
            }
        }
        catch (error) {
            logger.error("Erreur lors de la vérification des permissions", error);
            throw error;
        }
        // Charger la configuration
        logger.info("⚙️  Chargement de la configuration RAG");
        const configManager = getRagConfigManager();
        const defaults = configManager.getDefaults();
        // Utiliser les valeurs par défaut de la configuration
        const file_patterns = args.file_patterns || defaults.file_patterns;
        const recursive = args.recursive !== undefined ? args.recursive : defaults.recursive;
        const embedding_provider = defaults.embedding_provider;
        const embedding_model = defaults.embedding_model;
        const enable_graph_integration = args.enable_graph_integration !== undefined
            ? args.enable_graph_integration
            : true;
        // Appliquer les limites aux valeurs numériques de la configuration
        const chunk_size = configManager.applyLimits('chunk_size', defaults.chunk_size);
        const chunk_overlap = configManager.applyLimits('chunk_overlap', defaults.chunk_overlap);
        logger.info("📊 Configuration appliquée", {
            file_patterns_count: file_patterns.length,
            recursive,
            embedding_provider,
            embedding_model,
            chunk_size,
            chunk_overlap,
            enable_graph_integration
        });
        // Phase 1 : Intégration avec le graphe de connaissances (si activé)
        if (enable_graph_integration) {
            logger.info("🧠 Phase 1 - Intégration avec le graphe de connaissances");
            try {
                // Note: L'intégration complète avec les outils Graph se fait automatiquement
                // via le système d'enrichissement Phase 0 dans le pipeline RAG
                logger.debug("Enrichissement automatique des entités via Phase 0");
                // Ici, on pourrait appeler des fonctions spécifiques d'enrichissement
                // Par exemple: await enrichWithGraphKnowledge(args.project_path);
                logger.info("✅ Enrichissement Graph intégré automatiquement");
            }
            catch (error) {
                logger.error("Erreur lors de l'intégration Graph, continuation sans enrichissement", error);
                // Ne pas bloquer le processus principal en cas d'erreur Graph
            }
        }
        // Configurer le fournisseur d'embeddings
        logger.info(`🔧 Configuration du fournisseur d'embeddings: ${embedding_provider}`);
        setEmbeddingProvider(embedding_provider, embedding_model);
        const options = {
            filePatterns: file_patterns,
            recursive: recursive,
            chunkSize: chunk_size,
            chunkOverlap: chunk_overlap
        };
        // Phase 2 : Injection RAG principale
        logger.info("🚀 Phase 2 - Injection RAG principale");
        const startTime = Date.now();
        try {
            const result = await indexProject(args.project_path, options);
            const endTime = Date.now();
            const duration = ((endTime - startTime) / 1000).toFixed(2);
            logger.info("✅ Injection RAG terminée avec succès", {
                duration: `${duration}s`,
                total_files: result.totalFiles,
                indexed_files: result.indexedFiles,
                chunks_created: result.chunksCreated,
                errors: result.errors
            });
            return {
                content: [{
                        type: "text",
                        text: JSON.stringify({
                            success: true,
                            version: "v1.0.0",
                            duration_seconds: duration,
                            ...result,
                            config_used: {
                                embedding_provider,
                                embedding_model,
                                chunk_size,
                                chunk_overlap,
                                recursive,
                                file_patterns_count: file_patterns.length,
                                enable_graph_integration,
                                log_level: logLevel
                            },
                            pipeline: {
                                phase_0: "Vérification permissions ✓",
                                phase_1: enable_graph_integration ? "Enrichissement Graph intégré ✓" : "Enrichissement Graph désactivé",
                                phase_2: "Injection RAG principale ✓"
                            }
                        }, null, 2)
                    }]
            };
        }
        catch (error) {
            const endTime = Date.now();
            const duration = ((endTime - startTime) / 1000).toFixed(2);
            logger.error("❌ Erreur lors de l'injection RAG", {
                duration: `${duration}s`,
                error: error instanceof Error ? error.message : String(error)
            });
            throw error;
        }
    };
  • Tool definition object containing name, description, and detailed inputSchema for validation.
    export const injectionRagTool = {
        name: "injection_rag",
        description: "Analyse du projet complet + prépare et injecte les données automatiquement (Phase 0 → RAG)",
        inputSchema: {
            type: "object",
            properties: {
                project_path: {
                    type: "string",
                    description: "Chemin absolu vers le projet à analyser et injecter"
                },
                file_patterns: {
                    type: "array",
                    items: { type: "string" },
                    description: "Patterns de fichiers à inclure (ex: ['**/*.py', '**/*.js'])",
                    default: ["**/*.{js,ts,py,md,txt,json,yaml,yml,html,css,scss}"]
                },
                recursive: {
                    type: "boolean",
                    description: "Parcourir les sous-dossiers récursivement",
                    default: true
                },
                log_level: {
                    type: "string",
                    description: "Niveau de logs (INFO, DEBUG, ERROR)",
                    enum: ["INFO", "DEBUG", "ERROR"],
                    default: "INFO"
                },
                enable_graph_integration: {
                    type: "boolean",
                    description: "Activer l'intégration automatique avec le graphe de connaissances",
                    default: true
                }
            },
            required: ["project_path"]
        },
    };
  • Custom logging utility class used throughout the handler for structured logging with levels (INFO, DEBUG, ERROR).
    class InjectionLogger {
        static instance;
        logLevel = LogLevel.INFO;
        constructor() { }
        static getInstance() {
            if (!InjectionLogger.instance) {
                InjectionLogger.instance = new InjectionLogger();
            }
            return InjectionLogger.instance;
        }
        setLogLevel(level) {
            this.logLevel = level;
        }
        shouldLog(level) {
            const levels = [LogLevel.ERROR, LogLevel.INFO, LogLevel.DEBUG];
            return levels.indexOf(level) <= levels.indexOf(this.logLevel);
        }
        log(level, message, data) {
            if (this.shouldLog(level)) {
                const timestamp = new Date().toISOString();
                const logMessage = `[${timestamp}] [${level}] ${message}`;
                if (data) {
                    console.error(logMessage, JSON.stringify(data, null, 2));
                }
                else {
                    console.error(logMessage);
                }
            }
        }
        info(message, data) {
            this.log(LogLevel.INFO, message, data);
        }
        debug(message, data) {
            this.log(LogLevel.DEBUG, message, data);
        }
        error(message, error) {
            this.log(LogLevel.ERROR, message, error);
        }
        warn(message, data) {
            this.log(LogLevel.INFO, `⚠️  ${message}`, data);
        }
    }
  • TypeScript source definition of the tool schema with typed ToolDefinition.
    export const injectionRagTool: ToolDefinition = {
        name: "injection_rag",
        description: "Analyse du projet complet + prépare et injecte les données automatiquement (Phase 0 → RAG)",
        inputSchema: {
            type: "object",
            properties: {
                project_path: {
                    type: "string",
                    description: "Chemin absolu vers le projet à analyser et injecter"
                },
                file_patterns: {
                    type: "array",
                    items: { type: "string" },
                    description: "Patterns de fichiers à inclure (ex: ['**/*.py', '**/*.js'])",
                    default: ["**/*.{js,ts,py,md,txt,json,yaml,yml,html,css,scss}"]
                },
                recursive: {
                    type: "boolean",
                    description: "Parcourir les sous-dossiers récursivement",
                    default: true
                },
                log_level: {
                    type: "string",
                    description: "Niveau de logs (INFO, DEBUG, ERROR)",
                    enum: ["INFO", "DEBUG", "ERROR"],
                    default: "INFO"
                },
                enable_graph_integration: {
                    type: "boolean",
                    description: "Activer l'intégration automatique avec le graphe de connaissances",
                    default: true
                }
            },
            required: ["project_path"]
        },
    };
Behavior2/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 mentions analyzing, preparing, and injecting data automatically, but doesn't specify what 'injecte' entails (e.g., where data is stored, if it's destructive, authentication needs, or rate limits). The phrase 'automatiquement' hints at automation but lacks operational details.

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 that front-loads the core action. It could be slightly more structured (e.g., separating analysis from injection phases), but it avoids redundancy and wastes no words.

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?

For a complex tool with 5 parameters, no annotations, and no output schema, the description is incomplete. It doesn't explain what 'RAG' means, what data is injected where, or the expected outcomes. Given the lack of structured fields, more behavioral and contextual details are needed.

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 fully documents all 5 parameters. The description adds no parameter-specific information beyond what's in the schema, such as explaining how 'file_patterns' relate to analysis or what 'enable_graph_integration' does in practice. 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's purpose: 'Analyse du projet complet + prépare et injecte les données automatiquement (Phase 0 → RAG)'. It specifies the verb (analyze, prepare, inject) and resource (project data), though it doesn't explicitly differentiate from sibling tools like 'manage_projects' or 'update_project'.

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. It mentions 'Phase 0 → RAG' but doesn't explain what this phase entails or how it relates to other tools like 'search_code' or 'read_graph'. No exclusions or prerequisites are stated.

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