extract_code_context
Parse source files using AST to extract targeted code context and relevant imports, optimizing token usage for AI-based code analysis and assistance. Supports TypeScript, JavaScript, Python, Go, and Rust.
Instructions
Extract minimal code context from files using AST parsing
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| filePath | Yes | Path to the source file | |
| includeImports | No | Whether to include relevant imports | |
| maxTokens | No | Maximum tokens to return | |
| targetSymbols | No | Specific symbols/functions to extract context for |
Implementation Reference
- src/core/CodeReferenceOptimizer.ts:18-55 (handler)Core handler implementation for the 'extract_code_context' tool. Performs cache check, AST parsing via ASTParser, context extraction, optional import optimization, assembles CodeContext object, caches result, and applies token limit truncation.async extractCodeContext(options: ExtractContextOptions): Promise<CodeContext> { const { filePath, targetSymbols, includeImports, maxTokens } = options; // Check cache first const cacheKey = this.generateCacheKey(filePath, targetSymbols, includeImports); const cached = await this.cacheManager.get(cacheKey); if (cached && !this.isStale(cached, filePath)) { return this.truncateToTokenLimit(cached, maxTokens || 1000); } // Parse file and extract context const ast = await this.astParser.parseFile(filePath); const extractedContext = await this.astParser.extractContext(ast, targetSymbols); // Optimize imports if requested let optimizedImports: string[] = []; if (includeImports) { const usedSymbols = this.extractUsedSymbols(extractedContext); optimizedImports = await this.importAnalyzer.getMinimalImports(filePath, usedSymbols); } const context: CodeContext = { filePath, extractedCode: extractedContext.code, imports: optimizedImports, symbols: extractedContext.symbols, dependencies: extractedContext.dependencies, tokenCount: this.estimateTokenCount(extractedContext.code + optimizedImports.join('\n')), timestamp: Date.now(), relevanceScore: this.calculateRelevanceScore(extractedContext, targetSymbols), }; // Cache the result await this.cacheManager.set(cacheKey, context); return this.truncateToTokenLimit(context, maxTokens || 1000); }
- src/index.ts:301-320 (handler)MCP server wrapper handler for 'extract_code_context' tool calls. Parses input arguments and delegates execution to CodeReferenceOptimizer.extractCodeContext, formats result as MCP content response.private async handleExtractCodeContext(args: any) { const { filePath, targetSymbols, includeImports = true, maxTokens = 1000 } = args; this.logger.info(`extract_code_context: filePath=${filePath}`); const result = await this.optimizer.extractCodeContext({ filePath, targetSymbols, includeImports, maxTokens, }); return { content: [ { type: 'text', text: JSON.stringify(result, null, 2), }, ], }; }
- src/index.ts:229-230 (registration)Tool dispatch registration in CallToolRequestSchema switch statement.case 'extract_code_context': return await this.handleExtractCodeContext(args);
- src/index.ts:99-123 (schema)Input schema definition for the 'extract_code_context' tool, defining parameters like filePath, targetSymbols, includeImports, and maxTokens.inputSchema: { type: 'object', properties: { filePath: { type: 'string', description: 'Absolute or relative path to the source file to analyze. Supports TypeScript, JavaScript, Python, Go, and other languages with tree-sitter parsers.', }, targetSymbols: { type: 'array', items: { type: 'string' }, description: 'Array of specific symbol names (functions, classes, variables, types) to extract context for. If empty or omitted, extracts context for the entire file.', }, includeImports: { type: 'boolean', description: 'Whether to include import statements and dependencies relevant to the extracted symbols. Recommended for understanding symbol usage.', default: true, }, maxTokens: { type: 'number', description: 'Maximum number of tokens to include in the response. Higher values provide more context but consume more resources. Range: 100-5000.', default: 1000, }, }, required: ['filePath'], },
- src/index.ts:96-124 (registration)Full tool registration entry in ListTools response, including name, description, and input schema.{ name: 'extract_code_context', description: 'Extract minimal, focused code context from source files using AST parsing. Intelligently identifies and extracts only the relevant code sections, imports, and dependencies needed for understanding specific symbols or functions. Optimizes token usage by filtering out unnecessary code while maintaining semantic completeness.', inputSchema: { type: 'object', properties: { filePath: { type: 'string', description: 'Absolute or relative path to the source file to analyze. Supports TypeScript, JavaScript, Python, Go, and other languages with tree-sitter parsers.', }, targetSymbols: { type: 'array', items: { type: 'string' }, description: 'Array of specific symbol names (functions, classes, variables, types) to extract context for. If empty or omitted, extracts context for the entire file.', }, includeImports: { type: 'boolean', description: 'Whether to include import statements and dependencies relevant to the extracted symbols. Recommended for understanding symbol usage.', default: true, }, maxTokens: { type: 'number', description: 'Maximum number of tokens to include in the response. Higher values provide more context but consume more resources. Range: 100-5000.', default: 1000, }, }, required: ['filePath'], }, },