Cost Tracking
Comprehensive cost tracking and budget management for webMCP optimizations. Monitor spending, track savings, and maximize ROI.
Cost Tracking Features
Advanced cost monitoring and budget management capabilities
Real-Time Cost Monitoring
Track AI model costs and savings in real-time
- Live cost calculation per request
- Model-specific pricing tracking
- Instant savings calculations
- Budget threshold alerts
Cost Optimization Analytics
Analyze spending patterns and optimization opportunities
- Token reduction impact analysis
- Cost per optimization metrics
- ROI calculation and tracking
- Trend analysis and forecasting
Budget Management
Set budgets and manage spending across projects
- Project-level budget allocation
- Spending limit enforcement
- Automated alerts and notifications
- Cost center reporting
Model Pricing & Savings
Current pricing for supported AI models and average optimization savings
| Model | Input Cost (per 1K tokens) | Output Cost (per 1K tokens) | Avg Reduction | Avg Savings (per 1K tokens) |
|---|---|---|---|---|
| GPT-4o | $0.0025 | $0.0100 | 68.1% | $0.0068 |
| Claude-3.5-Sonnet | $0.0030 | $0.0150 | 71.3% | $0.0107 |
| GPT-4 | $0.0030 | $0.0060 | 64.9% | $0.0058 |
| GPT-3.5-Turbo | $0.0005 | $0.0015 | 62.4% | $0.0013 |
Cost Analytics Dashboard
Real-time cost tracking and performance metrics
This Month
Growth vs Last Month
Implementation Examples
Practical examples for implementing cost tracking in your applications
Basic Cost Tracking Setup
Enable cost tracking and monitoring in your application
JavaScriptimport { WebMCPProcessor, CostTracker } from '@webmcp/core';
const processor = new WebMCPProcessor({
costTracking: {
enabled: true,
currency: 'USD',
// Model pricing configuration
modelPricing: {
'gpt-4o': { input: 0.0025, output: 0.01 },
'claude-3.5-sonnet': { input: 0.003, output: 0.015 },
'gpt-4': { input: 0.003, output: 0.006 },
'gpt-3.5-turbo': { input: 0.0005, output: 0.0015 }
},
// Budget settings
budgets: {
monthly: 5000.00,
daily: 200.00,
perProject: 1000.00
},
// Alert thresholds
alerts: {
budgetThreshold: 0.8, // 80% of budget
costSpike: 2.0, // 2x normal spending
lowEfficiency: 0.5 // Below 50% optimization
}
}
});
// Track costs for optimization
const trackOptimizationCost = async (htmlContent, options = {}) => {
const startTime = Date.now();
try {
// Process with cost tracking
const result = await processor.parseWebMCP(htmlContent, {
trackCosts: true,
project: options.project || 'default',
...options
});
const processingTime = Date.now() - startTime;
// Get cost breakdown
const costData = {
originalCost: result.costAnalysis.originalCost,
optimizedCost: result.costAnalysis.optimizedCost,
savings: result.costAnalysis.savings,
savingsPercentage: result.costAnalysis.savingsPercentage,
processingTime,
model: result.targetModel,
tokenReduction: result.tokenReduction
};
console.log('Cost Analysis:', costData);
// Check budget status
const budgetStatus = await processor.costTracker.checkBudget(options.project);
if (budgetStatus.exceeded) {
console.warn('Budget exceeded:', budgetStatus);
}
return { result, costData, budgetStatus };
} catch (error) {
console.error('Cost tracking failed:', error);
throw error;
}
};
// Usage example
const processForm = async () => {
const htmlForm = `
<form>
<input name="email" type="email" required />
<input name="password" type="password" required />
<button type="submit">Login</button>
</form>
`;
const { result, costData } = await trackOptimizationCost(htmlForm, {
project: 'authentication',
targetModel: 'gpt-4o'
});
console.log(`Saved $${costData.savings.toFixed(4)} (${costData.savingsPercentage.toFixed(1)}%)`);
};Advanced Budget Management
Implement comprehensive budget tracking and alerts
JavaScriptclass BudgetManager {
constructor(processor) {
this.processor = processor;
this.budgets = new Map();
this.spending = new Map();
this.alerts = [];
}
// Set project budget
setBudget(projectId, budget) {
this.budgets.set(projectId, {
...budget,
createdAt: Date.now(),
alertThresholds: [0.5, 0.8, 0.9, 1.0] // 50%, 80%, 90%, 100%
});
// Initialize spending tracking
this.spending.set(projectId, {
current: 0,
daily: [],
monthly: 0,
lastReset: Date.now()
});
}
// Track spending
async trackSpending(projectId, cost, metadata = {}) {
if (!this.spending.has(projectId)) {
throw new Error(`Project ${projectId} not found`);
}
const spending = this.spending.get(projectId);
const budget = this.budgets.get(projectId);
// Update spending
spending.current += cost;
spending.monthly += cost;
spending.daily.push({
date: new Date().toISOString().split('T')[0],
amount: cost,
metadata
});
// Check for budget alerts
await this.checkBudgetAlerts(projectId, spending, budget);
// Clean old daily data (keep 30 days)
const thirtyDaysAgo = Date.now() - (30 * 24 * 60 * 60 * 1000);
spending.daily = spending.daily.filter(entry =>
new Date(entry.date).getTime() > thirtyDaysAgo
);
return {
projectId,
totalSpent: spending.current,
budgetRemaining: budget.monthly - spending.current,
utilizationPercentage: (spending.current / budget.monthly) * 100
};
}
// Check budget alerts
async checkBudgetAlerts(projectId, spending, budget) {
const utilization = spending.current / budget.monthly;
for (const threshold of budget.alertThresholds) {
const alertKey = `${projectId}_${threshold}`;
if (utilization >= threshold && !this.alerts.includes(alertKey)) {
this.alerts.push(alertKey);
await this.sendBudgetAlert({
projectId,
threshold: threshold * 100,
currentSpending: spending.current,
budgetLimit: budget.monthly,
utilization: utilization * 100
});
}
}
}
// Send budget alert
async sendBudgetAlert(alertData) {
const message = `
Budget Alert: Project ${alertData.projectId}
Current Spending: $${alertData.currentSpending.toFixed(2)}
Budget Limit: $${alertData.budgetLimit.toFixed(2)}
Utilization: ${alertData.utilization.toFixed(1)}%
Threshold Reached: ${alertData.threshold}%
`;
console.warn(message);
// Send to external alerting system
if (this.alertWebhook) {
try {
await fetch(this.alertWebhook, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
type: 'budget_alert',
...alertData,
timestamp: new Date().toISOString()
})
});
} catch (error) {
console.error('Failed to send alert:', error);
}
}
}
// Get spending report
getSpendingReport(projectId, timeRange = '30d') {
const spending = this.spending.get(projectId);
const budget = this.budgets.get(projectId);
if (!spending || !budget) {
throw new Error(`Project ${projectId} not found`);
}
const days = parseInt(timeRange.replace('d', ''));
const cutoffDate = new Date(Date.now() - (days * 24 * 60 * 60 * 1000));
const recentSpending = spending.daily.filter(entry =>
new Date(entry.date) >= cutoffDate
);
const totalSpent = recentSpending.reduce((sum, entry) => sum + entry.amount, 0);
const avgDailySpend = totalSpent / days;
const projectedMonthly = avgDailySpend * 30;
return {
projectId,
timeRange,
totalSpent,
avgDailySpend,
projectedMonthly,
budgetUtilization: (spending.current / budget.monthly) * 100,
budgetRemaining: budget.monthly - spending.current,
onTrack: projectedMonthly <= budget.monthly,
dailyBreakdown: recentSpending
};
}
// Optimize spending recommendations
getOptimizationRecommendations(projectId) {
const report = this.getSpendingReport(projectId);
const recommendations = [];
if (report.projectedMonthly > report.budgetRemaining) {
recommendations.push({
type: 'budget_risk',
priority: 'high',
message: 'Projected spending exceeds remaining budget',
action: 'Consider reducing usage or optimizing more aggressively'
});
}
if (report.avgDailySpend > report.budgetRemaining / 30) {
recommendations.push({
type: 'daily_overspend',
priority: 'medium',
message: 'Daily spending is above sustainable rate',
action: 'Review daily usage patterns and implement rate limiting'
});
}
return recommendations;
}
}
// Usage
const budgetManager = new BudgetManager(processor);
// Set up project budgets
budgetManager.setBudget('ecommerce', {
monthly: 2000.00,
daily: 80.00,
perOptimization: 0.50
});
budgetManager.setBudget('authentication', {
monthly: 500.00,
daily: 20.00,
perOptimization: 0.25
});
// Track spending
const costData = await trackOptimizationCost(htmlContent);
await budgetManager.trackSpending('ecommerce', costData.originalCost - costData.optimizedCost);
// Get spending report
const report = budgetManager.getSpendingReport('ecommerce', '7d');
console.log('Spending Report:', report);Cost Optimization ROI Calculator
Calculate return on investment for webMCP optimization
JavaScriptclass ROICalculator {
constructor() {
this.baselines = new Map();
this.optimizationResults = [];
}
// Set baseline costs before optimization
setBaseline(projectId, baselineData) {
this.baselines.set(projectId, {
...baselineData,
timestamp: Date.now()
});
}
// Calculate ROI for optimization
calculateROI(projectId, optimizationData) {
const baseline = this.baselines.get(projectId);
if (!baseline) {
throw new Error(`No baseline set for project ${projectId}`);
}
const timeSpan = optimizationData.timeSpan || 30; // days
// Calculate costs
const baselineMonthlyCost = baseline.avgCostPerRequest * baseline.monthlyRequests;
const optimizedMonthlyCost = optimizationData.avgCostPerRequest * optimizationData.monthlyRequests;
const monthlySavings = baselineMonthlyCost - optimizedMonthlyCost;
// Calculate implementation costs
const implementationCost = optimizationData.implementationCost || 0;
const maintenanceCost = optimizationData.maintenanceCost || 0;
// ROI calculation
const annualSavings = monthlySavings * 12;
const totalInvestment = implementationCost + (maintenanceCost * 12);
const roi = ((annualSavings - totalInvestment) / totalInvestment) * 100;
// Payback period
const paybackMonths = totalInvestment / monthlySavings;
const roiData = {
projectId,
timeSpan,
baseline: {
monthlyCost: baselineMonthlyCost,
annualCost: baselineMonthlyCost * 12
},
optimized: {
monthlyCost: optimizedMonthlyCost,
annualCost: optimizedMonthlyCost * 12
},
savings: {
monthly: monthlySavings,
annual: annualSavings,
percentage: (monthlySavings / baselineMonthlyCost) * 100
},
investment: {
implementation: implementationCost,
maintenance: maintenanceCost,
total: totalInvestment
},
roi: {
percentage: roi,
paybackMonths: paybackMonths,
netPresentValue: annualSavings - totalInvestment
},
calculatedAt: new Date().toISOString()
};
this.optimizationResults.push(roiData);
return roiData;
}
// Generate ROI report
generateROIReport(projectIds = null) {
const results = projectIds
? this.optimizationResults.filter(r => projectIds.includes(r.projectId))
: this.optimizationResults;
const totalAnnualSavings = results.reduce((sum, r) => sum + r.savings.annual, 0);
const totalInvestment = results.reduce((sum, r) => sum + r.investment.total, 0);
const avgROI = results.reduce((sum, r) => sum + r.roi.percentage, 0) / results.length;
const avgPayback = results.reduce((sum, r) => sum + r.roi.paybackMonths, 0) / results.length;
return {
summary: {
totalProjects: results.length,
totalAnnualSavings,
totalInvestment,
netBenefit: totalAnnualSavings - totalInvestment,
avgROI,
avgPaybackMonths: avgPayback
},
projects: results,
recommendations: this.generateRecommendations(results)
};
}
generateRecommendations(results) {
const recommendations = [];
// High ROI projects
const highROI = results.filter(r => r.roi.percentage > 200);
if (highROI.length > 0) {
recommendations.push({
type: 'scale_success',
message: `${highROI.length} projects showing high ROI (>200%). Consider expanding optimization to similar projects.`,
projects: highROI.map(r => r.projectId)
});
}
// Quick payback projects
const quickPayback = results.filter(r => r.roi.paybackMonths < 3);
if (quickPayback.length > 0) {
recommendations.push({
type: 'quick_wins',
message: `${quickPayback.length} projects with quick payback (<3 months). Prioritize these for immediate impact.`,
projects: quickPayback.map(r => r.projectId)
});
}
// Low performing projects
const lowROI = results.filter(r => r.roi.percentage < 50);
if (lowROI.length > 0) {
recommendations.push({
type: 'optimization_needed',
message: `${lowROI.length} projects showing low ROI (<50%). Review optimization strategies.`,
projects: lowROI.map(r => r.projectId)
});
}
return recommendations;
}
}
// Usage example
const roiCalculator = new ROICalculator();
// Set baseline (before webMCP)
roiCalculator.setBaseline('checkout-forms', {
avgCostPerRequest: 0.025,
monthlyRequests: 10000,
avgResponseTime: 2.5,
errorRate: 0.02
});
// Calculate ROI after optimization
const roiData = roiCalculator.calculateROI('checkout-forms', {
avgCostPerRequest: 0.008,
monthlyRequests: 10000,
avgResponseTime: 1.2,
errorRate: 0.005,
implementationCost: 5000,
maintenanceCost: 200
});
console.log(`ROI: ${roiData.roi.percentage.toFixed(1)}%`);
console.log(`Payback: ${roiData.roi.paybackMonths.toFixed(1)} months`);
console.log(`Annual Savings: $${roiData.savings.annual.toFixed(2)}`);Python Cost Tracking
Cost tracking implementation for Python applications
Pythonfrom webmcp_core import WebMCPProcessor, CostTracker
from datetime import datetime, timedelta
import pandas as pd
from typing import Dict, List, Optional
class WebMCPCostTracker:
def __init__(self, model_pricing: Dict[str, Dict[str, float]]):
self.model_pricing = model_pricing
self.cost_history = []
self.budgets = {}
self.alerts = []
def calculate_cost(self, tokens_input: int, tokens_output: int, model: str) -> Dict:
"""Calculate cost for token usage"""
if model not in self.model_pricing:
raise ValueError(f"Pricing not configured for model: {model}")
pricing = self.model_pricing[model]
input_cost = (tokens_input / 1000) * pricing['input']
output_cost = (tokens_output / 1000) * pricing['output']
total_cost = input_cost + output_cost
return {
'input_cost': input_cost,
'output_cost': output_cost,
'total_cost': total_cost,
'tokens_input': tokens_input,
'tokens_output': tokens_output,
'model': model,
'timestamp': datetime.utcnow()
}
def track_optimization(self, original_tokens: int, optimized_tokens: int,
model: str, project_id: str = 'default') -> Dict:
"""Track cost savings from optimization"""
# Calculate original cost
original_cost_data = self.calculate_cost(original_tokens, 0, model)
optimized_cost_data = self.calculate_cost(optimized_tokens, 0, model)
savings = original_cost_data['total_cost'] - optimized_cost_data['total_cost']
savings_percentage = (savings / original_cost_data['total_cost']) * 100
cost_record = {
'project_id': project_id,
'original_cost': original_cost_data['total_cost'],
'optimized_cost': optimized_cost_data['total_cost'],
'savings': savings,
'savings_percentage': savings_percentage,
'tokens_saved': original_tokens - optimized_tokens,
'model': model,
'timestamp': datetime.utcnow()
}
self.cost_history.append(cost_record)
# Check budgets
self.check_budget_status(project_id, optimized_cost_data['total_cost'])
return cost_record
def set_budget(self, project_id: str, monthly_budget: float,
alert_thresholds: List[float] = [0.5, 0.8, 0.9]):
"""Set budget for a project"""
self.budgets[project_id] = {
'monthly_budget': monthly_budget,
'alert_thresholds': alert_thresholds,
'current_spend': 0.0,
'period_start': datetime.utcnow().replace(day=1, hour=0, minute=0, second=0),
'alerts_sent': set()
}
def check_budget_status(self, project_id: str, cost: float):
"""Check if spending exceeds budget thresholds"""
if project_id not in self.budgets:
return
budget = self.budgets[project_id]
budget['current_spend'] += cost
utilization = budget['current_spend'] / budget['monthly_budget']
for threshold in budget['alert_thresholds']:
alert_key = f"{project_id}_{threshold}"
if utilization >= threshold and alert_key not in budget['alerts_sent']:
self.send_budget_alert(project_id, threshold, utilization)
budget['alerts_sent'].add(alert_key)
def send_budget_alert(self, project_id: str, threshold: float, utilization: float):
"""Send budget alert"""
alert = {
'project_id': project_id,
'threshold': threshold,
'utilization': utilization,
'timestamp': datetime.utcnow(),
'message': f"Budget alert: {project_id} has reached {threshold*100}% of budget"
}
self.alerts.append(alert)
print(f"BUDGET ALERT: {alert['message']}")
def get_cost_report(self, project_id: str = None, days: int = 30) -> Dict:
"""Generate cost analysis report"""
end_date = datetime.utcnow()
start_date = end_date - timedelta(days=days)
# Filter data
filtered_data = [
record for record in self.cost_history
if record['timestamp'] >= start_date and
(project_id is None or record['project_id'] == project_id)
]
if not filtered_data:
return {'error': 'No data found for the specified period'}
df = pd.DataFrame(filtered_data)
# Calculate metrics
total_savings = df['savings'].sum()
total_original_cost = df['original_cost'].sum()
total_optimized_cost = df['optimized_cost'].sum()
avg_savings_percentage = df['savings_percentage'].mean()
optimization_count = len(df)
# Model breakdown
model_stats = df.groupby('model').agg({
'savings': 'sum',
'savings_percentage': 'mean',
'original_cost': 'sum'
}).to_dict()
# Daily trends
df['date'] = pd.to_datetime(df['timestamp']).dt.date
daily_stats = df.groupby('date').agg({
'savings': 'sum',
'original_cost': 'sum',
'optimized_cost': 'sum'
}).to_dict()
return {
'period': f"{start_date.date()} to {end_date.date()}",
'summary': {
'total_savings': total_savings,
'total_original_cost': total_original_cost,
'total_optimized_cost': total_optimized_cost,
'avg_savings_percentage': avg_savings_percentage,
'optimization_count': optimization_count,
'avg_cost_per_optimization': total_optimized_cost / optimization_count
},
'model_breakdown': model_stats,
'daily_trends': daily_stats,
'roi_metrics': {
'cost_avoidance': total_savings,
'efficiency_gain': avg_savings_percentage,
'processing_volume': optimization_count
}
}
def export_cost_data(self, filename: str, format: str = 'csv'):
"""Export cost tracking data"""
df = pd.DataFrame(self.cost_history)
if format == 'csv':
df.to_csv(filename, index=False)
elif format == 'json':
df.to_json(filename, orient='records', date_format='iso')
elif format == 'excel':
df.to_excel(filename, index=False)
return f"Data exported to {filename}"
# Usage example
model_pricing = {
'gpt-4o': {'input': 0.0025, 'output': 0.01},
'claude-3.5-sonnet': {'input': 0.003, 'output': 0.015},
'gpt-4': {'input': 0.003, 'output': 0.006}
}
cost_tracker = WebMCPCostTracker(model_pricing)
# Set budgets
cost_tracker.set_budget('ecommerce', 2000.0, [0.5, 0.8, 0.9])
cost_tracker.set_budget('auth', 500.0, [0.7, 0.9])
# Track optimization
cost_record = cost_tracker.track_optimization(
original_tokens=1500,
optimized_tokens=485,
model='gpt-4o',
project_id='ecommerce'
)
print(f"Saved ${cost_record['savings']:.4f} (${cost_record['savings_percentage']:.1f}%)")
# Generate report
report = cost_tracker.get_cost_report(project_id='ecommerce', days=30)
print("Cost Report:", report['summary'])
# Export data
cost_tracker.export_cost_data('cost_analysis.csv')
Budgeting Strategies
Proven strategies for managing webMCP costs and maximizing ROI
Project-Based Budgeting
Allocate budgets per project or application
Benefits:
- Clear cost attribution
- Project-level accountability
- Easier ROI calculation
Implementation:
Set monthly/quarterly budgets for each project with automatic tracking
Usage-Based Budgeting
Budget based on expected usage patterns
Benefits:
- Scales with demand
- Predictable cost structure
- Natural cost optimization
Implementation:
Monitor usage patterns and set budgets based on historical data
Value-Based Budgeting
Budget allocation based on business value generated
Benefits:
- Aligns costs with revenue
- Prioritizes high-value projects
- ROI-focused approach
Implementation:
Calculate revenue impact and allocate budgets proportionally
Cost-Plus Budgeting
Set budgets with built-in optimization targets
Benefits:
- Encourages optimization
- Built-in cost reduction goals
- Performance incentives
Implementation:
Add percentage buffer above baseline costs with reduction targets
Maximize Your Cost Efficiency
Start tracking costs and optimizing your webMCP spending for maximum ROI