Lesson 17 of 39 · Sessions, Memory and Context
Agent Skills
Give Agent Framework agents skills: SKILL.md folders, inline and class skills, scripts, resources, MCP skills, skill sources and unloading with compaction.
- 20 min read
- Intermediate
- Reviewed
- Explain what an agent skill is and how loading it only when needed keeps requests small
- Write a SKILL.md skill with resources and a script, and give it to an agent with SkillsProvider
- Define skills in code with InlineSkill and ClassSkill
- Load skills from an MCP server, and combine skill sources with filtering, deduplication and caching
- Control approvals for skill tools, and unload skills the agent no longer needs
What a skill is
Some tasks need a lot of know-how: how to fit a bike, how to handle a return, how to write a report in your company's style. You could put all of it in the agent's instructions, but then every request carries every procedure, even for "Do you sell helmets?".
Skills follow the open Agent Skills format, so a skill folder you write for Agent Framework also works with other tools that support the format. In Agent Framework, SkillsProvider gives skills to an agent. It's a context provider, like the ones in the previous lessons.
Load only what's needed
SkillsProvider works in three steps. This idea is called progressive disclosure: show a little first, and more only when it's needed.
- Advertise. Before every run it adds each skill's name and description to the instructions, roughly 100 tokens per skill.
- Load. When a task matches a skill, the model calls the
load_skilltool and gets the skill's full instructions. - Use. The model reads reference files with
read_skill_resourceand runs scripts withrun_skill_script, only if the instructions say so.
See how much that saves:
# Three skills: (name, description, length of the full instructions in characters)
skills = [
("bike-fitting", "Recommend a frame size from a customer's inside-leg length.", 2400),
("returns-policy", "Handle bike returns and refunds.", 1800),
("tyre-pressure", "Recommend a tyre pressure from tyre width and rider weight.", 1500),
]
def tokens(characters):
return round(characters / 4) # roughly 4 characters per token
everything = sum(tokens(len(name) + len(description) + body) for name, description, body in skills)
advertised = sum(tokens(len(name) + len(description)) for name, description, _ in skills)
print("All instructions, on every call: ", everything, "tokens")
print("Names and descriptions only: ", advertised, "tokens")
print("Plus bike-fitting, once it's needed:", advertised + tokens(2400), "tokens")The model still knows all three skills exist, but it pays for one skill's instructions, and only in the conversation that needs them.
A skill folder
A file skill is a folder with a SKILL.md file, plus any other files the skill needs:
skills/
bike-fitting/
SKILL.md
references/size-chart.md
scripts/frame_size.py
SKILL.md starts with frontmatter, a block of settings between two --- lines, followed by the instructions in Markdown:
---
name: bike-fitting
description: Recommend a bike frame size from an inside-leg measurement. Use when a customer asks which size to buy.
license: MIT
metadata:
author: Bike shop support team
version: "1.2"
---
# Bike fitting
1. Ask for the customer's height and inside-leg length in centimetres, if they haven't given them.
2. Run `scripts/frame_size.py` with the inside-leg length and the bike type (road, gravel or city).
3. Read `references/size-chart.md` to turn the frame size into our S, M, L or XL label.
4. Answer with the label and the frame size, and suggest a test ride in the shop.| Field | Required | What it's for |
|---|---|---|
name | Yes | Lowercase letters, numbers and single hyphens, at most 64 characters. It must match the folder name |
description | Yes | At most 1,024 characters. Until the skill is loaded, this is all the model sees, so say what the skill does and when to use it |
license, compatibility, metadata, allowed-tools | No | Extra information. Agent Framework reads them into skill.frontmatter, a SkillFrontmatter, but doesn't act on them |
The other files are found automatically, up to two folder levels deep:
- Resources are files with the extensions
.md,.json,.yaml,.yml,.csv,.xmlor.txt. Each one is named by its path inside the skill, herereferences/size-chart.md. - Scripts are
.pyfiles, such asscripts/frame_size.py. The model passes their arguments as a list of strings, like a command line:
"""Usage: frame_size.py INSIDE_LEG_CM BIKE_TYPE (BIKE_TYPE is road, gravel or city)"""
import sys
FACTORS = {"road": 0.70, "gravel": 0.68, "city": 0.66}
inside_leg = float(sys.argv[1])
bike_type = sys.argv[2]
print(f"Frame size: {round(inside_leg * FACTORS[bike_type])} cm")Give the skills to an agent
SkillsProvider.from_paths finds every skill folder in a directory. Each folder becomes a FileSkill, and each script a FileSkillScript:
import asyncio
import subprocess
import sys
from agent_framework import Agent, Message, SkillsProvider
from agent_framework.openai import OpenAIChatClient
def run_python_script(skill, script, args=None):
"""A script runner: runs a skill's Python file in a new process and returns what it prints."""
arguments = args if isinstance(args, list) else []
result = subprocess.run(
[sys.executable, script.full_path, *arguments],
capture_output=True, text=True, timeout=30,
)
return result.stdout if result.returncode == 0 else f"Error: {result.stderr}"
async def main():
skills = SkillsProvider.from_paths(
"skills", # the folder that holds bike-fitting/
script_runner=run_python_script,
disable_load_skill_approval=True, # our own skills: reading them needs no approval,
disable_read_skill_resource_approval=True, # but running a script still does
)
agent = Agent(
client=OpenAIChatClient(),
instructions="You are the assistant of a bike shop.",
context_providers=[skills],
)
session = agent.create_session()
response = await agent.run("I have an 81 cm inside leg. Which road bike size fits me?", session=session)
while response.user_input_requests: # the model wants to run a script
answers = []
for request in response.user_input_requests:
call = request.function_call
print("Approve?", call.name, call.arguments)
answers.append(request.to_function_approval_response(approved=True)) # in an app, ask a person
response = await agent.run(Message("user", answers), session=session)
print(response.text)
asyncio.run(main())A typical run: the model calls load_skill for bike-fitting, then asks to run scripts/frame_size.py with ["81", "road"]. The loop prints that request and approves it, and the script prints "Frame size: 57 cm". The model then reads references/size-chart.md and answers that a 57 cm frame is size L.
What happens, step by step:
- Advertising. Before the run, the provider adds a short guide to the instructions. It lists the skills inside an
<available_skills>block, with each skill's name and description, and explains the three tools. - Loading.
load_skillreturns the wholeSKILL.md, followed by an<available_resources>list and an<available_scripts>list, so the model knows exactly which names it can use. - The script runner. File scripts don't run by themselves: you pass a
script_runner. It's any function that takes the skill, the script and the arguments, as described bySkillScriptRunner. This one starts a new Python process withscript.full_pathand returns what the script prints. - Approvals. Every skill tool asks for approval by default. Here reading is allowed without asking, but running a script still needs a yes, which the
whileloop gives. The Tool Approval and User Input lesson explains this loop.
from_paths also takes resource_extensions, script_extensions, search_depth, and resource_filter and script_filter functions to leave files out.
Skills in code: InlineSkill
A skill doesn't have to be a folder. InlineSkill defines one in Python, which is handy when its resources come from your own data:
import asyncio
from agent_framework import Agent, InlineSkill, InlineSkillResource, SkillFrontmatter, SkillsProvider
from agent_framework.openai import OpenAIChatClient
returns = InlineSkill(
frontmatter=SkillFrontmatter(
name="returns-policy",
description="Handle bike returns and refunds. Use when a customer wants to return a bike.",
),
instructions="Read the policy, work out the refund with refund_amount, then explain it in two sentences.",
resources=[InlineSkillResource(name="policy", content="Unused bikes can be returned within 30 days.")],
)
@returns.resource(description="Returns that are waiting to be checked")
def open_returns() -> str:
return "3 returns are waiting to be checked." # in a real shop: read from the database
@returns.script(description="Work out the refund for a returned bike.")
def refund_amount(price: float, days_since_purchase: int) -> str:
if days_since_purchase > 30:
return "No refund: the bike was bought more than 30 days ago."
fee = 0 if days_since_purchase <= 14 else round(price * 0.10, 2) # 10% fee after two weeks
return f"Refund {price - fee:.2f} EUR (fee {fee:.2f} EUR)"
async def main():
print(await returns.get_content()) # what load_skill returns for this skill
agent = Agent(
client=OpenAIChatClient(),
instructions="You are the assistant of a bike shop.",
context_providers=[SkillsProvider(
[returns],
disable_load_skill_approval=True,
disable_read_skill_resource_approval=True,
disable_run_skill_script_approval=True, # our own, trusted Python function
)],
)
response = await agent.run("I bought a 900 EUR bike 20 days ago. Can I return it?")
print(response.text)
asyncio.run(main())<name>returns-policy</name>
<description>Handle bike returns and refunds. Use when a customer wants to return a bike.</description>
<instructions>
Read the policy, work out the refund with refund_amount, then explain it in two sentences.
</instructions>
<available_resources>
<resource name="policy"/>
<resource name="open_returns" description="Returns that are waiting to be checked"/>
</available_resources>
<available_scripts>
<script name="refund_amount" description="Work out the refund for a returned bike.">
<parameters_schema>{"properties": {"days_since_purchase": {"title": "Days Since Purchase", "type": "integer"}, "price": {"title": "Price", "type": "number"}}, "required": ["price", "days_since_purchase"], "title": "refund_amount_input", "type": "object"}</parameters_schema>
</script>
</available_scripts>Then the agent's answer follows. The printed text is what load_skill returns for an inline skill: the name, description and instructions, plus the resources and scripts, each script with a JSON schema of its arguments.
frontmatter=SkillFrontmatter(name=..., description=...)holds the name and description, with the same rules as inSKILL.md.- Resources are
InlineSkillResourceobjects with fixedcontent, or functions registered with@returns.resource. A function resource runs each time the model reads it, so it can return fresh data. Its name is the function's name unless you passname=. - Scripts registered with
@returns.scriptbecomeInlineSkillScriptobjects. They run inside your program, with the named arguments the model sends as a JSON object ({"price": 900, "days_since_purchase": 20}). No script runner is needed. argument_parser(aSkillScriptArgumentParser) helps with models that send script arguments in a different shape, such as one JSON string. It turns them into a dictionary first.
Because these scripts are your own functions, this example turns all three approvals off.
Skills as classes: ClassSkill
For a skill you want to reuse in many agents, or share as a Python package, subclass ClassSkill:
import asyncio
from agent_framework import ClassSkill, SkillFrontmatter
class TyrePressureSkill(ClassSkill):
"""A reusable skill: put it in a shared package and give it to any agent."""
def __init__(self, unit: str = "bar"):
super().__init__(frontmatter=SkillFrontmatter(
name="tyre-pressure",
description="Recommend a tyre pressure from the tyre width and the rider's weight.",
))
self.unit = unit
@property
def instructions(self) -> str:
return f"Check the pressure table, then run recommend-pressure. Answer in {self.unit}."
@ClassSkill.resource
def pressure_table(self) -> str:
return "For a 75 kg rider: 28 mm tyres 6.5 bar, 32 mm 5.5 bar, 40 mm 4.0 bar."
@ClassSkill.script
def recommend_pressure(self, tyre_width_mm: int, rider_kg: float) -> str:
"""Recommend a pressure for one tyre width and rider weight."""
bar = {28: 6.5, 32: 5.5, 40: 4.0}[tyre_width_mm] + (rider_kg - 75) * 0.02
return f"{bar:.1f} bar" if self.unit == "bar" else f"{bar * 14.5:.0f} psi"
async def main():
skill = TyrePressureSkill(unit="psi")
resource = await skill.get_resource("pressure-table") # underscores become hyphens
script = await skill.get_script("recommend-pressure")
print(resource.name, "->", await resource.read())
print(script.name, "->", await script.run(skill, {"tyre_width_mm": 32, "rider_kg": 90}))
asyncio.run(main())pressure-table -> For a 75 kg rider: 28 mm tyres 6.5 bar, 32 mm 5.5 bar, 40 mm 4.0 bar. recommend-pressure -> 84 psi
instructionsis a property you must write. It can use the object's settings, such asself.unit.@ClassSkill.resourceand@ClassSkill.scriptmark methods. Their names are the method names with hyphens instead of underscores:pressure_tablebecomespressure-table.- Every skill works the same way.
get_resource(name)returns aSkillResource, which you read withread().get_script(name)returns aSkillScript, which you start withrun(skill, args). That's exactly what the provider's tools do.
InlineSkill, ClassSkill, FileSkill and MCPSkill are all kinds of Skill. Pass any mix of them to SkillsProvider([...]).
Skills from an MCP server
A team can publish skills on an MCP server, so every agent gets the latest version. MCPSkillsSource reads them:
import asyncio
from mcp import Client
from agent_framework import Agent, CachingSkillsSource, MCPSkillsSource, SkillsProvider, SkillsSourceContext
from agent_framework.openai import OpenAIChatClient
async def main():
async with Client("https://skills.example.com/mcp") as mcp_client: # only servers you trust
source = CachingSkillsSource(MCPSkillsSource(mcp_client)) # read the index once, then reuse it
agent = Agent(
client=OpenAIChatClient(),
instructions="You are the assistant of a bike shop.",
context_providers=[SkillsProvider(source)],
)
for skill in await source.get_skills(SkillsSourceContext(agent=agent)):
print(type(skill).__name__, skill.frontmatter.name)
# ... run the agent here, while the MCP connection is open
asyncio.run(main())MCPSkill bike-fitting
The server lists its skills in a resource called skill://index.json:
{
"skills": [
{
"name": "bike-fitting",
"type": "skill-md",
"description": "Recommend a bike frame size from an inside-leg measurement.",
"url": "skill://bike-fitting/SKILL.md"
}
]
}skill-mdentries becomeMCPSkillobjects. TheSKILL.mdtext is fetched only when the model loads the skill, and each resource (anMCPSkillResource) when the model reads it.archiveentries point to a ZIP file with the whole skill folder, which is unpacked in memory. Asha256:digest in the entry is checked before unpacking.- Scripts from an MCP server never run. They're offered as resources to read, not as scripts.
You need the mcp package, which is installed with Agent Framework, and a server that publishes skills this way. Running your own is free. The MCP Tools lesson explains how to connect to servers; Model Context Protocol explains MCP itself.
Combine skill sources
Where skills come from is a skill source. Sources can be wrapped inside each other like layers, each adding one feature:
import asyncio
from datetime import timedelta
from agent_framework import (
Agent, AggregatingSkillsSource, CachingSkillsSource, DeduplicatingSkillsSource, FileSkillsSource,
FilteringSkillsSource, InlineSkill, InMemorySkillsSource, SkillFrontmatter, SkillsProvider, SkillsSourceContext,
)
from agent_framework.openai import OpenAIChatClient
def quick_skill(name, description):
return InlineSkill(frontmatter=SkillFrontmatter(name=name, description=description), instructions="...")
def allowed(skill, context): # staff skills only for the staff assistant
return skill.frontmatter.name != "stock-count" or context.agent.name == "staff-assistant"
source = CachingSkillsSource( # 4. remember the list for 10 minutes
DeduplicatingSkillsSource( # 3. one skill per name: the first wins
FilteringSkillsSource( # 2. keep only the allowed skills
AggregatingSkillsSource([ # 1. skills from a folder and from code
FileSkillsSource("skills"),
InMemorySkillsSource([
quick_skill("stock-count", "Count the bikes in the stock room."),
quick_skill("bike-fitting", "An old copy of the fitting skill."),
]),
]),
predicate=allowed,
),
),
refresh_interval=timedelta(minutes=10),
cache_isolation_key_selector=lambda context: context.agent.name, # one cache per agent
)
async def main():
for name in ["support-agent", "staff-assistant"]:
agent = Agent(client=OpenAIChatClient(), name=name, context_providers=[SkillsProvider(source)])
skills = await source.get_skills(SkillsSourceContext(agent=agent))
print(name, "->", [skill.frontmatter.name for skill in skills])
asyncio.run(main())support-agent -> ['bike-fitting'] staff-assistant -> ['bike-fitting', 'stock-count']
Read it from the inside out:
| Source | What it does |
|---|---|
FileSkillsSource | Finds SKILL.md folders, like from_paths |
InMemorySkillsSource | Serves skill objects you created in code |
AggregatingSkillsSource | Joins several sources into one list |
FilteringSkillsSource | Keeps only the skills for which predicate(skill, context) returns True. The context is a SkillsSourceContext with the agent and the session |
DeduplicatingSkillsSource | Keeps the first skill of each name (ignoring case) and logs a warning about the others. Here the folder's bike-fitting wins over the old copy |
CachingSkillsSource | Remembers the list, so files or servers aren't read on every run. refresh_interval makes it look again after a while |
Order matters. This filter gives different skills to different agents, so the cache needs cache_isolation_key_selector, which keeps one cache per agent name. Without it, the first agent's list would be reused for every agent.
When you pass skill objects, SkillsProvider adds deduplication and caching itself (turn caching off with disable_caching=True, or set cache_refresh_interval). A source you build yourself is used exactly as it is. For a new kind of source, such as skills stored in a database, subclass SkillsSource and write get_skills(context). To build a new layer, subclass DelegatingSkillsSource, which wraps another source.
Approvals for skill tools
Every skill tool needs a person's approval unless you say otherwise:
| Tool | What it does | Turn its approval off with |
|---|---|---|
load_skill | Returns a skill's instructions | disable_load_skill_approval=True |
read_skill_resource | Returns a resource | disable_read_skill_resource_approval=True |
run_skill_script | Runs a script | disable_run_skill_script_approval=True |
Instead of switching approvals off, you can approve some calls automatically with ToolApprovalMiddleware:
import asyncio
from agent_framework import Agent, SkillsProvider, ToolApprovalMiddleware
from agent_framework.openai import OpenAIChatClient
async def main():
agent = Agent(
client=OpenAIChatClient(),
instructions="You are the assistant of a bike shop.",
context_providers=[SkillsProvider.from_paths("skills")], # every skill tool asks for approval...
middleware=[ToolApprovalMiddleware(
auto_approval_rules=[SkillsProvider.read_only_tools_auto_approval_rule], # ...except reading
)],
)
session = agent.create_session() # the middleware keeps its rules here
response = await agent.run("Which road bike size fits an 81 cm inside leg?", session=session)
print([request.function_call.name for request in response.user_input_requests])
asyncio.run(main())['run_skill_script']
SkillsProvider.read_only_tools_auto_approval_rule approved load_skill and read_skill_resource by itself, so only the script waited for a person. SkillsProvider.all_tools_auto_approval_rule approves all three. The middleware stores its state in the session, so always pass one.
Unload skills you're done with
A loaded skill stays in the conversation, and is sent again on every later call. When the task is done, the agent can drop it with UnloadSkillsCompactionStrategy:
import asyncio
from agent_framework import Agent, AgentTriggeredCompactionStrategy, SkillsProvider, UnloadSkillsCompactionStrategy
from agent_framework.openai import OpenAIChatClient
async def main():
unload = AgentTriggeredCompactionStrategy(UnloadSkillsCompactionStrategy())
agent = Agent(
client=OpenAIChatClient(),
instructions="You are the assistant of a bike shop. When you are done with a skill, call unload_skill.",
default_options={"store": False}, # compaction needs the history in your app
context_providers=[SkillsProvider.from_paths("skills", disable_load_skill_approval=True)],
tools=[unload.tool], # the tool the model calls to unload skills
compaction_strategy=unload,
)
print("Tool:", unload.tool.name)
session = agent.create_session()
await agent.run("Which road bike size fits an 81 cm inside leg?", session=session)
await agent.run("Thanks! Do you sell helmets?", session=session)
asyncio.run(main())Tool: unload_skill
AgentTriggeredCompactionStrategy, which you met in the Compaction lesson, gets the unload_skill tool from the strategy it wraps. When the model calls unload_skill with a skill name, or with no name for all skills, every load_skill and read_skill_resource call and result for that skill is hidden before the next model call. For example, after the model loads bike-fitting and then calls unload_skill, its next request no longer contains the skill's instructions. As with all compaction, the history must live in your app (store=False).
Common mistakes
Check skill folders the way FileSkillsSource does: every SKILL.md needs a valid name that matches its folder, or the skill is skipped.
import re
folders = {
"bike-fitting": "---\nname: bike-fitting\ndescription: Recommend a frame size.\n---\n# Bike fitting",
"returns": "---\nname: Returns\ndescription: Handle bike returns.\n---\n# Returns",
"tyre-pressure": "---\nname: tyre-pressures\ndescription: Recommend a tyre pressure.\n---\n# Tyres",
}
# For each folder, read the value of the "name:" line in the frontmatter.
# A valid name uses only lowercase letters, numbers and single hyphens, with no hyphen at the start or end.
# Print "<folder>: invalid name" if the name isn't valid,
# "<folder>: name does not match folder" if it differs from the folder name,
# and "<folder>: ok" otherwise.
An agent has 20 skills. Why does SkillsProvider put only each skill's name and description into the instructions?
Summary
- A skill packages instructions, resources and scripts for one kind of task;
SkillsProvideradvertises it and loads it withload_skillonly when needed. - File skills are folders with a
SKILL.mdwhosenamematches the folder; resources are found by extension, and.pyscripts run through your script runner. InlineSkillandClassSkilldefine skills in Python, with resources and scripts that run in your program;MCPSkillsSourcereads skills from an MCP server.- Skill sources stack: aggregate, filter, deduplicate and cache, with one cache per agent when the filter depends on the agent.
- Skill tools need approval by default, and
UnloadSkillsCompactionStrategylets the agent drop skills it no longer needs.
Next: Harness Agents: Todos, Modes and File Memory.
Finished reading? Tick it off to track your progress.