Skip to main content
Back to all articles
AI Engineering 6 min readUpdated August 31, 2026

MCP Does Not Mean Every Tool Belongs in Every Prompt

Large MCP installations can waste context on tool schemas and intermediate results. A host-side design for progressive discovery, schema caching, and sandboxed programmatic execution that keeps the model focused on reasoning.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#mcp#ai-agents#tool-calling#context-engineering#sandboxing#typescript#python
On this page

Connecting an MCP server is easy. Connecting ten of them without turning the model's context into a catalog of APIs is a different problem.

A general-purpose engineering assistant may have access to GitHub, issue tracking, monitoring, databases, cloud infrastructure, documentation, and internal admin systems. If every server contributes every tool definition to every model call, the prompt starts paying for capabilities that have nothing to do with the current task.

The problem gets worse when a task chains tools. A log query returns thousands of records, the entire result enters model context, the model extracts three values, then sends those values to another tool. The model became an expensive data pipe between two systems.

The current MCP client guidance explicitly describes two useful patterns for this: progressive discovery, where clients load detailed tool definitions only when they are needed, and programmatic tool calling, where model-authored code can compose multiple tools inside a sandbox so intermediate results do not all have to pass through the model context.

Those patterns fit a broader engineering principle I use for agent systems: capability availability, prompt representation, and execution authority should be separate concerns.

The tool registry can be large without the prompt being large

The host may know about hundreds of tools. The model does not need the full JSON Schema for all of them at once.

I keep a compact catalog outside the prompt:

TypeScript
type ToolCatalogEntry = {  qualifiedName: string;  serverId: string;  title: string;  description: string;  keywords: string[];  definitionVersion: string;};​interface ToolCatalog {  search(query: string, limit: number): Promise<ToolCatalogEntry[]>;  getDefinition(qualifiedName: string): Promise<McpToolDefinition>;}

The always-visible model surface can be as small as two meta-tools:

TypeScript
type SearchToolsInput = {  query: string;  limit?: number;};​type InspectToolInput = {  qualifiedName: string;};

A request such as “find the production errors for checkout and open one issue per unique signature” first searches the capability catalog. The model may discover a logging search tool and an issue-creation tool. Only then does it inspect their full schemas.

This is substantially different from asking the model to scan 150 schemas before deciding what it needs.

Discovery is retrieval, so rank it like retrieval

A capability search index can be simple at first.

For a modest installation, keywords and full-text search over tool names/descriptions may be enough. For a large heterogeneous catalog, semantic search can help connect user language to unfamiliar tool names.

I still prefer a hybrid approach because exact system names matter:

TypeScript
async function searchToolCatalog(  query: string,  limit = 8,): Promise<ToolCatalogEntry[]> {  const [lexical, semantic] = await Promise.all([    lexicalToolSearch(query, limit * 2),    semanticToolSearch(query, limit * 2),  ]);​  return fuseToolRanks(lexical, semantic).slice(0, limit);}

The catalog result should stay intentionally small: name, server, one-line purpose, perhaps risk class. Full parameter descriptions and schemas come later.

This is the same candidate-generation versus detail-loading split that works well in RAG.

Cache definitions in the host, not by duplicating them in conversation history

Once a tool definition has been fetched from a server, the host can cache it according to the protocol and server's change signals.

That is different from keeping the schema permanently in every model request.

TypeScript
type CachedDefinition = {  definition: McpToolDefinition;  expiresAt: number;  version: string;};​class ToolDefinitionCache {  private readonly entries = new Map<string, CachedDefinition>();​  get(name: string, now = Date.now()): McpToolDefinition | undefined {    const entry = this.entries.get(name);    if (!entry || entry.expiresAt <= now) return undefined;    return entry.definition;  }​  set(name: string, value: CachedDefinition): void {    this.entries.set(name, value);  }​  invalidateServer(serverId: string): void {    for (const [name, entry] of this.entries) {      if (entry.definition.serverId === serverId) {        this.entries.delete(name);      }    }  }}

When a server reports that its tool list changed, re-index the relevant catalog entries and invalidate definitions that may no longer be current.

The model should see the current interface; the network should not need to rediscover it on every turn.

Keep authorization independent from discovery

A tool that is absent from search results should still be protected at execution time.

Discovery can be permission-aware—there is little value in showing a read-only user an admin-only deletion tool—but hiding a tool is not authorization.

The host broker still validates the authenticated actor and the specific action when a call arrives.

TypeScript
type ToolExecutionContext = {  userId: string;  tenantId: string;  runId: string;  grantedScopes: Set<string>;};​async function brokerToolCall(  context: ToolExecutionContext,  name: string,  args: unknown,): Promise<unknown> {  const definition = await resolveDefinition(name);  authorizeToolCall(context, definition, args);  validateArguments(definition.inputSchema, args);  return mcpClient.callTool(name, args);}

Progressive discovery reduces context overhead. The broker remains the security boundary.

Direct calls are fine until the model becomes a data bus

Consider this workflow:

  1. search error logs from the last hour;
  2. group them by normalized signature;
  3. count occurrences;
  4. create one issue for each signature above a threshold.

With ordinary model-mediated calls, step 1 can push thousands of log lines into context just so the model can run a deterministic grouping operation.

That is a poor use of model tokens.

A programmatic execution mode can instead expose typed tool stubs inside an isolated runtime:

TypeScript
type LogEntry = {  timestamp: string;  service: string;  message: string;};​declare function searchLogs(input: {  service: string;  since: string;}): Promise<{ entries: LogEntry[] }>;​declare function createIssue(input: {  title: string;  body: string;}): Promise<{ id: string }>;

The model can generate a small program:

TypeScript
const result = await searchLogs({  service: "checkout-api",  since: oneHourAgo,});​const groups = new Map<string, LogEntry[]>();​for (const entry of result.entries) {  const signature = normalizeError(entry.message);  const current = groups.get(signature) ?? [];  current.push(entry);  groups.set(signature, current);}​const created: string[] = [];​for (const [signature, entries] of groups) {  if (entries.length < 3) continue;​  const issue = await createIssue({    title: `Recurring checkout error: ${signature}`,    body: `${entries.length} occurrences in the last hour`,  });​  created.push(issue.id);}​return {  scanned: result.entries.length,  issuesCreated: created,};

The large log payload stays inside the execution environment. The model receives the compact final result.

The point is not that every task should become generated code. It is that deterministic data transformation does not always need another model round trip.

The sandbox must have less authority than the host

Programmatic tool calling creates a code-execution surface, so I do not run generated code inside the main application process.

The sandbox should have:

  • no direct network access;
  • no application credentials;
  • no host filesystem access except explicitly mounted temporary data;
  • CPU, memory, and wall-clock limits;
  • only generated tool stubs as external capabilities.

The host intercepts calls to those stubs and brokers them to MCP servers.

That architecture gives the generated code something like:

Text
searchLogs(...)createIssue(...)

but not:

Text
process.env.PRODUCTION_DATABASE_URLfetch("https://arbitrary-host.example")

Credentials stay in the broker.

A script is not blanket approval

There is an easy security mistake here: approve the generated script once and assume every call it makes is now authorized.

I would not do that.

The broker evaluates each call against the grant for this run. If a user approved “create issues in project OPS,” the script should not gain permission to create records somewhere else because it happened to discover another tool.

TypeScript
type ExecutionGrant = {  allowedTools: Set<string>;  projectId?: string;  maxWriteCalls: number;};​function enforceGrant(  grant: ExecutionGrant,  toolName: string,  writeCallsSoFar: number,): void {  if (!grant.allowedTools.has(toolName)) {    throw new Error(`Tool ${toolName} is outside the execution grant`);  }​  if (writeCallsSoFar >= grant.maxWriteCalls) {    throw new Error("Write-call budget exhausted");  }}

The generated program is untrusted orchestration code. It does not get to expand its own capabilities.

Python host-side discovery looks similar

The catalog is a host concern, so either ecosystem can implement it without changing MCP servers.

Python
from dataclasses import dataclassfrom typing import Protocol​@dataclass(frozen=True)class ToolCatalogEntry:    qualified_name: str    server_id: str    title: str    description: str    keywords: tuple[str, ...]​class ToolCatalog(Protocol):    async def search(        self,        query: str,        limit: int,    ) -> list[ToolCatalogEntry]: ...​    async def get_definition(self, qualified_name: str) -> dict: ...​async def discover_for_task(    catalog: ToolCatalog,    task: str,) -> list[ToolCatalogEntry]:    candidates = await catalog.search(task, limit=8)    return candidates

I would then validate any selected definition and its arguments at the broker boundary just as I would in TypeScript.

Stable tool surfaces can help prompt caching

Progressive discovery has a tradeoff: changing the tool array every turn can disturb provider-side prefix caching.

A host can avoid constant reshuffling by keeping a small stable set of meta-tools—search, inspect, and perhaps a brokered call_tool interface—while detailed definitions are loaded in a controlled section or used inside the sandbox.

The exact strategy depends on the model provider and client architecture. The important thing is to measure both effects: tool-definition tokens saved and prompt-cache hit rate.

An optimization that saves 5,000 schema tokens but destroys a much larger cached prefix may be a loss.

Output schemas matter more in programmatic mode

Generated code works best when tool results have reliable types.

MCP tools can expose output schemas. When they do, the host can generate precise stubs and validate returned structured data.

When a server only returns unstructured text, I prefer to keep the wrapper honest:

TypeScript
declare function legacySearch(input: { query: string }): Promise<string>;

I would not invent a rich TypeScript type and pretend the server guarantees it.

If downstream code needs structure, parse and validate it explicitly. Better yet, improve the server contract.

Progressive discovery does not excuse poor tool design

A catalog can hide a bad schema until later, but the model still has to understand it when selected.

Tools benefit from:

  • specific names;
  • concise descriptions that distinguish neighboring actions;
  • narrow schemas;
  • explicit required fields;
  • bounded result sizes;
  • stable structured output where possible;
  • clear execution errors.

If six tools all say “manage customer data,” retrieval will not know which one is appropriate either.

When loading every tool is perfectly fine

If an agent has eight small, frequently used tools, progressive discovery may create unnecessary round trips. A stable tool set is easier to reason about and may cache well.

The pattern earns its complexity when capability count becomes large, tools come from many servers, schemas are verbose, or only a small fraction is relevant to each task.

Programmatic execution is similarly situational. For one or two tool calls, direct model-mediated calls are simpler and more observable. Code mode helps when a workflow contains deterministic loops, joins, filtering, or large intermediate data that the model does not need to read.

MCP makes capabilities interoperable. It does not require every capability to occupy permanent model context, and it does not require every intermediate byte to travel through the model.

A scalable host treats the protocol like any other integration layer: discover lazily, cache contracts, broker permissions, keep credentials outside untrusted execution, and move deterministic data work closer to the tools that own the data.

KEEP READING

Related engineering notes