Skip to main content
Glama
bswa006

AI Agent Template MCP Server

by bswa006

create_token_optimizer

Generate tiered context files for token optimization with ROI tracking to manage AI agent coding efficiency.

Instructions

Create tiered context files for token optimization with ROI tracking

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
projectPathYesPath to the project directory
analysisIdNoAnalysis ID from analyze_codebase_deeply
tiersNoWhich context tiers to generate
trackUsageNoEnable token usage tracking
generateMetricsNoGenerate ROI metrics report

Implementation Reference

  • The main handler function that implements the tool logic: creates tiered token-optimized context files (minimal, standard, comprehensive), context router YAML, usage tracking, and metrics report based on prior codebase analysis.
    export async function createTokenOptimizer(
      config: TokenOptimizerConfig
    ): Promise<TokenOptimizerResult> {
      const result: TokenOptimizerResult = {
        success: false,
        filesCreated: [],
        message: '',
        tokenSavings: {
          minimal: 0,
          standard: 0,
          comprehensive: 0,
          percentSaved: 0,
        },
      };
    
      try {
        // Check if analysis has been completed
        const analysisId = config.analysisId || global.latestAnalysisId;
        if (!analysisId || !global.codebaseAnalysis?.[analysisId]) {
          throw new Error('Codebase analysis must be completed first. Run analyze_codebase_deeply tool.');
        }
    
        const analysis: DeepAnalysisResult = global.codebaseAnalysis[analysisId];
        const tiers = config.tiers || ['minimal', 'standard', 'comprehensive'];
        
        // Create agent-context directory if it doesn't exist
        const contextDir = join(config.projectPath, 'agent-context');
        if (!existsSync(contextDir)) {
          mkdirSync(contextDir, { recursive: true });
        }
        
        // Generate tiered context files
        const contextTiers = generateTieredContexts(analysis, tiers);
        
        // Write each tier
        for (const tier of contextTiers) {
          const filePath = join(contextDir, `${tier.name}-context.md`);
          writeFileSync(filePath, tier.content);
          result.filesCreated.push(filePath);
          
          // Calculate token savings
          const baselineTokens = estimateTokens(getFullContext(analysis));
          const tierTokens = estimateTokens(tier.content);
          result.tokenSavings[tier.name] = tierTokens;
          
          if (tier.name === 'minimal') {
            result.tokenSavings.percentSaved = Math.round((1 - tierTokens / baselineTokens) * 100);
          }
        }
        
        // Create context router configuration
        const routerConfig = createContextRouter(analysis, contextTiers);
        const routerPath = join(contextDir, 'context-router.yaml');
        writeFileSync(routerPath, yaml.dump(routerConfig));
        result.filesCreated.push(routerPath);
        
        // Create usage tracking configuration if requested
        if (config.trackUsage) {
          const trackingConfig = createUsageTracking();
          const trackingPath = join(contextDir, 'token-tracking.yaml');
          writeFileSync(trackingPath, yaml.dump(trackingConfig));
          result.filesCreated.push(trackingPath);
        }
        
        // Generate metrics report if requested
        if (config.generateMetrics) {
          const metricsReport = generateMetricsReport(contextTiers, analysis);
          const metricsPath = join(contextDir, 'token-optimization-report.md');
          writeFileSync(metricsPath, metricsReport);
          result.filesCreated.push(metricsPath);
        }
        
        result.success = true;
        result.message = `Created ${result.filesCreated.length} token-optimized files. Minimal tier saves ${result.tokenSavings.percentSaved}% tokens!`;
      } catch (error) {
        result.success = false;
        result.message = `Failed to create token optimizer: ${error}`;
      }
    
      return result;
    }
  • MCP tool schema definition specifying input parameters like projectPath, analysisId, tiers, trackUsage, generateMetrics.
      name: 'create_token_optimizer',
      description: 'Create tiered context files for token optimization with ROI tracking',
      inputSchema: {
        type: 'object',
        properties: {
          projectPath: {
            type: 'string',
            description: 'Path to the project directory',
          },
          analysisId: {
            type: 'string',
            description: 'Analysis ID from analyze_codebase_deeply',
          },
          tiers: {
            type: 'array',
            items: {
              type: 'string',
              enum: ['minimal', 'standard', 'comprehensive'],
            },
            description: 'Which context tiers to generate',
          },
          trackUsage: {
            type: 'boolean',
            description: 'Enable token usage tracking',
          },
          generateMetrics: {
            type: 'boolean',
            description: 'Generate ROI metrics report',
          },
        },
        required: ['projectPath'],
      },
    },
  • Tool registration and dispatch in the main tool call handler: validates input with Zod matching the schema and calls the handler function.
    case 'create_token_optimizer': {
      const params = z.object({
        projectPath: z.string(),
        analysisId: z.string().optional(),
        tiers: z.array(z.enum(['minimal', 'standard', 'comprehensive'])).optional(),
        trackUsage: z.boolean().optional(),
        generateMetrics: z.boolean().optional(),
      }).parse(args);
      
      const result = await createTokenOptimizer(params);
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2),
          },
        ],
      };
    }
  • TypeScript interfaces defining input config, output result, and internal ContextTier used by the handler for type safety.
    interface TokenOptimizerConfig {
      projectPath: string;
      analysisId?: string;
      tiers?: ('minimal' | 'standard' | 'comprehensive')[];
      trackUsage?: boolean;
      generateMetrics?: boolean;
    }
    
    interface TokenOptimizerResult {
      success: boolean;
      filesCreated: string[];
      message: string;
      tokenSavings: {
        minimal: number;
        standard: number;
        comprehensive: number;
        percentSaved: number;
      };
    }
    
    interface ContextTier {
      name: 'minimal' | 'standard' | 'comprehensive';
      targetTokens: number;
      files: string[];
      content: string;
    }
  • Key helper function that generates the tiered context configurations based on analysis and requested tiers.
    function generateTieredContexts(
      analysis: DeepAnalysisResult,
      tiers: ('minimal' | 'standard' | 'comprehensive')[]
    ): ContextTier[] {
      const contextTiers: ContextTier[] = [];
      
      if (tiers.includes('minimal')) {
        contextTiers.push({
          name: 'minimal',
          targetTokens: 300,
          files: ['quick-reference.md'],
          content: generateMinimalContext(analysis),
        });
      }
      
      if (tiers.includes('standard')) {
        contextTiers.push({
          name: 'standard',
          targetTokens: 1500,
          files: ['quick-reference.md', 'patterns.yaml'],
          content: generateStandardContext(analysis),
        });
      }
      
      if (tiers.includes('comprehensive')) {
        contextTiers.push({
          name: 'comprehensive',
          targetTokens: 3000,
          files: ['quick-reference.md', 'CODEBASE-CONTEXT.md', 'PROJECT-TEMPLATE.md'],
          content: generateComprehensiveContext(analysis),
        });
      }
      
      return contextTiers;
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool creates files and tracks ROI, but doesn't describe what 'tiered context files' are, how they're used, whether this is a read or write operation, potential side effects, or any permissions/rate limits. For a tool with no annotation coverage, this leaves significant behavioral gaps.

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 without unnecessary words. Every part of the sentence contributes to understanding the tool's function, making it appropriately 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 complexity (5 parameters, no annotations, no output schema), the description is incomplete. It doesn't explain what 'tiered context files' are, how token optimization works, what ROI metrics include, or the tool's output. For a tool with no annotations or output schema, more contextual detail is needed to guide effective use.

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 already documents all 5 parameters thoroughly. The description adds minimal value beyond the schema—it mentions 'tiered context files' which relates to the 'tiers' parameter, and 'ROI tracking' which relates to 'trackUsage' and 'generateMetrics', but doesn't provide additional context or meaning. Baseline 3 is appropriate when the 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 action ('Create tiered context files') and purpose ('for token optimization with ROI tracking'), providing a specific verb+resource combination. It distinguishes from siblings by focusing on token optimization and ROI tracking, though it doesn't explicitly contrast with similar tools like 'track_agent_performance' or 'initialize_agent_workspace'.

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?

No explicit guidance on when to use this tool versus alternatives is provided. The description mentions 'analysisId from analyze_codebase_deeply', implying a prerequisite, but doesn't state when this tool is appropriate or when other tools might be better suited. No exclusions or alternatives are mentioned.

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/bswa006/mcp-context-manager'

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