Skip to main content
Glama
FosterG4

Code Reference Optimizer MCP Server

by FosterG4

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
NameRequiredDescriptionDefault
filePathYesPath to the source file
includeImportsNoWhether to include relevant imports
maxTokensNoMaximum tokens to return
targetSymbolsNoSpecific symbols/functions to extract context for

Implementation Reference

  • 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);
    }
  • 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);
  • 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'],
      },
    },
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 'minimal code context' and 'AST parsing', which hints at read-only, non-destructive behavior, but fails to specify critical details like error handling, performance implications, or what 'minimal' entails (e.g., token limits, scope). This leaves significant gaps for a tool with 4 parameters.

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

Conciseness5/5

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

The description is a single, efficient sentence that front-loads the core purpose ('extract minimal code context') and method ('using AST parsing'). Every word earns its place with no redundancy or fluff, making it highly concise and well-structured.

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 tool's complexity (4 parameters, AST parsing), lack of annotations, and no output schema, the description is incomplete. It doesn't explain return values, error cases, or behavioral nuances, leaving the agent under-informed for effective use. This is inadequate for a tool with moderate complexity and no structured support.

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 4 parameters. The description adds no additional parameter semantics beyond what's in the schema (e.g., it doesn't explain how 'targetSymbols' interacts with 'includeImports' or clarify 'maxTokens' units). This meets the baseline for high schema coverage.

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 action ('extract minimal code context') and method ('using AST parsing'), which is specific and distinguishes it from siblings like 'analyze_code_diff' or 'get_cached_context'. However, it doesn't explicitly differentiate from all siblings (e.g., 'optimize_imports' also deals with code structure), keeping it from a perfect score.

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 'get_cached_context' or 'analyze_code_diff'. It lacks context about prerequisites, typical scenarios, or exclusions, leaving the agent with minimal usage direction beyond the basic purpose.

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

Related 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/FosterG4/mcpsaver'

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