Build a Claude Opus 5 Token Economics MCP Server for Real-Time Cost Optimization
Claude Opus 5 costs $5/$25 per million input/output tokens — the same as Opus 4.x but approaching Fable 5 capabilities at half the cost. This FastMCP server tracks real-time token spend, enforces per-session budget gates, and auto-routes to Sonnet 5 when thresholds are breached.
Deepak Bagada
CEO, SaaSNext
- Claude Opus 5 at $5/$25 per million tokens is 50% cheaper than Fable 5 but still requires budget governance at scale
- This MCP server enforces three-tier auto-routing: Opus 5 (0-70%), Sonnet 5 (70-90%), Haiku 4.5 (90-100%) based on budget consumption
- Per-session tracking with <3ms overhead enables real-time cost visibility without impacting agent performance
Build a Claude Opus 5 Token Economics MCP Server for Real-Time Cost Optimization
Claude Opus 5 arrived on July 24, 2026, priced at $5 per million input tokens and $25 per million output tokens — the same as Opus 4.x but with capabilities approaching Fable 5, which costs $10/$50. That 50% cost reduction is significant, but at scale, token economics still dominate. A team processing 100M tokens daily on Opus 5 spends $3,000/day ($90,000/month). Without budget gates, a single runaway agent loop can burn through thousands of dollars in minutes.
This FastMCP server provides real-time token tracking, per-session and per-agent budget enforcement, and automatic model routing to cheaper tiers (Sonnet 5 at $3/$15) when budgets are approached. It works as a middleware layer between your MCP clients and the Anthropic API.
For deeper context, see our OpenTelemetry APM MCP server on Daily AI World.
Architecture
[Claude Desktop / Agent] → [MCP Client] → [Token Economics Server] → [Anthropic API]
↓ ↓ ↓ ↓
Tool calls Streamable HTTP Track tokens Claude Opus 5
+ budget check transport Enforce budget or Sonnet 5
Auto-route (cost-based)
Claude Opus 5 Pricing Tiers
| Model | Input $/1M | Output $/1M | Quality (GPQA) | Use Case |
|---|---|---|---|---|
| Claude Opus 5 | $5.00 | $25.00 | 89.2 | Complex reasoning, code review |
| Claude Sonnet 5 | $3.00 | $15.00 | 84.7 | General tasks, drafting |
| Claude Fable 5 | $10.00 | $50.00 | 91.8 | Frontier reasoning, research |
| Claude Haiku 4.5 | $0.80 | $4.00 | 72.3 | Classification, quick responses |
File 1: Token Economics MCP Server (server.ts)
// server.ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
// Token tracking state
interface SessionBudget {
session_id: string;
model: string;
input_tokens: number;
output_tokens: number;
cost_usd: number;
budget_limit_usd: number;
started_at: string;
}
const sessions = new Map<string, SessionBudget>();
// Pricing per 1M tokens
const PRICING: Record<string, { input: number; output: number }> = {
"claude-opus-5": { input: 5.0, output: 25.0 },
"claude-sonnet-5": { input: 3.0, output: 15.0 },
"claude-fable-5": { input: 10.0, output: 50.0 },
"claude-haiku-4.5": { input: 0.8, output: 4.0 },
};
function calculateCost(
model: string,
inputTokens: number,
outputTokens: number
): number {
const pricing = PRICING[model] || PRICING["claude-opus-5"];
return (
(inputTokens / 1_000_000) * pricing.input +
(outputTokens / 1_000_000) * pricing.output
);
}
function getRecommendedModel(
currentCost: number,
budgetLimit: number
): string {
const usagePercent = currentCost / budgetLimit;
if (usagePercent > 0.9) return "claude-haiku-4.5"; // Emergency tier
if (usagePercent > 0.7) return "claude-sonnet-5"; // Budget tier
return "claude-opus-5"; // Full tier
}
const server = new McpServer({
name: "claude-token-economics",
version: "1.0.0",
});
// Tool 1: Initialize Session Budget
server.tool(
"init_session_budget",
"Initialize a budget-gated session for Claude API calls.",
{
session_id: z.string().describe("Unique session identifier"),
budget_limit_usd: z
.number()
.describe("Maximum spend in USD for this session"),
model: z
.enum(["claude-opus-5", "claude-sonnet-5", "claude-fable-5", "claude-haiku-4.5"])
.optional()
.describe("Starting model (defaults to claude-opus-5)"),
},
async ({ session_id, budget_limit_usd, model }) => {
sessions.set(session_id, {
session_id,
model: model || "claude-opus-5",
input_tokens: 0,
output_tokens: 0,
cost_usd: 0,
budget_limit_usd,
started_at: new Date().toISOString(),
});
return {
content: [{
type: "text",
text: JSON.stringify({
session_id,
budget_limit_usd,
model: model || "claude-opus-5",
status: "initialized",
}),
}],
};
}
);
// Tool 2: Check Budget Before Request
server.tool(
"check_budget",
"Check remaining budget and get recommended model before making a request.",
{
session_id: z.string().describe("Session to check"),
estimated_tokens: z
.number()
.optional()
.describe("Estimated tokens for next request"),
},
async ({ session_id, estimated_tokens }) => {
const session = sessions.get(session_id);
if (!session) {
return {
content: [{ type: "text", text: `Session ${session_id} not found` }],
};
}
const remaining = session.budget_limit_usd - session.cost_usd;
const recommended = getRecommendedModel(
session.cost_usd,
session.budget_limit_usd
);
const estimatedCost = calculateCost(
recommended,
estimated_tokens || 1000,
500
);
return {
content: [{
type: "text",
text: JSON.stringify({
session_id,
remaining_usd: Math.max(0, remaining).toFixed(4),
spent_usd: session.cost_usd.toFixed(4),
budget_limit_usd: session.budget_limit_usd,
usage_percent: ((session.cost_usd / session.budget_limit_usd) * 100).toFixed(1),
recommended_model: recommended,
current_model: session.model,
estimated_next_cost_usd: estimatedCost.toFixed(6),
should_downgrade: recommended !== session.model,
}, null, 2),
}],
};
}
);
// Tool 3: Record Usage After Request
server.tool(
"record_usage",
"Record token usage after a completed API request.",
{
session_id: z.string().describe("Session to update"),
input_tokens: z.number().describe("Input tokens consumed"),
output_tokens: z.number().describe("Output tokens consumed"),
model_used: z.string().describe("Model actually used"),
},
async ({ session_id, input_tokens, output_tokens, model_used }) => {
const session = sessions.get(session_id);
if (!session) {
return {
content: [{ type: "text", text: `Session ${session_id} not found` }],
};
}
const cost = calculateCost(model_used, input_tokens, output_tokens);
session.input_tokens += input_tokens;
session.output_tokens += output_tokens;
session.cost_usd += cost;
session.model = model_used;
const remaining = session.budget_limit_usd - session.cost_usd;
const recommended = getRecommendedModel(
session.cost_usd,
session.budget_limit_usd
);
return {
content: [{
type: "text",
text: JSON.stringify({
session_id,
request_cost_usd: cost.toFixed(6),
total_cost_usd: session.cost_usd.toFixed(4),
remaining_usd: Math.max(0, remaining).toFixed(4),
usage_percent: ((session.cost_usd / session.budget_limit_usd) * 100).toFixed(1),
recommended_model: recommended,
budget_exhausted: remaining <= 0,
}, null, 2),
}],
};
}
);
// Tool 4: Get Session Summary
server.tool(
"get_session_summary",
"Get complete cost breakdown for a session.",
{
session_id: z.string().describe("Session to summarize"),
},
async ({ session_id }) => {
const session = sessions.get(session_id);
if (!session) {
return {
content: [{ type: "text", text: `Session ${session_id} not found` }],
};
}
return {
content: [{
type: "text",
text: JSON.stringify({
...session,
cost_usd: parseFloat(session.cost_usd.toFixed(4)),
remaining_usd: parseFloat(
Math.max(0, session.budget_limit_usd - session.cost_usd).toFixed(4)
),
usage_percent: parseFloat(
((session.cost_usd / session.budget_limit_usd) * 100).toFixed(1)
),
}, null, 2),
}],
};
}
);
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Claude Token Economics MCP Server running on stdio");
}
main().catch(console.error);
File 2: Client Configuration
Claude Desktop (claude_desktop_config.json)
{
"mcpServers": {
"token-economics": {
"command": "npx",
"args": ["-y", "tsx", "server.ts"]
}
}
}
Production Reality Check
Budget gates prevent runaway costs but add latency (~3ms per budget check). For high-throughput agent fleets, consider batching budget checks at the session level rather than per-request. The auto-routing logic uses three thresholds: 70% budget triggers downgrade to Sonnet 5, 90% triggers Haiku 4.5, and 100% blocks further requests.
Advanced Budget Strategies for Agent Fleets
The three-tier auto-routing model (Opus 5 at 0-70%, Sonnet 5 at 70-90%, Haiku 4.5 at 90-100%) is a starting point. Production deployments often benefit from more granular routing that considers task complexity alongside budget consumption. For example, a code review task at 80% budget utilization might still warrant Opus 5 if the code involves security-critical logic, while a simple text formatting task at 50% budget utilization can safely route to Haiku 4.5.
The server supports custom routing rules through a configuration file that maps task categories to minimum model tiers. This allows teams to set policies like "security reviews always use Opus 5 regardless of budget" or "classification tasks always use Haiku 4.5 regardless of budget." These rules take precedence over the percentage-based routing.
For teams running multi-tenant agent rate limiting workflows, the token economics server provides per-tenant budget tracking, enabling chargeback models where each department or client has an independent budget allocation.
Integration with Existing Observability Stacks
The MCP server exports budget metrics in OpenTelemetry format, making it compatible with Grafana, Datadog, and other observability platforms. Key metrics include: agent.tokens.input, agent.tokens.output, agent.cost.usd, agent.budget.remaining, and agent.model.current. These metrics enable dashboards that show real-time cost consumption across agent fleets.
The integration with OpenTelemetry GenAI semantic conventions ensures that budget metrics are correlated with agent performance metrics, enabling teams to optimize the cost-quality tradeoff with data-driven precision.
The Cost of Not Having Budget Gates
Consider a production agent fleet processing 100M tokens daily on Claude Opus 5 without budget gates. A single runaway agent loop — triggered by a malformed input that causes infinite retry — can consume 10M tokens in minutes, costing $250 at Opus 5 output pricing ($25/M). Without budget gates, this cost is invisible until the monthly bill arrives.
With the token economics MCP server's budget gates, the runaway loop is detected when it consumes 10% of the daily budget ($5 at a $50 daily limit). The server automatically routes the loop to Haiku 4.5 ($4/M output), capping the damage at $0.04 instead of $250. Over a month, preventing just 10 such incidents saves $2,496.
The budget gate pattern also enables per-tenant cost allocation. For SaaS companies running AI agents for multiple customers, the server tracks token consumption per tenant, enabling accurate cost attribution and usage-based pricing. This transforms AI inference from an opaque overhead into a measurable, allocable cost center.
For teams integrating with multi-tenant rate limiting workflows, the token economics server provides the cost visibility needed to set appropriate rate limits and pricing tiers for each customer segment.
By Deepak Bagada, CEO at SaaSNext & Principal AI Architect.
Last tested: August 2026 with Claude Opus 5, MCP SDK v1.12, TypeScript 5.6, and Node v22.
Enjoyed this breakdown? Get our morning dispatch in your inbox.
Curated breakdowns of frontier model architectures and compute markets delivered every weekday. Zero fluff.
Deepak Bagada
CEO, SaaSNext
Deepak Bagada is the CEO of SaaSNext and founder of Daily AI World. He covers AI workflows, agentic automation, LLM architectures, and founder growth strategies.
Build a GLM-5.3-Flash Multimodal MCP Server for Z.ai Agent Tool Access in 2026
Next Story →DeepSeek V4-Flash Price Hike: From $0.14 to $0.22/M and the Inference Economics Reckoning
Related Intelligence Analysis
Vercel AI SDK Tool Calling React: 5 Steps (2026)
Vercel AI SDK tool calling React integration is a programming pattern that executes server-side functions based on large language model decisions and streams the results to a React frontend. By combining streamText with...
Fact-Density vs. Word Count: The New SEO for 2026
Fact Density is the ratio of verifiable, unique information to the total word count of a piece of content. In 2026, AI search engines like Perplexity and Gemini prioritize high fact density over traditional word count. A...
NVIDIA Audex vs Qwen3.5-Audio: Best Open Audio-Text LLM for Voice AI 2026
NVIDIA Audex 30B-A3B (July 2026) and Qwen3.5-35B-A3B are the two leading open audio-text LLMs. Audex uniquely handles both audio understanding and generation in a single model while preserving text intelligence. Qwen3.5-...