MCP Context Caching and Prompt Compression
Drastically reduce API costs and latency by combining Anthropic Prompt Caching, OpenAI Prefix Caching, and MCP tool schema compression.
Generate & Validate Multi-Client MCP Config
One-click export with environment variables & path locators for Claude Desktop, Cursor, Windsurf, and OpenAI Codex CLI.
MCP Context Caching and Prompt Compression
As developers connect autonomous agents to 10+ Model Context Protocol (MCP) servers simultaneously (databases, Slack, GitHub, Jira, AWS, Sentry), tool definitions alone can consume 15,000 to 40,000 tokens before the user prompt is even evaluated. In a 20-turn agent session, repeatedly transmitting these massive JSON schemas inflates latency to 5+ seconds per turn and balloons LLM API costs.
By implementing Prompt Caching (Anthropic Ephemeral Cache, OpenAI Prefix Caching, Gemini Context Caching) and Dynamic Tool Schema Compression, teams can slash token consumption by up to 80% and cut time-to-first-token (TTFT) by 70%.
This guide provides the exact configuration recipes and token-stripping algorithms required to optimize production MCP deployments.
1. The Cost & Latency Bottleneck
When an agent communicates with MCP servers:
┌────────────────────────────────────────────────────────┐
│ Turn 1: 25,000 tokens (Tool Schemas) + 200 user tokens │
├────────────────────────────────────────────────────────┤
│ Turn 2: 25,000 tokens (Tool Schemas) + 1,200 tokens │
├────────────────────────────────────────────────────────┤
│ ... │
├────────────────────────────────────────────────────────┤
│ Turn 20: 25,000 tokens + 15,000 history tokens │
└────────────────────────────────────────────────────────┘
Cumulative Uncached Cost: ~650,000 input tokens per session!By placing static MCP tool definitions behind a Cache Breakpoint, the model reuses pre-computed KV-cache states on every subsequent turn at a 90% discount.
2. Implementing Anthropic Prompt Caching with MCP
To enable prompt caching in Claude Desktop or custom SDK implementations, inject the cache_control: { "type": "ephemeral" } header on the last tool declaration:
# cached_mcp_client.py
import anthropic
from typing import List, Dict, Any
def prepare_cached_mcp_tools(mcp_tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""
Format MCP tools for Anthropic API and place an ephemeral cache breakpoint
at the end of the tool catalog.
"""
formatted_tools = []
for i, tool in enumerate(mcp_tools):
tool_def = {
"name": tool["name"],
"description": tool.get("description", ""),
"input_schema": tool.get("inputSchema", {})
}
# Apply cache breakpoint to the final tool definition
if i == len(mcp_tools) - 1:
tool_def["cache_control"] = {"type": "ephemeral"}
formatted_tools.append(tool_def)
return formatted_tools
client = anthropic.Anthropic()
def execute_agent_turn(messages: list, mcp_tools: list):
cached_tools = prepare_cached_mcp_tools(mcp_tools)
response = client.messages.create(
model="claude-3-7-sonnet-20250219",
max_tokens=2048,
tools=cached_tools,
messages=messages
)
# Inspect cache read hits
usage = response.usage
print(f"Tokens written to cache: {getattr(usage, 'cache_creation_input_tokens', 0)}")
print(f"Tokens read from cache: {getattr(usage, 'cache_read_input_tokens', 0)}")
return response3. Dynamic Tool Schema Compression
Beyond caching, you can compress JSON Schema definitions by stripping unnecessary metadata properties (title, $schema, examples, redundant descriptions) before sending them over the wire:
// schema-compressor.ts
export function compressMcpToolSchema(rawTool: any): any {
const schema = { ...rawTool.inputSchema };
// Recursive stripper for JSON Schema bloat
function stripBloat(obj: any): any {
if (!obj || typeof obj !== "object") return obj;
if (Array.isArray(obj)) return obj.map(stripBloat);
const cleaned: any = {};
for (const [key, value] of Object.entries(obj)) {
// Discard cosmetic schema keys not needed for LLM argument parsing
if (["title", "$schema", "examples", "default"].includes(key)) {
continue;
}
cleaned[key] = stripBloat(value);
}
return cleaned;
}
return {
name: rawTool.name,
description: rawTool.description?.substring(0, 160) || "",
input_schema: stripBloat(schema)
};
}4. Benchmark Results
| Metric | Uncompressed / Uncached | Cached + Compressed MCP | Improvement |
|---|---|---|---|
| Tool Payload Tokens | 28,400 tokens | 11,200 tokens | 60.5% reduction |
| Cost per 15-Turn Session | $1.92 | $0.28 | 85.4% savings |
| Average Latency (TTFT) | 3.4 seconds | 0.9 seconds | 73.5% faster |
Applying prompt caching and schema compression transforms multi-server MCP setups from sluggish, expensive experiments into responsive production systems.
Build your full agent toolstack in the Visual Generator
Combine MCP Context Caching and Prompt Compression with databases, search APIs, and memory graphs in a single configuration file.
Did this setup guide work with your AI host?
Real-time developer votes ensure configurations stay current across client updates.
MCP Context Caching and Prompt Compression FAQ
What is the MCP Context Caching and Prompt Compression?
Drastically reduce API costs and latency by combining Anthropic Prompt Caching, OpenAI Prefix Caching, and MCP tool schema compression.
How do I configure MCP Context Caching and Prompt Compression in Claude Desktop or Cursor?
You can copy the configuration JSON from our guide or launch the interactive MCP Codex Config Generator at https://mcp-codex.com/generator to export valid configs in 1 click.
Can I use MCP Context Caching and Prompt Compression with the OpenAI Codex CLI?
Yes, OpenAI Codex CLI supports Model Context Protocol. You can add it directly to ~/.codex/config.toml or pass arguments to codex mcp add.
Specializing in Model Context Protocol (MCP) integrations, autonomous AI agent orchestration, and distributed developer toolchains. Researches and benchmarks production MCP client-server architectures across OpenAI Codex, Claude, and Cursor.
Related Guides
Reinforcement Learning for MCP Tool Calling
Train open-weight models (Llama 3.3, Qwen 2.5, DeepSeek R1) on multi-turn Model Context Protocol tool execution using Group Relative Policy Optimization (GRPO).
AI FrameworksGEM Framework: Agentic RL and MCP Environments
Integrate the General Experience Maker (GEM) framework with Model Context Protocol (MCP) servers to train and benchmark agentic LLMs via reinforcement learning.
AI FrameworksHow to Use the Memory MCP Server for Persistent AI Knowledge
Give your AI agent persistent memory using the Knowledge Graph MCP server. Store and retrieve information across conversations.