Skip to main content
Glama
bswa006
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; }

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