local_debug_context
Analyze error logs and stack traces to extract relevant code context, identify symbols, and provide structured debug reports for troubleshooting complex issues across your codebase.
Instructions
π Gather comprehensive debug context from error logs and codebase analysis with focused embedding enhancement
When to use:
When you have error logs, stack traces, or console output to analyze
When debugging complex issues with multiple file involvement
When you need to understand error context across the codebase
Before using AI debugging tools to get structured context
What this does:
Parses error logs to extract file paths, line numbers, symbols, and error types
Extracts focused error contexts (~200 characters) for precise embedding queries
Uses tree-sitter to build symbol indexes for TypeScript/JavaScript/Python files
Searches codebase for symbol matches with surrounding context
ENHANCED: Uses semantic embeddings with focused error contexts for better relevance
Processes each error/warning separately for improved semantic matching
Ranks matches by relevance (severity, recency, frequency, semantic similarity)
Returns comprehensive debug report ready for AI analysis
Input: Error logs or stack traces as text Output: Structured debug context report with ranked matches and semantic insights
Performance: Fast local analysis, ~1-3 seconds depending on codebase size Embedding Features: Focused context queries reduce noise and improve relevance
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| logText | Yes | Error logs, stack traces, or console output containing error information | |
| projectPath | Yes | Project root directory path. Required. Can be absolute or relative to workspace. | |
| maxMatches | No | Maximum number of matches to return (default: 20) | |
| format | No | Output format preference | structured |
| useEmbeddings | No | Enable embedding-based similarity search for enhanced context (requires local embeddings to be enabled) | |
| embeddingSimilarityThreshold | No | Similarity threshold for embedding-based matches (lower = more results, higher = more precise) | |
| maxSimilarChunks | No | Maximum number of similar code chunks to include from embedding search | |
| generateEmbeddingsIfMissing | No | Generate embeddings for project files if they don't exist (may take time for large projects) |
Input Schema (JSON Schema)
Implementation Reference
- Main handler function that executes the tool logic: parses error logs from input, extracts file/line/symbol info, builds symbol indexes with tree-sitter, performs keyword and semantic embedding searches, calculates relevance scores, ranks matches, generates suggestions, and returns structured DebugContextReport.export async function handleLocalDebugContext(args: any): Promise<DebugContextReport> { const { logText, projectPath = process.cwd(), maxMatches = 20, format = 'structured', useEmbeddings = true, embeddingSimilarityThreshold = 0.2, maxSimilarChunks = 5, generateEmbeddingsIfMissing = false, } = args; if (!logText || typeof logText !== 'string') { throw new Error( 'β logText is required and must be a string. Please provide error logs or stack traces.' ); } const resolvedProjectPath = validateAndResolvePath(projectPath); logger.info('π Starting local debug context gathering', { logLength: logText.length, projectPath: resolvedProjectPath, maxMatches, format, useEmbeddings, embeddingSimilarityThreshold, maxSimilarChunks, generateEmbeddingsIfMissing, embeddingsEnabled: LocalEmbeddingStorage.isEnabled(), }); try { // Phase 1: Parse errors and gather context const errors = parseErrorLogs(logText); const symbols: string[] = []; const fileHints: string[] = []; let allFiles: string[] | null = null; for (const err of errors) { if (err.filePath) { const absPath = path.resolve(resolvedProjectPath, err.filePath); fileHints.push(absPath); if (!err.symbol) { const fileSymbols = await buildSymbolIndex(absPath); const match = fileSymbols.find(s => err.line >= s.startLine && err.line <= s.endLine); if (match) { err.symbol = match.name; symbols.push(match.name); } } else { symbols.push(err.symbol); } } else if (err.symbol) { symbols.push(err.symbol); if (!allFiles) { allFiles = await globby(['**/*.{ts,tsx,js,jsx,py}'], { cwd: resolvedProjectPath, absolute: true, ignore: ['node_modules/**', 'dist/**', '.git/**'], }); } } } if (allFiles) { fileHints.push(...allFiles); } // Search for symbol matches const matches = await searchSymbols(symbols, resolvedProjectPath, fileHints, maxMatches); // Phase 1.5: Add embedding-enhanced search if enabled let allMatches = [...matches]; let embeddingsUsed = false; let similarChunksFound = 0; if (useEmbeddings && LocalEmbeddingStorage.isEnabled() && symbols.length > 0) { try { // Get project identifier for embeddings const projectInfo = await projectIdentifier.identifyProject(resolvedProjectPath); const projectId = projectInfo.id; // Ensure embeddings exist const embeddingsReady = await ensureEmbeddingsForProject( projectId, resolvedProjectPath, generateEmbeddingsIfMissing ); if (embeddingsReady) { // Search for semantically similar code using focused error contexts const semanticMatches = await searchSemanticSimilarities( projectId, errors, symbols, maxSimilarChunks, embeddingSimilarityThreshold ); if (semanticMatches.length > 0) { allMatches = [...matches, ...semanticMatches]; embeddingsUsed = true; similarChunksFound = semanticMatches.length; logger.info('π― Enhanced debug context with focused semantic matches', { originalMatches: matches.length, semanticMatches: semanticMatches.length, totalMatches: allMatches.length, errorsProcessed: errors.length, avgSimilarity: semanticMatches.reduce((sum, m) => sum + (m.embeddingSimilarity || 0), 0) / semanticMatches.length, }); } } } catch (error) { logger.warn('β οΈ Embedding enhancement failed, continuing with standard matches', { error: error instanceof Error ? error.message : String(error), }); } } // Phase 2: Calculate scores and rank matches const freqMap = new Map<string, number>(); for (const m of allMatches) { freqMap.set(m.symbol, (freqMap.get(m.symbol) || 0) + 1); } // Calculate scores for all matches for (const match of allMatches) { const frequency = freqMap.get(match.symbol) || 1; const { score, reason } = await calculateScore(match, errors, resolvedProjectPath, frequency); match.score = score; match.reason = reason; } // Sort by score and assign ranks allMatches.sort((a, b) => b.score - a.score); allMatches.forEach((m, i) => { m.rank = i + 1; }); const uniqueFiles = [...new Set(allMatches.map(m => m.filePath))].length; const topMatches = allMatches.slice(0, 5).map(m => ({ symbol: m.symbol, filePath: m.filePath, score: m.score, reason: m.reason, })); // Generate debugging suggestions const suggestions = generateDebugSuggestions( allMatches, errors, embeddingsUsed, similarChunksFound ); const report: DebugContextReport = { errors, matches: allMatches, summary: { errorCount: errors.length, matchCount: allMatches.length, uniqueFiles, topMatches, embeddingsUsed, similarChunksFound, suggestions, }, }; logger.info('β Local debug context gathering completed', { errorCount: errors.length, matchCount: allMatches.length, uniqueFiles, topScore: allMatches[0]?.score || 0, embeddingsUsed, similarChunksFound, }); return report; } catch (error) { logger.error('β Local debug context gathering failed', { error: (error as Error).message, }); throw new Error(`Local debug context gathering failed: ${(error as Error).message}`); } }
- Tool schema definition with name 'local_debug_context', detailed description, and inputSchema for parameters like logText, projectPath, maxMatches, useEmbeddings etc. Defines input validation and defaults.export const localDebugContextTool = { name: 'local_debug_context', description: `π Gather comprehensive debug context from error logs and codebase analysis with focused embedding enhancement **When to use**: - When you have error logs, stack traces, or console output to analyze - When debugging complex issues with multiple file involvement - When you need to understand error context across the codebase - Before using AI debugging tools to get structured context **What this does**: - Parses error logs to extract file paths, line numbers, symbols, and error types - Extracts focused error contexts (~200 characters) for precise embedding queries - Uses tree-sitter to build symbol indexes for TypeScript/JavaScript/Python files - Searches codebase for symbol matches with surrounding context - **ENHANCED**: Uses semantic embeddings with focused error contexts for better relevance - Processes each error/warning separately for improved semantic matching - Ranks matches by relevance (severity, recency, frequency, semantic similarity) - Returns comprehensive debug report ready for AI analysis **Input**: Error logs or stack traces as text **Output**: Structured debug context report with ranked matches and semantic insights **Performance**: Fast local analysis, ~1-3 seconds depending on codebase size **Embedding Features**: Focused context queries reduce noise and improve relevance`, inputSchema: { type: 'object', properties: { logText: { type: 'string', description: 'Error logs, stack traces, or console output containing error information', }, projectPath: { type: 'string', description: 'Project root directory path. Required. Can be absolute or relative to workspace.', }, maxMatches: { type: 'number', description: 'Maximum number of matches to return (default: 20)', default: 20, minimum: 1, maximum: 100, }, format: { type: 'string', enum: ['structured', 'compact', 'detailed'], default: 'structured', description: 'Output format preference', }, useEmbeddings: { type: 'boolean', default: true, description: 'Enable embedding-based similarity search for enhanced context (requires local embeddings to be enabled)', }, embeddingSimilarityThreshold: { type: 'number', default: 0.2, minimum: 0.0, maximum: 1.0, description: 'Similarity threshold for embedding-based matches (lower = more results, higher = more precise)', }, maxSimilarChunks: { type: 'number', default: 5, minimum: 1, maximum: 20, description: 'Maximum number of similar code chunks to include from embedding search', }, generateEmbeddingsIfMissing: { type: 'boolean', default: false, description: "Generate embeddings for project files if they don't exist (may take time for large projects)", }, }, required: ['logText', 'projectPath'], }, };
- src/index.ts:135-142 (registration)Registration of tool handlers in the MCP server's handlers object, mapping 'local_debug_context' to handleLocalDebugContext function.this.handlers = { ...(allowLocalContext ? { local_context: handleSemanticCompact } : {}), local_project_hints: handleProjectHints, local_file_summary: handleFileSummary, frontend_insights: handleFrontendInsights, local_debug_context: handleLocalDebugContext, ast_grep_search: handleAstGrep, };
- src/index.ts:126-133 (registration)Registration of tool definitions in the MCP server's tools list/array, including localDebugContextTool.this.tools = [ ...(allowLocalContext ? [localSemanticCompactTool] : []), localProjectHintsTool, localFileSummaryTool, frontendInsightsTool, localDebugContextTool, astGrepTool, ];
- src/tools/debug/index.ts:31-34 (registration)Sub-module re-export and registration of debug tool handlers, including local_debug_context.export const debugHandlers = { local_debug_context: handleLocalDebugContext, ai_debug: handleAIDebug, };