Loading Tools and Skills on Demand
Keep the working context lean: load tool definitions on demand with permission checks in the dispatcher, show instruction skills as a name and summary until one is needed, and run broad sub-tasks in a separate context that returns a short structured result.
Contentsand lesson path
On this page
- The Problem: Everything Loaded on Every Call
- Step 1: Load Tool Definitions on Demand
- Tool Lifecycle: Unloading, Bundles and Access
- Step 2: The Dispatcher Refuses What the Prompt Never Offered
- Step 3: Instruction Skills with Progressive Disclosure
- Step 4: Isolate a Broad Sub-Task in Its Own Context
- Practice
- Apply it
- Review prompt
Lessons of Memory & Context Engineering
- Context as a Scarce Resource Concept · 15 min
- Building a Per-Step Context Assembler Worked example · 20 min
- Lab: Compaction for a Fifty-Step Task Lab · 25 min
- Loading Tools and Skills on Demand Worked example · 15 min
- A Long-Term Memory Store with Write and Expiry Policies Lab · 25 min
- Check: Context and Memory Design Review Knowledge check · 8 questions
What you will learn
- Reduce context load by loading tools, instructions or skills on demand and by isolating sub-tasks in separate contexts.
Prerequisites: Tokens & Context
01. The Problem: Everything Loaded on Every Call
A prototype agent usually sends every tool definition, every instruction and every intermediate result on every call. With five tools that works. As the agent grows, three things crowd the window. Tool definitions are verbose: a schema with typed parameters and descriptions often takes a few hundred tokens, so 80 tools can cost tens of thousands of tokens before the user has said anything. Instructions grow too: procedures for refunds, deployments or reports pile up in the system prompt. And broad sub-tasks, such as searching a codebase, leave dozens of raw reads in the history.
More is not only more expensive. With many similar tools (query_user_db, search_customer_profile, lookup_account_v2) the model picks the wrong one more often, and irrelevant text distracts it.
This lesson works through three fixes, one per section: load tools on demand, load instruction skills on demand, and run sub-tasks in their own context.
02. Step 1: Load Tool Definitions on Demand
Three patterns load tools on demand:
- Tool search. The agent starts with a few core tools plus
discover_tools(query). When it needs, say, a database query, it searches the catalog and the runtime adds the matching definitions for the next steps. - Phase scoping. In a structured workflow the orchestrator knows the phase: search and inspection tools while discovering, change tools while executing, linters and tests while verifying.
- Routing. A small classifier or embedding search picks the few most relevant tools for the current step before the main model runs.
Also strip text meant for human API readers (full URLs, rate-limit notes, long examples) from the definitions you send; keep types, short parameter descriptions and required flags.
The registry below uses keyword matching to stay short; a real one would rank by embeddings. Every lookup takes the user's role, the active tool set belongs to the session (the registry is shared, so it must not hold one session's tools for everyone), and dispatch checks permissions again before it runs anything.
from typing import Any, Callable, Dict, Iterable, List, Set
class ToolNotPermitted(Exception):
pass
class DynamicToolRegistry:
def __init__(self) -> None:
self.catalog: Dict[str, Dict[str, Any]] = {} # every tool, with its roles
def register_tool(self, name: str, description: str, schema: Dict[str, Any],
fn: Callable[..., Any], roles: Iterable[str]) -> None:
self.catalog[name] = {"description": description, "schema": schema,
"fn": fn, "roles": set(roles)}
def allowed_for(self, role: str) -> Set[str]:
return {n for n, t in self.catalog.items() if role in t["roles"]}
def discover_tools(self, role: str, query: str, limit: int = 4) -> List[str]:
# Keyword match keeps the demo small; real registries use embeddings
terms = query.lower().split()
hits = [n for n in sorted(self.allowed_for(role))
if any(t in self.catalog[n]["description"].lower() for t in terms)]
return hits[:limit]
def load_tools_for_step(self, role: str, names: List[str]) -> Set[str]:
"""Returns this step's active set; each session keeps its own."""
return set(names) & self.allowed_for(role)
def schemas(self, active: Set[str]) -> List[Dict]:
return [self.catalog[n]["schema"] for n in sorted(active)]
def dispatch(self, role: str, active: Set[str], name: str,
args: Dict[str, Any]) -> Any:
# The security check lives here, not in which schemas the prompt showed
if name not in self.allowed_for(role):
raise ToolNotPermitted(f"{name} is not permitted for role {role}")
if name not in active:
raise ToolNotPermitted(f"{name} was not loaded for this step")
return self.catalog[name]["fn"](**args)03. Tool Lifecycle: Unloading, Bundles and Access
Tools loaded on step 3 and step 6 pile up unless the runtime also unloads them. Two rules help:
- Unload in stable bundles. Group related tools (for example four cluster tools, or schema inspection plus query for Postgres) and load or unload the whole bundle at phase boundaries. Tool definitions sit near the start of the prompt, so every change to the tool list changes the prefix and invalidates the prompt cache from that point on. Churning single tools every few steps costs more than it saves. A provider tool-search feature (such as Anthropic's tool search tool) can add discovered tools without rewriting the cached prefix; measure the cache hit rate either way.
- Hiding a tool is not access control. The model can emit a call to any tool name, for example one named in injected text, and if the dispatcher looks names up in the full catalog the call runs. Scope the catalog by user role, enforce the same allowlist in the dispatcher (reject calls outside this user's permitted set or outside the tools loaded for this step), and keep server-side authorisation on the underlying API. The OWASP Top 10 for LLM Applications 2026 lists this risk as LLM03:2026 Excessive Agency. The 2026 edition renumbered the 2025 list, so ids in older articles differ: in 2025 Excessive Agency was LLM06.
04. Step 2: The Dispatcher Refuses What the Prompt Never Offered
Save the registry above as dynamic_registry.py, add this script next to it and run python3 demo_registry.py (Python 3.12 or later, standard library only; tested with 3.12.13). A support user discovers only the tools their role allows. Then the script plays the attacker: it asks the dispatcher to run tools that were never in the prompt.
from dynamic_registry import DynamicToolRegistry, ToolNotPermitted
reg = DynamicToolRegistry()
reg.register_tool("search_orders", "search customer orders", {"name": "search_orders"},
lambda query: f"2 orders match {query!r}", roles=["support", "admin"])
reg.register_tool("refund_order", "refund an order", {"name": "refund_order"},
lambda order_id: f"refunded {order_id}", roles=["admin"])
reg.register_tool("delete_customer", "delete a customer and orders",
{"name": "delete_customer"}, lambda cid: "deleted", roles=["admin"])
found = reg.discover_tools("support", "orders refund delete")
print("support can discover:", found)
support_step = reg.load_tools_for_step("support", found) # per session
print(reg.dispatch("support", support_step, "search_orders", {"query": "late parcel"}))
# The model was never shown delete_customer, but injected text names it anyway:
admin_step = reg.load_tools_for_step("admin", ["search_orders"]) # search only
attempts = [("support", support_step, "delete_customer", {"cid": "c-9"}),
("support", support_step, "refund_order", {"order_id": 7}),
("admin", admin_step, "refund_order", {"order_id": 7})]
for role, active, name, args in attempts:
try:
reg.dispatch(role, active, name, args)
except ToolNotPermitted as exc:
print("blocked:", exc)support can discover: ['search_orders']
2 orders match 'late parcel'
blocked: delete_customer is not permitted for role support
blocked: refund_order is not permitted for role support
blocked: refund_order was not loaded for this stepAll three calls are refused in code. Even an admin cannot run a tool that was not loaded for the current step, so a confused or injected call cannot reach outside the step's scope. Server-side authorisation on the refund API is still needed in case the agent process itself is compromised.
05. Step 3: Instruction Skills with Progressive Disclosure
A tool is something the agent can call. A skill, in the sense used by Anthropic's Agent Skills and similar systems, is a package of instructions: a procedure such as "how we decide refunds", often with reference files or scripts next to it. Putting every procedure in the system prompt wastes the window on procedures the current task never uses.
Progressive disclosure loads a skill in stages. By default the context holds only each skill's name and a one-line description that says what it does and when to use it. When a task matches a description, the agent loads that skill's full instructions (in Agent Skills, by reading its SKILL.md), and reads extra reference files only if the instructions point to them. The description has to be specific, because it is all the model sees when it decides whether a skill applies.
The script below builds 40 skills. Run python3 skill_index.py:
"""Progressive disclosure: skill names and summaries up front, bodies on demand."""
import math
def tokens(text):
return math.ceil(len(text) / 4)
def steps(topic, n=60):
return "\n".join(f"{k}. For {topic}, check item {k} and log the result."
for k in range(1, n + 1))
SKILLS = {f"team-{i:02d}-runbook": # name -> (one-line description, full body)
(f"Runbook for team {i}. Use for tickets tagged T{i}.", steps(f"team {i}"))
for i in range(1, 40)}
SKILLS["refund-policy"] = ("Decide refunds and credits. Use for refund or chargeback "
"requests.", steps("refunds"))
def skill_index():
"""What sits in the system prompt by default: one line per skill."""
return "\n".join(f"- {name}: {desc}" for name, (desc, _) in sorted(SKILLS.items()))
def load_skill(name):
"""A tool the model calls when a description matches the task."""
return SKILLS[name][1]
everything = sum(tokens(desc + body) for desc, body in SKILLS.values())
index = tokens(skill_index())
print(f"{len(SKILLS)} skills, all instructions loaded: {everything:,} tokens")
print(f"index of names and summaries: {index:,} tokens")
body = load_skill("refund-policy") # the model matched "refund" in the request
print(f"index + refund-policy loaded: {index + tokens(body):,} tokens")
print("first line loaded:", body.splitlines()[0])40 skills, all instructions loaded: 30,780 tokens
index of names and summaries: 680 tokens
index + refund-policy loaded: 1,441 tokens
first line loaded: 1. For refunds, check item 1 and log the result.The index costs about 2% of loading everything, and a request that needs one skill pays for one body. Tool bundles from the previous section can travel with a skill: load the refund tools when the refund skill loads.
06. Step 4: Isolate a Broad Sub-Task in Its Own Context
Some sub-tasks need many reads but produce a short answer: "find every call to charge_v1" may open 30 files to report four lines. Run inline, all 30 files stay in the main agent's history and are re-sent on every later step.
Instead, start a sub-agent: a separate model loop with a fresh context that holds only the sub-task instructions and the tools it needs, here read_file. It explores, hits dead ends and reads raw output in its own context. When it finishes, it returns a condensed, structured result (findings, sources, open questions, under a stated token limit), and only that result enters the main context.
In subagent.py the sub-agent is a deterministic stand-in for that loop, so the token counts are repeatable. Run python3 subagent.py:
"""Isolate a broad search in a sub-agent; the main context receives a short result."""
import json
import math
import random
def tokens(text):
return math.ceil(len(text) / 4)
def make_repo():
rng = random.Random(7)
repo = {f"svc/mod_{i:02d}.py": [f"def f{i}_{k}(x): return x * {rng.randrange(99)}"
for k in range(40)] for i in range(30)}
for i, k, cur in ((3, 12, "EUR"), (11, 5, "USD"), (19, 30, "EUR"), (26, 8, "GBP")):
repo[f"svc/mod_{i:02d}.py"][k] = f" charge_v1(order, currency={cur!r})"
return repo
REPO = make_repo()
def read_file(path):
return "\n".join(REPO[path])
def sub_agent(task):
"""Stand-in for a model loop with a fresh context: the task and read_file only."""
context, hits = [task], []
for path in sorted(REPO):
text = read_file(path)
context.append(text) # every read lands in the sub-agent's context, not main
hits += [{"file": path, "line": n} for n, line in
enumerate(text.splitlines(), 1) if "charge_v1(" in line]
result = {"findings": hits, "files_read": len(REPO),
"open_questions": ["Are any calls behind a feature flag?"]}
return json.dumps(result), sum(tokens(c) for c in context)
TASK = ("Find every call to charge_v1 in svc/. Reply with JSON only: findings "
"(file, line), files_read, open_questions. At most 200 tokens.")
MAIN = 3000 # tokens already in the main agent's context
inline = MAIN + sum(tokens(read_file(p)) for p in REPO)
result, used = sub_agent(TASK)
print(f"search inline: main context grows to {inline:,} tokens")
print(f"search delegated: main context grows to {MAIN + tokens(result):,} tokens")
print(f" the sub-agent used {used:,} tokens in its own context")
for hit in json.loads(result)["findings"]:
print(" finding:", hit)
print("currency of each call in the result?", "currency" in result)
print(f"re-read svc/mod_11.py to get it: +{tokens(read_file('svc/mod_11.py'))} tokens")search inline: main context grows to 11,503 tokens
search delegated: main context grows to 3,062 tokens
the sub-agent used 8,536 tokens in its own context
finding: {'file': 'svc/mod_03.py', 'line': 13}
finding: {'file': 'svc/mod_11.py', 'line': 6}
finding: {'file': 'svc/mod_19.py', 'line': 31}
finding: {'file': 'svc/mod_26.py', 'line': 9}
currency of each call in the result? False
re-read svc/mod_11.py to get it: +289 tokensThe main context grows by about 60 tokens instead of 8,500, and every later step re-sends the smaller history. Total tokens did not go down: the sub-agent still read every file, and a real one also pays for its own system prompt and reasoning. The other cost is lost detail. The result lists file and line but not the currency argument, so when the main agent needs it, it must re-read a file or ask again. Ask the sub-agent for the fields you know you will need, and keep sub-agents for tasks whose answer is much smaller than the work. The lab Parallel Sub-Agents with Isolated Context runs several of these at once.
07. Practice
08. Apply it
In your own agent, measure before and after each change:
- Size the tool set by measurement. Track tool-selection accuracy on an eval set as the catalog grows, and switch to on-demand loading when it drops or tools overlap.
- Load and unload in bundles at phase boundaries, and check the cache hit rate after changing the policy.
- Turn long procedures into skills with a specific one-line description, and log which skills load per task.
- Delegate one broad sub-task to a sub-agent with a fixed result schema. Compare main-context tokens, total tokens and how often the main agent has to go back for a missing detail.
- Test the router with ambiguous requests, so each one resolves to the intended tool or skill before you ship.
09. Review prompt
Without looking back, name three things that crowd an agent's context and the on-demand fix for each. What sits in the context for a skill that has not been used yet? What does a sub-agent save, what does it not save, and what can it lose?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.