RAG — Context Engineering
Context Engineering for MCP Tool Calls
Direct answer
Every MCP tool you connect costs context: its name, description and JSON schema are loaded into the prompt, and every tool result lands there too. To keep MCP agents fast and accurate, expose only the tools a task needs, write descriptions as routing instructions, return compact structured results with pagination instead of raw dumps, hand large payloads back as resource links, and keep a human able to approve or deny sensitive calls.
The Model Context Protocol made it easy to plug an agent into databases, ticketing systems and internal APIs. It also made it easy to connect forty tools and wonder why the agent got slower, more expensive and worse at picking the right one. This guide covers where MCP spends your context window and the design choices — on the server and the client — that keep it under control.
Key facts, with sources
- Anthropic introduced the Model Context Protocol on November 25, 2024 as an open standard for connecting AI assistants to the systems where data lives, replacing one-off integrations with a single protocol. (Anthropic, Nov 2024)
- The MCP specification (2025-06-18) defines tool discovery via a paginated tools/list request and invocation via tools/call; a tool definition carries a name, description, JSON Schema inputSchema and optional outputSchema and annotations. (MCP specification)
- MCP defines two standard transports — stdio and Streamable HTTP — and Streamable HTTP servers MUST validate the Origin header to prevent DNS rebinding attacks. (MCP specification)
- Anthropic notes most MCP clients load all tool definitions into context up front; in their example, moving tool use into code execution cut token usage from 150,000 to 2,000 tokens — a 98.7% saving. (Anthropic Engineering, Nov 2025)
Where MCP spends your context window
There are three costs, and teams usually notice only the last one. First, tool definitions: when a client connects to servers it calls tools/list and typically places every returned tool — name, description, full input schema — into the model's context before the user says anything. Ten servers with eight tools each is eighty schemas riding along on every single call.
Second, tool selection: the more tools the model can see, the more similar-looking options it has to choose between, and the easier it is to pick search_orders when it needed get_order. Third, tool results: whatever the server returns in a tools/call response goes back into the context, and a tool that returns a 300-row JSON dump will flood the window faster than any amount of conversation. Good MCP design attacks all three.
Write tool definitions as routing instructions
A tool description is not documentation for humans — it is the only signal the model has for deciding when to call the tool. Write it as a routing rule: what the tool does, when to use it, when not to use it, and what it returns. Keep input schemas tight: required fields only where truly required, enums instead of free-text where values are known, and short field descriptions that state formats (ISO dates, cents, IDs).
Prefer a few task-shaped tools over a wrapper around every REST endpoint. One find_order tool that accepts an order ID or customer email is easier for the model than list_orders, get_order, search_orders_by_email and get_customer, and it costs a quarter of the definition tokens.
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("orders")
@mcp.tool()
async def find_order(order_id: str | None = None, email: str | None = None) -> dict:
"""Look up ONE customer order. Use when the user mentions a specific order
number or asks about their own recent order. Not for reports or totals.
Pass order_id if known, otherwise the customer email (returns the latest order).
Returns: id, status, items (name, qty), total_cents, eta (ISO 8601)."""
order = await repo.find(order_id=order_id, email=email)
if order is None:
# A tool-level error the model can recover from, not a crash
raise ValueError("No order found. Ask the user to confirm the order number.")
return {
"id": order.id,
"status": order.status,
"items": [{"name": i.name, "qty": i.qty} for i in order.items[:10]],
"total_cents": order.total_cents,
"eta": order.eta.isoformat() if order.eta else None,
}
if __name__ == "__main__":
mcp.run() # stdio by defaultShape results for the model, not for an API client
Tool results should be the smallest payload that answers the question. Return the handful of fields the model needs instead of the whole database row, cap list lengths and include a cursor or a “more available” flag instead of returning everything, and convert internal codes into readable values so the model doesn't have to guess what status 7 means.
The spec gives you the right primitives. structuredContent returns typed JSON that clients can validate against the tool's outputSchema, with a short text summary alongside for compatibility. isError: true reports a recoverable failure — rate limit hit, record not found — as a normal result the model can react to, instead of a protocol error that ends the turn. And for big artifacts such as a full log file or a generated report, return a resource_link so the client can fetch or show it without pasting the whole thing into the context.
{
"jsonrpc": "2.0",
"id": 7,
"result": {
"content": [
{ "type": "text", "text": "3 failed payments in the last 24h (showing 3 of 3)." },
{
"type": "resource_link",
"uri": "reports://payments/failed/2026-10-23",
"name": "failed-payments.csv",
"mimeType": "text/csv"
}
],
"structuredContent": {
"count": 3,
"failures": [
{ "id": "pay_81", "reason": "card_declined", "amount_cents": 4200 },
{ "id": "pay_84", "reason": "expired_card", "amount_cents": 1900 },
{ "id": "pay_90", "reason": "card_declined", "amount_cents": 7550 }
],
"next_cursor": null
},
"isError": false
}
}Scope the toolset to the task
The cheapest tool definition is the one you never send. Most agents don't need every tool on every turn: a billing question needs billing tools, a bug triage flow needs tickets and logs. The client is where this gets decided, and there are a few common patterns with different trade-offs.
| Pattern | How it works | Good for | Trade-off |
|---|---|---|---|
| Static subset | Each agent or flow is configured with a fixed allow-list of tools | Focused assistants, most products | Needs a new config per flow |
| Router step | A cheap first call classifies the task, then only that group's tools are loaded | Assistants with distinct domains | One extra model call per turn |
| Tool search | The model sees a search tool and loads matching tool definitions on demand | Very large tool catalogs | Discovery can miss the right tool |
| Code execution | The model writes code that calls MCP tools; only the final output returns to context | Data-heavy, multi-step work | Needs a secure sandbox to run code |
Safety is part of the context design
Tool results are untrusted input. A support ticket, a web page or a document fetched by a tool can contain text written to look like instructions, and once it lands in the context the model may follow it. Treat every tool result as data: keep it clearly delimited, don't let one tool's output trigger a sensitive second tool without a check, and strip or summarize content from sources you don't control.
The specification is explicit on the rest. Servers must validate inputs, enforce access control, rate-limit invocations and sanitize outputs. Clients should show users which tools are exposed, display tool inputs before sending them, ask for confirmation on sensitive operations, time out slow calls and log tool use for audit — and must treat tool annotations from untrusted servers as untrusted. For Streamable HTTP servers, validate the Origin header and bind local servers to 127.0.0.1, not 0.0.0.0.
Measure what each tool costs
Before trimming anything, measure. Count the tokens in each tool definition and in a typical result, then multiply by how often they appear in real traffic. It usually turns out that two or three verbose tools or one chatty result format account for most of the overhead, and fixing those beats any architectural change.
import json
import tiktoken
enc = tiktoken.get_encoding("o200k_base")
def tool_costs(tools: list[dict]) -> list[tuple[str, int]]:
costs = [(t["name"], len(enc.encode(json.dumps(t)))) for t in tools]
return sorted(costs, key=lambda c: c[1], reverse=True)
for name, tokens in tool_costs(listed_tools):
print(f"{tokens:>6} {name}")
print("total:", sum(t for _, t in tool_costs(listed_tools)))When to hire senior help
Context engineering expertise pays off when agent or RAG quality regresses at scale, such as degraded answers in long sessions or ballooning token bills, because the fixes involve caching structure, compaction, and retrieval budgets rather than model swaps. A senior review of your context layout can often cut inference spend substantially while improving accuracy, which quickly recovers the cost of the engagement. If your stack includes React Native + Python + AI, a senior engineer who owns the full product beats coordinating multiple juniors.
Bottom line
Dhairya Senjaliya ships RAG — Context Engineering projects worldwide — book a scoping call to discuss your specific situation.
Common pitfalls to avoid
- ✕Stuffing the full document set into a million-token window and assuming accuracy holds, when Chroma measured degradation starting around 50K tokens.
- ✕Placing the most important instructions or evidence mid-prompt, exactly where lost-in-the-middle effects hit hardest.
- ✕Rebuilding the entire prompt on every call instead of structuring stable prefixes for prompt caching, paying 10x more input cost than necessary.
- ✕Fixing missed answers by retrieving more chunks, which increases distractor interference and often lowers answer quality instead of raising it.
Frequently asked questions
Why does my agent get worse as I add more MCP servers?
Each server adds tool definitions to the context and more similar-looking choices for the model. Past a certain point, selection accuracy drops and every call gets slower and more expensive. Scope tools per task and merge overlapping tools.
Should an MCP tool return JSON or text?
Both, ideally: structuredContent with typed JSON that matches an outputSchema, plus a short text summary in content for clients that only read text. Keep both compact — return the fields the model needs, not the full record.
How should MCP tools report errors?
Use a normal result with isError: true for recoverable problems like a missing record or rate limit, so the model can adjust. Reserve JSON-RPC protocol errors for unknown tools or invalid arguments.
Is MCP safe to connect to production data?
It can be, with the controls the spec calls for: server-side input validation and access control, rate limits, human confirmation for sensitive operations, audit logs, and treating all tool output as untrusted data that can't override your instructions.
stdio or Streamable HTTP — which transport should I use?
stdio for local tools launched by the client as a subprocess; Streamable HTTP for shared, remote servers that serve many clients. Remote servers need authentication and Origin validation.
With million-token context windows, is RAG obsolete?
No: a 2026 benchmark measured long-context prompting at roughly 26 times the per-query cost of RAG, and Chroma's research shows accuracy degrades as inputs grow regardless of advertised window size. Long context is useful for single-document analysis, while retrieval remains cheaper and more reliable for large or frequently changing corpora.
What is context engineering versus prompt engineering?
Prompt engineering focuses on instruction wording; context engineering manages everything occupying the model's context window, including retrieved documents, tool outputs, conversation history, and memory. In agent systems it covers compaction, note-taking, and sub-agent isolation to keep the window under control over long sessions.
How much context should we give the model per query?
Only what earns its place: retrieval studies consistently show a handful of high-relevance chunks beats large dumps, because semantically similar but irrelevant text actively misleads models. Measure with an evaluation set as you vary retrieved chunk count, since the optimum differs by task and corpus.
Bottom line: Dhairya Senjaliya ships RAG — Context Engineering projects worldwide. Book a scoping call at https://dhairyasenjaliya.com/#book-call.