/** * RAG Context Builder MCP Tool Handler * * Builds comprehensive context for agent use by executing multiple RAG searches * in parallel, consolidating and deduplicating results, and fitting within * a specified token budget. * * @module @wundr/mcp-server/tools/rag/rag-context-builder */ import { z } from 'zod'; import { GeminiRAGService } from '../../services/gemini'; import type { McpToolResult } from '../registry'; import type { ConsolidatedContextItem, IRAGService, ITokenCounter, PrioritizationStrategy, RAGChunk, RAGContextBuilderInput, RAGContextBuilderOutput, RAGSearchResult, RAGStore, QueryResult, TokenCountResult } from './types'; /** * Default token counter implementation using character-based estimation */ export declare class DefaultTokenCounter implements ITokenCounter { private readonly charsPerToken; constructor(charsPerToken?: number); /** * Count tokens in a string */ count(text: string): TokenCountResult; /** * Estimate tokens without full counting */ estimate(text: string): number; /** * Truncate text to fit within token limit */ truncateToFit(text: string, maxTokens: number): string; } /** * Get the default token counter instance */ export declare function getTokenCounter(): ITokenCounter; /** * Estimate token count for a string */ export declare function estimateTokens(text: string): number; /** * Truncate text to fit within token budget */ export declare function truncateToTokenBudget(text: string, maxTokens: number): string; /** * Merge duplicate chunks from multiple search results */ export declare function deduplicateChunks(searchResults: readonly RAGSearchResult[]): Map; /** * Convert deduplicated chunks to consolidated context items */ export declare function consolidateChunks(deduped: Map, tokenCounter: ITokenCounter): ConsolidatedContextItem[]; export declare const ContextQuerySchema: z.ZodObject<{ query: z.ZodString; storeIds: z.ZodOptional>; priority: z.ZodDefault>>; weight: z.ZodDefault>; }, "strip", z.ZodTypeAny, { query: string; weight: number; priority: "low" | "medium" | "high"; storeIds?: string[] | undefined; }, { query: string; weight?: number | undefined; priority?: "low" | "medium" | "high" | undefined; storeIds?: string[] | undefined; }>; export type ContextQuery = z.infer; export declare const RagContextBuilderInputSchema: z.ZodObject<{ queries: z.ZodUnion<[z.ZodArray, z.ZodArray>; priority: z.ZodDefault>>; weight: z.ZodDefault>; }, "strip", z.ZodTypeAny, { query: string; weight: number; priority: "low" | "medium" | "high"; storeIds?: string[] | undefined; }, { query: string; weight?: number | undefined; priority?: "low" | "medium" | "high" | undefined; storeIds?: string[] | undefined; }>, "many">]>; targetPath: z.ZodOptional; contextGoal: z.ZodOptional; maxContextTokens: z.ZodDefault>; prioritization: z.ZodDefault>>; includePatterns: z.ZodOptional>; excludePatterns: z.ZodOptional>; minScore: z.ZodDefault>; tokenBudget: z.ZodOptional; strategy: z.ZodOptional>; deduplication: z.ZodDefault>; includeMetadata: z.ZodDefault>; maxResultsPerQuery: z.ZodDefault>; }, "strip", z.ZodTypeAny, { minScore: number; queries: string[] | { query: string; weight: number; priority: "low" | "medium" | "high"; storeIds?: string[] | undefined; }[]; maxContextTokens: number; prioritization: "relevance" | "recency" | "coverage"; deduplication: boolean; includeMetadata: boolean; maxResultsPerQuery: number; includePatterns?: string[] | undefined; excludePatterns?: string[] | undefined; strategy?: "relevance" | "recency" | "diversity" | "balanced" | undefined; targetPath?: string | undefined; contextGoal?: string | undefined; tokenBudget?: number | undefined; }, { queries: string[] | { query: string; weight?: number | undefined; priority?: "low" | "medium" | "high" | undefined; storeIds?: string[] | undefined; }[]; includePatterns?: string[] | undefined; excludePatterns?: string[] | undefined; minScore?: number | undefined; strategy?: "relevance" | "recency" | "diversity" | "balanced" | undefined; targetPath?: string | undefined; contextGoal?: string | undefined; maxContextTokens?: number | undefined; prioritization?: "relevance" | "recency" | "coverage" | undefined; deduplication?: boolean | undefined; tokenBudget?: number | undefined; includeMetadata?: boolean | undefined; maxResultsPerQuery?: number | undefined; }>; export type RagContextBuilderInputLegacy = z.infer; export interface ContextSegment { queryIndex: number; query: string; content: string; source: string; score: number; tokenCount: number; metadata?: Record; } export interface RagContextBuilderOutputLegacy { context: string; segments: ContextSegment[]; totalTokens: number; tokenBudgetUsed: number; queriesExecuted: number; resultsIncluded: number; deduplicatedCount?: number; } export interface GeminiRAGServiceLegacy { listStores(): Promise; getStore(storeId: string): Promise; search(storeId: string, query: string, options?: { topK?: number; minScore?: number; fileFilter?: string[]; }): Promise; estimateTokens(text: string): number; } /** * Strategy interface for context prioritization */ export interface PrioritizationStrategyImpl { sort(items: ConsolidatedContextItem[]): ConsolidatedContextItem[]; getName(): PrioritizationStrategy; } /** * Relevance-based prioritization - highest relevance scores first */ export declare class RelevancePrioritization implements PrioritizationStrategyImpl { sort(items: ConsolidatedContextItem[]): ConsolidatedContextItem[]; getName(): PrioritizationStrategy; } /** * Recency-based prioritization - most recent items first */ export declare class RecencyPrioritization implements PrioritizationStrategyImpl { sort(items: ConsolidatedContextItem[]): ConsolidatedContextItem[]; getName(): PrioritizationStrategy; } /** * Coverage-based prioritization - ensure all queries have representation */ export declare class CoveragePrioritization implements PrioritizationStrategyImpl { sort(items: ConsolidatedContextItem[]): ConsolidatedContextItem[]; getName(): PrioritizationStrategy; } /** * Get the appropriate prioritization strategy implementation */ export declare function getPrioritizationStrategy(strategy: PrioritizationStrategy): PrioritizationStrategyImpl; /** * Creates the RAG context builder handler */ export declare function createRagContextBuilderHandler(ragService: GeminiRAGService): (input: RagContextBuilderInputLegacy) => Promise>; /** * Tool definition for MCP registration (legacy format) */ export declare const ragContextBuilderToolLegacy: { name: string; description: string; inputSchema: { type: string; properties: { queries: { type: string; items: { type: string; properties: { query: { type: string; description: string; }; storeIds: { type: string; items: { type: string; }; description: string; }; priority: { type: string; enum: string[]; description: string; }; weight: { type: string; description: string; }; }; required: string[]; }; description: string; }; tokenBudget: { type: string; description: string; default: number; }; strategy: { type: string; enum: string[]; description: string; default: string; }; deduplication: { type: string; description: string; default: boolean; }; includeMetadata: { type: string; description: string; default: boolean; }; maxResultsPerQuery: { type: string; description: string; default: number; }; }; required: string[]; }; category: string; }; /** * Format consolidated context items into a structured string for agent use */ export declare function formatContextForAgent(items: readonly ConsolidatedContextItem[], contextGoal: string): string; /** * Select items that fit within the token budget */ export declare function selectWithinBudget(items: ConsolidatedContextItem[], maxTokens: number, tokenCounter: ITokenCounter): { selected: ConsolidatedContextItem[]; totalTokens: number; }; /** * RAG Context Builder Handler * * Executes multiple RAG searches in parallel, consolidates results, * and builds comprehensive context within a token budget. * * @param input - Context builder input parameters * @param ragService - Optional RAG service instance (defaults to GeminiRAGService) * @returns Context builder output with formatted context and metadata * * @example * ```typescript * const result = await ragContextBuilderHandler({ * queries: ['authentication', 'JWT tokens', 'refresh tokens'], * targetPath: '/path/to/project', * contextGoal: 'Understand the authentication system', * maxContextTokens: 4000, * prioritization: 'relevance', * }); * * console.log(result.formattedContext); * ``` */ export declare function ragContextBuilderHandler(input: RAGContextBuilderInput, ragService?: IRAGService): Promise; /** * MCP Tool definition for RAG Context Builder (new format) */ export declare const ragContextBuilderTool: { name: string; description: string; inputSchema: { type: "object"; properties: { queries: { type: string; items: { type: string; }; description: string; minItems: number; }; targetPath: { type: string; description: string; }; contextGoal: { type: string; description: string; }; maxContextTokens: { type: string; description: string; minimum: number; default: number; }; prioritization: { type: string; enum: string[]; description: string; default: string; }; includePatterns: { type: string; items: { type: string; }; description: string; }; excludePatterns: { type: string; items: { type: string; }; description: string; }; minScore: { type: string; description: string; minimum: number; maximum: number; default: number; }; }; required: string[]; }; category: string; }; /** * Handle MCP tool call for RAG Context Builder */ export declare function handleRagContextBuilder(args: Record): Promise<{ success: boolean; data?: RAGContextBuilderOutput; error?: string; }>; //# sourceMappingURL=rag-context-builder.d.ts.map