08E.4 A2A Basics, Agent Skills (SKILL.md) and Tool Selection at Scale
08E.2 and 08E.3 were about connecting an agent to tools and data through MCP. This lesson covers the other three ways an agent gets extended, and a problem that appears when you use all of them. First, Agent2Agent (A2A): a protocol for one agent to hand work to a different agent that you do not control. Second, Agent Skills: folders of instructions and scripts, with a SKILL.md file, that an agent loads only when a task needs them. Third, tool selection at scale: what to do when an agent has hundreds of tools available, because a long tool list makes the model slower, more expensive and less accurate. Three programs run for real with the standard library: an A2A-shaped task lifecycle, a skill validator that shows progressive disclosure, and a tool search engine over 50 fake tools.
What you'll learn
- What A2A is, how it differs from MCP, and its core objects: Agent Card, task, message, part, artifact, plus streaming and push notifications (spec version 1.0)
- When an agent-to-agent protocol is worth it, and when a tool or an in-process sub-agent is enough
- What an Agent Skill is: the folder layout, the
SKILL.mdfrontmatter fields, progressive disclosure, bundled scripts, and how agents load them - How to author a good skill, with a complete worked example you can validate and run
- Why a long tool list hurts, and the ladder of fixes: fewer better tools, narrower active sets, tool search, dynamic tool loading (Anthropic's tool search tool and
defer_loading; OpenAI'stool_search), and your own retrieval - How to build and measure a tool retrieval step (BM25 keyword search over 50 tools), and what it gets wrong
- How to evaluate each of the three, with pointers into Modules 10A and 10B
What you don't need
- API keys, an A2A server or an agent product that supports skills. All three programs are standard library only and run locally. The provider request samples are illustrative.
- To have used A2A or Skills before. Both are introduced from scratch.
- Docker or any service.
Setup
Python 3.11 or newer. As of 1 December 2026 there is nothing to install and no key is needed.
mkdir extensibility && cd extensibility
python3 --version # 3.11 or newerFor Part 2 you also create a skill folder, described there. Save each program under the name in its first comment.
What you must be able to do after this lesson#
- Explain how A2A differs from MCP, and name its core objects (Agent Card, task, message, part, artifact) and the terminal and interrupted task states
- Decide when an agent-to-agent protocol is justified and when a tool or an in-process sub-agent is enough
- Write a valid
SKILL.md(name, description, body) with a description that says what the skill does and when to use it - Explain the three levels of progressive disclosure and what each costs in tokens
- Describe why a long tool list hurts and apply the ladder of fixes in order
- Build a tool retrieval step, measure its recall@k and fix its misses by improving descriptions
- Filter a dynamic tool search by permission before ranking
Why this matters for an AI engineer#
An agent is more than a model and a few functions. In a real system it calls other teams' agents, loads task-specific know-how, and reaches dozens of tool servers. Each of those is a place where cost and errors grow. An engineer who knows these three mechanisms can say "that belongs in a skill, not in the system prompt", "that should be a remote agent, not another tool" and "we have 200 tools, so we need search, not a bigger context window".
| You'll hear... | You'll understand it after... |
|---|---|
| "Is A2A a replacement for MCP?" | 1.2 A2A and MCP |
| "Publish an Agent Card so other agents can find us." | 1.3 The core objects |
"What is a task state of input-required?" |
1.4 The task lifecycle |
| "Put that in a skill." | Part 2 |
| "Why is the description field so important?" | 2.4 Writing a good skill |
| "The agent picks the wrong tool now that we have 80." | Part 3 |
"Turn on tool search and defer_loading." |
3.4 Provider tool search |
| "How do we know the retrieval step finds the right tool?" | 3.5 Build your own |
Part 1: Agent2Agent (A2A) basics#
Deep-dive
08D.3, Part 4 introduces A2A: what it is, the object table, what changed in v1.0 and a decision table. This part extends it with the full object and operation lists, streaming and push notifications, a runnable task lifecycle and the old-to-new name mapping. The sections that repeat 08D.3 are kept short.
1.1 What A2A is#
Agent2Agent (A2A) is an open protocol that lets one agent send work to another agent and follow its progress, when the two agents are built and run by different teams or companies and cannot see each other's internals. Think of calling a contractor rather than a function: you describe the job, they may ask questions, they take time, and they hand back a result. You do not see their tools or prompts.
Facts verified on 1 and 2 December 2026 (as of 1 December 2026):
| Fact | Value | Source |
|---|---|---|
| Specification | A2A Protocol Specification, latest released version 1.0.0. Earlier: 0.3.0, 0.2.6, 0.1.0 | a2a-protocol.org/latest/specification |
| Release dates | v1.0.0: 12 March 2026. v1.0.1: 28 May 2026 per the release header (its changelog says 2026-05-26). v0.3.0: 30 July 2025 | github.com/a2aproject/A2A/releases |
| Authoritative definition | The spec/a2a.proto file. The v1.0 names such as TASK_STATE_* come from it |
The specification page says so |
| Governance | The docs are © The Linux Foundation. The announcement "A new chapter for A2A: joining the Agentic AI Foundation", dated 27 August 2026, says A2A was accepted as a Growth Stage project at the Agentic AI Foundation (AAIF), a Linux Foundation-directed organisation (opened 2 December 2026) | a2a-protocol.org/latest/blog/2026/08/27/... |
| Version negotiation | Clients send an A2A-Version header (or query parameter) such as 1.0. An empty value is treated as 0.3. Servers return VersionNotSupportedError for an unsupported version |
The specification page |
1.2 A2A and MCP: vertical and horizontal#
As 08D.3, 4.1 says, MCP is vertical (an agent to its tools) and A2A is horizontal (agents to each other, across a team or organisation boundary). The A2A project's own page on the subject (read 1 December 2026) adds the contrast in the table below, and sums it up: "A2A connects the agents to each other; MCP connects each agent to its own tools."
| MCP | A2A | |
|---|---|---|
| What you call | A tool, resource or prompt (a function-like capability) | Another agent (a task-taker) |
| Typical shape | One request, one result, structured | A task with a lifecycle, maybe several messages, maybe minutes or hours |
| Who knows the internals | The caller sees the tool's schema | The caller sees an Agent Card and the task's messages. Internals are opaque |
| State | Stateless requests (in 2026-07-28) |
Stateful tasks with ids and a contextId for grouping |
| Discovery | server/discover, tools/list |
The Agent Card at a well-known URL |
| Who is it for | An agent using capabilities | An agent partnering with another agent |
The two are used together. Inside a team an agent uses MCP to reach its tools. Between teams, agents talk A2A. The A2A page notes an overlap: an A2A server can expose well-defined skills as MCP-compatible resources, but A2A's main strength is stateful collaboration.
1.3 The core objects#
Everything below is from the A2A specification, version 1.0 (read 1 and 2 December 2026), except where marked. 08D.3, 4.2 has the one-table version of the objects and an AgentCard example in the Python SDK; this section adds the field lists, the operations, streaming, push notifications and bindings.
Agent Card. A JSON document an A2A server publishes to describe itself. The well-known location is https://{server_domain}/.well-known/agent-card.json (specification sections 8.2 and 14.3). Fields include name, description, version, supportedInterfaces (each with a url, a protocolBinding and a protocolVersion), provider, documentationUrl, iconUrl, capabilities (streaming, pushNotifications, extendedAgentCard), securitySchemes, securityRequirements, defaultInputModes, defaultOutputModes, skills and signatures. Each skill has an id, name, description, tags and example prompts. An Agent Card can be signed (JWS, RFC 7515), so a client can check who published it.
Task. A stateful unit of work with a server-generated id. Its fields are id, contextId (groups related tasks and messages), status, artifacts, history and metadata.
Message. One turn of communication. Fields: messageId, contextId, taskId, role, parts, metadata, extensions, referenceTaskIds. The role is ROLE_USER (client to server) or ROLE_AGENT (server to client).
Part. The smallest content unit inside a message or an artifact. A part holds exactly one of text, raw (bytes), url (a file reference) or data (structured JSON), plus optional metadata, filename and mediaType.
Artifact. An output of a task, made of parts. A task's final deliverable (a booking confirmation, a generated report) is an artifact, while conversational turns are messages.
Task states (v1.0). TASK_STATE_SUBMITTED, TASK_STATE_WORKING, TASK_STATE_COMPLETED, TASK_STATE_FAILED, TASK_STATE_CANCELED, TASK_STATE_INPUT_REQUIRED, TASK_STATE_REJECTED, TASK_STATE_AUTH_REQUIRED (and an UNSPECIFIED placeholder). Completed, failed, canceled and rejected are terminal. Input-required and auth-required are interrupted: the task waits for the client to supply something.
Operations (JSON-RPC method names in v1.0).
| Method | Purpose |
|---|---|
SendMessage |
Send a message. The reply is a task or a direct message |
SendStreamingMessage |
Same, but stream updates back (server-sent events) |
GetTask, ListTasks, CancelTask |
Read, list (with pagination) and cancel tasks |
SubscribeToTask |
Stream updates for an existing task |
CreateTaskPushNotificationConfig, GetTaskPushNotificationConfig, ListTaskPushNotificationConfigs, DeleteTaskPushNotificationConfig |
Manage webhooks for updates |
GetExtendedAgentCard |
Fetch a more detailed card after authenticating |
Streaming. In a stream, updates arrive wrapped in a StreamResponse that can carry a task, a message, a statusUpdate (TaskStatusUpdateEvent: taskId, contextId, status) or an artifactUpdate (TaskArtifactUpdateEvent: taskId, contextId, artifact, append, lastChunk). The append and lastChunk fields let an agent deliver a large artifact in pieces.
Push notifications. For long tasks a client can register a webhook, and the server calls it when the task changes, so the client need not hold a connection open or poll. The webhook is plain HTTP with a JSON payload whatever binding the agent uses.
Bindings. The same model is carried over JSON-RPC, gRPC or HTTP+JSON/REST, and the specification allows custom bindings. A server lists the ones it supports in supportedInterfaces.
Security. The Agent Card's securitySchemes can describe API key, HTTP auth, OAuth 2.0, OpenID Connect and mutual TLS. Errors distinguish authentication (401) from authorization (403). The authorization concepts from 08E.3 (audience, least scope, no token passthrough) apply the same way when one agent calls another.
1.4 The task lifecycle, run it#
The most important idea in A2A is that a request creates a task, and a task has a lifecycle. This sketch makes that visible. The Agent Card and the object and state names follow specification v1.0. The in-process "transport" and the transition table are this lesson's simplification: the specification defines the states and which are terminal, not this exact state machine, and it is not a wire-accurate JSON-RPC exchange.
# a2a_sketch.py - an A2A-shaped toy: Agent Card, tasks, messages with parts, and the task lifecycle.
# Field and state names follow A2A spec v1.0; the in-process "transport" and the allowed-transition table are
# this lesson's simplification (the spec defines the states, not this exact state machine).
import json, uuid
TERMINAL = {"TASK_STATE_COMPLETED", "TASK_STATE_FAILED", "TASK_STATE_CANCELED", "TASK_STATE_REJECTED"}
INTERRUPTED = {"TASK_STATE_INPUT_REQUIRED", "TASK_STATE_AUTH_REQUIRED"}
ALLOWED = {"TASK_STATE_SUBMITTED": {"TASK_STATE_WORKING", "TASK_STATE_REJECTED"},
"TASK_STATE_WORKING": {"TASK_STATE_COMPLETED", "TASK_STATE_FAILED", "TASK_STATE_CANCELED"} | INTERRUPTED,
"TASK_STATE_INPUT_REQUIRED": {"TASK_STATE_WORKING", "TASK_STATE_CANCELED"},
"TASK_STATE_AUTH_REQUIRED": {"TASK_STATE_WORKING", "TASK_STATE_CANCELED"}}
AGENT_CARD = { # what a remote agent publishes at https://<host>/.well-known/agent-card.json
"name": "Travel Booking Agent", "description": "Finds and books flights for a traveller.", "version": "1.0.0",
"supportedInterfaces": [{"url": "https://travel.example.com/a2a", "protocolBinding": "JSONRPC", "protocolVersion": "1.0"}],
"capabilities": {"streaming": True, "pushNotifications": False, "extendedAgentCard": False},
"defaultInputModes": ["text/plain"], "defaultOutputModes": ["text/plain", "application/json"],
"skills": [{"id": "book-flight", "name": "Book a flight", "description": "Books a flight given origin, destination and date.",
"tags": ["travel", "flights"], "examples": ["Book me a flight from Chennai to Berlin on 12 March."]}],
}
class RemoteAgent:
"""Stands in for another team's agent. The caller sees an opaque task, never this agent's prompt or tools."""
def __init__(self): self.tasks = {}
def send_message(self, message): # ~ SendMessage
tid = message.get("taskId")
if tid is None:
tid = str(uuid.uuid4())[:8]
self.tasks[tid] = {"id": tid, "contextId": "ctx-1", "status": {"state": "TASK_STATE_SUBMITTED"}, "history": [], "artifacts": []}
task = self.tasks[tid]
task["history"].append(message)
text = " ".join(p["text"] for p in message["parts"] if "text" in p).lower()
self._move(task, "TASK_STATE_WORKING")
if "date" not in text and "march" not in text:
self._move(task, "TASK_STATE_INPUT_REQUIRED")
task["status"]["message"] = {"role": "ROLE_AGENT", "parts": [{"text": "Which date do you want to fly?"}]}
else:
task["artifacts"].append({"artifactId": "a1", "name": "booking", "parts": [{"data": {"flight": "LH 755", "date": "2027-03-12"}, "mediaType": "application/json"}]})
self._move(task, "TASK_STATE_COMPLETED")
return task
def get_task(self, tid): return self.tasks[tid] # ~ GetTask
def cancel_task(self, tid): # ~ CancelTask
self._move(self.tasks[tid], "TASK_STATE_CANCELED"); return self.tasks[tid]
def _move(self, task, new):
old = task["status"]["state"]
if old in TERMINAL: raise RuntimeError(f"task already {old}: terminal tasks cannot change")
if new not in ALLOWED.get(old, set()): raise RuntimeError(f"illegal move {old} -> {new}")
task["status"] = {"state": new}
def msg(text, task_id=None):
m = {"messageId": str(uuid.uuid4())[:8], "role": "ROLE_USER", "parts": [{"text": text}]}
if task_id: m["taskId"] = task_id
return m
if __name__ == "__main__":
print("Agent Card (skills are advertised, internals are not):")
print(json.dumps({k: AGENT_CARD[k] for k in ("name", "supportedInterfaces", "capabilities")}, indent=2))
agent = RemoteAgent()
print("\n-- Turn 1: vague request --")
t = agent.send_message(msg("Book me a flight to Berlin"))
print("state:", t["status"]["state"], "| agent asks:", t["status"]["message"]["parts"][0]["text"])
print("interrupted?", t["status"]["state"] in INTERRUPTED, "| terminal?", t["status"]["state"] in TERMINAL)
print("\n-- Turn 2: same taskId, answer the question --")
t = agent.send_message(msg("12 March please", task_id=t["id"]))
print("state:", t["status"]["state"], "| artifact:", json.dumps(t["artifacts"][0]["parts"][0]["data"]))
print("history length:", len(t["history"]), "messages from the caller")
print("\n-- Terminal tasks stay terminal --")
for action in (lambda: agent.cancel_task(t["id"]), lambda: agent.send_message(msg("one more thing", task_id=t["id"]))):
try: action()
except RuntimeError as exc: print("rejected:", exc)Agent Card (skills are advertised, internals are not):
{
"name": "Travel Booking Agent",
"supportedInterfaces": [
{
"url": "https://travel.example.com/a2a",
"protocolBinding": "JSONRPC",
"protocolVersion": "1.0"
}
],
"capabilities": {
"streaming": true,
"pushNotifications": false,
"extendedAgentCard": false
}
}
-- Turn 1: vague request --
state: TASK_STATE_INPUT_REQUIRED | agent asks: Which date do you want to fly?
interrupted? True | terminal? False
-- Turn 2: same taskId, answer the question --
state: TASK_STATE_COMPLETED | artifact: {"flight": "LH 755", "date": "2027-03-12"}
history length: 2 messages from the caller
-- Terminal tasks stay terminal --
rejected: task already TASK_STATE_COMPLETED: terminal tasks cannot change
rejected: task already TASK_STATE_COMPLETED: terminal tasks cannot changeWhat it shows:
- A vague request becomes an interrupted task. The remote agent moved to
TASK_STATE_INPUT_REQUIREDand asked "Which date do you want to fly?". The client's agent must now ask its user, or answer from context. - Follow-ups reuse the task id. The second message carried
taskId, so the remote agent continued the same task and completed it, with an artifact holding structureddata. The history lists the two caller messages. - Terminal means terminal. Cancelling or messaging a completed task is refused. A new request needs a new task.
- Opacity. The caller never saw the remote agent's prompt, model or tools. It saw the Agent Card (its advertised skills), task states, messages and artifacts.
1.5 What changed from 0.3 to 1.0#
08D.3, 4.3 summarises v1.0 in bullets. The "What's new in v1.0" page (read 1 December 2026) lists these migrations in full, which are worth knowing when you meet older code:
| 0.3 | 1.0 |
|---|---|
message/send, message/stream |
SendMessage, SendStreamingMessage |
tasks/get, tasks/cancel, tasks/resubscribe |
GetTask, CancelTask, SubscribeToTask |
| (no list method) | ListTasks is new |
agent/getAuthenticatedExtendedCard |
GetExtendedAgentCard |
tasks/pushNotificationConfig/{set,get,list,delete} |
Create…, Get…, List…, DeleteTaskPushNotificationConfig |
protocolVersion on the card; preferredTransport and additionalInterfaces |
supportedInterfaces[], each with url, protocolBinding and protocolVersion |
supportsAuthenticatedExtendedCard |
capabilities.extendedAgentCard |
kind discriminator on objects |
Removed |
| Lowercase task states | TASK_STATE_* names |
The discovery path /.well-known/agent-card.json is listed under 0.3.0 and the page lists no change to it in 1.0.
1.6 When to use A2A, and when not to#
A2A adds a network hop, a trust boundary and a task lifecycle, so use it when those are real. 08D.3, 4.4 has the full decision table. In short: a function with clear inputs and outputs is a tool (local or MCP), not A2A. Your own code in the same process is an in-process sub-agent or agent-as-a-tool (08D.1). Another team or company's agent with its own tools and prompt, which may need several turns, is the A2A case. Work that takes minutes or hours and needs status, cancellation or a callback fits A2A tasks and push notifications, or MCP's Tasks extension for a tool (08E.1, 6.6). An auditable, authenticated boundary between two organisations is another reason for A2A and its security schemes.
Part 2: Agent Skills (SKILL.md)#
08A.15, 3.3 and 08A.4, 2.7 introduce skills in a few lines, and 08A.8, 3.4 covers Anthropic's container.skills. This part is the full treatment: the format, progressive disclosure, how to write a good skill, a worked example you can validate and run, where skills run and their security.
2.1 What a skill is#
An Agent Skill is a folder that teaches an agent how to do one kind of task. The only required file is SKILL.md: a small block of metadata at the top, then instructions in Markdown. The folder may also hold scripts the agent can run, reference documents it can read, and templates or data files.
The key idea is that a skill is loaded on demand. Your agent might have fifty skills installed, but only the name and one-sentence description of each sits in its context at the start. The full instructions are read only when the task matches. That is very different from putting everything in the system prompt, where every instruction costs tokens on every request.
The format is published as an open specification at agentskills.io. It was created by Anthropic and is described in 08A.15 as an open standard (08A.15, 3.3 covers how skills relate to AGENTS.md). Which agent products load skills is listed on that site and changes often, and this lesson did not enumerate them, so check the site rather than assuming your agent supports it.
drafting-release-notes/
├── SKILL.md # required: metadata + instructions
├── scripts/ # optional: executable code
├── references/ # optional: documentation loaded on demand
└── assets/ # optional: templates, data files2.2 The SKILL.md format#
From the Agent Skills specification (agentskills.io/specification, read 1 December 2026). The file is YAML frontmatter between --- lines, then a Markdown body with no format restrictions.
| Field | Required | Constraints |
|---|---|---|
name |
Yes | 1 to 64 characters. Lowercase letters, numbers and hyphens only. Must not start or end with a hyphen, must not contain --, and must match the parent directory name |
description |
Yes | 1 to 1024 characters, non-empty. Should say what the skill does and when to use it, with keywords that help an agent recognise relevant tasks |
license |
No | A licence name or the name of a bundled licence file |
compatibility |
No | Up to 500 characters. Environment needs (intended product, system packages, network access). Most skills do not need it |
metadata |
No | A map of string keys to string values for anything else (author, version). Use reasonably unique key names |
allowed-tools |
No | A space-separated list of pre-approved tools. Experimental: support varies between agent implementations |
Anthropic's own documentation adds constraints for skills used on Anthropic's platform (the Agent Skills overview, read 1 December 2026): the name and description cannot contain XML tags, and the name cannot contain the reserved words anthropic or claude. The demo validator below checks both sets.
2.3 Progressive disclosure: how agents load a skill#
The specification describes three levels, and Anthropic's overview gives the same structure with token figures:
| Level | When loaded | Cost | Content |
|---|---|---|---|
| 1. Metadata | Always, at startup, for every installed skill | About 100 tokens per skill | name and description |
| 2. Instructions | When the skill is triggered by a matching task | The spec recommends under 5,000 tokens, and keeping SKILL.md under 500 lines |
The SKILL.md body |
| 3. Resources | As needed | None until accessed | Files in scripts/, references/, assets/ |
How this works mechanically (Anthropic's overview): the agent has a filesystem and a bash tool. At startup the system prompt lists each skill's name and description. When a request matches, the agent reads SKILL.md with a command such as cat drafting-release-notes/SKILL.md, and only then do its instructions enter the context. If those instructions mention references/STYLE.md, the agent reads that file when it needs it. If they mention a script, the agent runs it and only the script's output enters the context. The script's code never does. That makes a script both cheaper and more reliable than asking the model to write equivalent code.
Two consequences for how you write skills:
- Keep references one level deep from
SKILL.md. Anthropic's guide warns that when files reference other files, the model may preview them with commands likehead -100and read only part. Link everything directly fromSKILL.md, and give any reference file longer than about 100 lines a table of contents at the top. - Say whether to run or read a script. "Run
analyze_form.py" and "Seeanalyze_form.pyfor the algorithm" lead to different behaviour. Execution is usually what you want.
2.4 How to write a good skill#
These rules come from Anthropic's "Skill authoring best practices" (read 1 December 2026) and the open specification, organised as a checklist.
1. Be concise. Assume the model is already smart. The skill shares the context window with the system prompt, the conversation and every other skill's metadata. Add only what the model does not already know. Do not explain what a PDF is. For each paragraph ask: does this justify its token cost?
2. Match the freedom to the fragility. The guide uses a bridge analogy.
| Freedom | Use when | Looks like |
|---|---|---|
| High (text instructions) | Many approaches are valid, context decides | "Review the code for bugs, readability and conventions" |
| Medium (pseudocode or parameterised script) | A preferred pattern exists, some variation is fine | A template function with parameters |
| Low (an exact command, few parameters) | Operations are fragile, order matters | "Run exactly python scripts/migrate.py --verify --backup. Do not add flags" |
3. Name it clearly. Use lowercase hyphenated names. The guide suggests the gerund form (processing-pdfs, drafting-release-notes) as clearest, and accepts noun phrases (pdf-processing) or verbs (process-pdfs). Avoid vague names (helper, utils, tools) and reserved words.
4. Write the description in the third person, with what and when. The description is injected into the system prompt, so a point-of-view that does not match can confuse discovery. Good: "Drafts user-facing release notes from a list of commit messages... Use when the user asks for release notes or a changelog entry." Bad: "I can help you with release notes." Worse: "Helps with documents."
5. Use progressive disclosure. Keep the body short (under 500 lines). Move detail into references/ files and point to them. Organise reference files by domain (reference/finance.md, reference/sales.md) so the agent reads only what the task needs.
6. Give workflows, checklists and feedback loops. For multi-step work, write numbered steps and a checklist the agent can copy and tick. For quality-critical work add a validate, fix, repeat loop: run a validator, fix the errors, run again. For batch or destructive operations use plan, validate, execute: have the agent write a plan file, validate it with a script, and only then act.
7. Let scripts solve problems, not pass them on. A bundled script should handle errors itself and print messages that tell the agent what to do next ("error: 1 line is not a conventional commit... Expected 'type(scope): message'"). Document every constant: a mystery number like TIMEOUT = 47 forces the agent to guess.
8. Provide a default, not a menu. "Use pdfplumber. For scanned PDFs use pdf2image with pytesseract instead" beats listing five libraries.
9. Avoid time-sensitive text. "Before August 2025 use the old API" goes stale. Put legacy material in a collapsed "old patterns" section.
10. Use consistent terms. Pick one word (field, endpoint, extract) and use it throughout.
11. Do not assume packages exist. Say which packages are needed. On the Claude API skills run with no network access and no runtime package installation. In Claude Code they have the same network access as any program on the user's machine. In claude.ai the access varies with settings.
12. For MCP tools mentioned in a skill, use fully qualified names (ServerName:tool_name), so the agent finds the right tool when several servers are connected.
13. Build evaluations first. The guide recommends evaluation-driven development: run the agent on representative tasks without the skill and note the failures, write three scenarios that test those gaps, measure the baseline, write the minimum instructions that fix them, then iterate. It also says there is not currently a built-in way to run such evaluations, so you build your own. See Part 4.
14. Test with every model you plan to use. A skill that works with a large model may need more detail for a small one, and a skill written for a small model may over-explain for a large one.
2.5 A complete worked example#
Here is a whole skill: a folder with a SKILL.md, a reference file and a script. It turns commit messages into customer-facing release notes. The SKILL.md follows every rule above: a third-person description with what and when, a checklist, a low-freedom step that runs a script exactly, a reference file one level deep, an output template and explicit edge cases.
drafting-release-notes/SKILL.md
---
name: drafting-release-notes
description: Drafts user-facing release notes from a list of commit messages or merged pull request titles. Use when the user asks for release notes, a changelog entry, or "what shipped" for a version or date range.
license: Apache-2.0
compatibility: Needs Python 3.11+ to run scripts/group_commits.py. No network access required.
metadata:
author: platform-docs-team
version: "1.0"
allowed-tools: Read Bash(python3:*)
---
# Drafting release notes
Turn raw commit messages into release notes a customer can read.
## When to use this skill
Use it when the input is a list of commits or pull request titles and the output is for
people who do not read code. Do not use it for internal changelogs that list every commit.
## Workflow
Copy this checklist into your reply and tick items off:
```
- [ ] 1. Get the commit list (ask the user if it was not provided)
- [ ] 2. Group the commits: run scripts/group_commits.py
- [ ] 3. Rewrite each bullet in plain language (see references/STYLE.md)
- [ ] 4. Fill in the output template below
- [ ] 5. Check: every bullet came from a real commit, and nothing internal leaked
```
### Step 2: group the commits
Write the commits to a file, one per line, then run:
```bash
python3 scripts/group_commits.py commits.txt
```
The script prints Markdown sections (Added, Fixed, Changed) and drops `chore`, `ci`,
`test` and `docs` commits. If it prints `error:`, read the message and fix the input; do
not guess the grouping by hand.
### Step 3: rewrite for customers
Follow `references/STYLE.md`. Short version: start with a verb, describe the benefit,
leave out ticket numbers, file names and internal service names.
## Output template
```markdown
## <version> (<date>)
### Added
- <benefit-first sentence>
### Fixed
- <what was wrong, now fixed>
### Changed
- <what behaves differently and what the user should do>
```
Leave out any section that has no bullets.
## Edge cases
- A commit marked `BREAKING` goes under "Changed" and starts with "Action needed:".
- If two commits describe one change, merge them into one bullet.
- If the commit list is empty after filtering, say so. Never invent entries.drafting-release-notes/references/STYLE.md
# Release note style
- Start each bullet with a verb in the past tense: "Added", "Fixed", "Improved".
- Say what the user can now do, not what the code does.
- No ticket ids, file names, class names or internal service names.
- One sentence per bullet. Two only for a breaking change.
- Example. Commit: `fix(export): handle empty csv header`.
Bullet: "Fixed an error that stopped CSV exports when a report had no rows."drafting-release-notes/scripts/group_commits.py
# scripts/group_commits.py - group conventional-commit lines into release-note sections (stdlib only).
import re
import sys
from collections import defaultdict
SECTION = {"feat": "Added", "fix": "Fixed", "perf": "Changed", "refactor": "Changed", "change": "Changed"}
DROP = {"chore", "ci", "test", "docs", "build", "style"}
PATTERN = re.compile(r"^(?P<type>[a-z]+)(\((?P<scope>[^)]+)\))?(?P<bang>!)?: (?P<text>.+)$")
def main(path: str) -> int:
try:
lines = [l.strip() for l in open(path, encoding="utf-8") if l.strip()]
except OSError as exc:
print(f"error: cannot read {path}: {exc.strerror}. Pass the path of a text file with one commit per line.")
return 1
groups, bad = defaultdict(list), []
for line in lines:
m = PATTERN.match(line)
if not m:
bad.append(line)
continue
kind, text = m["type"], m["text"]
if kind in DROP:
continue
if m["bang"] or "BREAKING" in line:
groups["Changed"].append(f"Action needed: {text}")
else:
groups[SECTION.get(kind, "Changed")].append(text)
if bad:
print(f"error: {len(bad)} line(s) are not conventional commits, for example: {bad[0]!r}. "
"Expected 'type(scope): message'.")
return 1
for name in ("Added", "Fixed", "Changed"):
if groups[name]:
print(f"### {name}")
print(*[f"- {t}" for t in groups[name]], sep="\n")
print()
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1]) if len(sys.argv) == 2 else print("usage: group_commits.py FILE") or 2)Now a program that validates the folder against the specification and shows what each level costs. It is a simplified check, not a replacement for the official validator. The specification points to the skills-ref library (skills-ref validate ./my-skill) for that.
# skills_demo.py - validate a skill folder against the Agent Skills spec and show progressive disclosure.
import math, re, subprocess, sys, tempfile
from pathlib import Path
NAME_RE = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$") # lowercase, digits, single hyphens, no leading/trailing hyphen
def parse_frontmatter(text):
"""A tiny parser for the subset skills use: `key: value` lines and one level of nested mapping."""
lines = text.splitlines()
if lines[0] != "---":
raise ValueError("SKILL.md must start with '---' frontmatter")
end = lines.index("---", 1)
data, current = {}, None
for raw in lines[1:end]:
if raw.startswith(" ") and current is not None:
k, _, v = raw.strip().partition(":")
data[current][k.strip()] = v.strip().strip('"')
else:
k, _, v = raw.partition(":")
current = k.strip()
data[current] = {} if v.strip() == "" else v.strip()
return data, "\n".join(lines[end + 1:])
def validate(skill_dir: Path):
problems = []
meta, body = parse_frontmatter((skill_dir / "SKILL.md").read_text())
name, desc = meta.get("name", ""), meta.get("description", "")
desc = desc if isinstance(desc, str) else "" # an empty value parses as an empty mapping
if not (1 <= len(name) <= 64 and NAME_RE.match(name)): problems.append(f"name {name!r} breaks the naming rule")
if name != skill_dir.name: problems.append(f"name {name!r} must match the directory {skill_dir.name!r}")
if any(w in name for w in ("anthropic", "claude")): problems.append("name contains a reserved word (Anthropic API rule)")
if not (1 <= len(desc) <= 1024): problems.append(f"description length {len(desc)} not in 1..1024")
if re.search(r"<[a-z/][^>]*>", desc + name): problems.append("XML tags not allowed (Anthropic API rule)")
if "compatibility" in meta and not (1 <= len(meta["compatibility"]) <= 500): problems.append("compatibility must be 1..500 chars")
if len(body.splitlines()) > 500: problems.append("body over 500 lines: split into references/")
return meta, body, problems
def est_tokens(text): return math.ceil(len(text) / 4) # rough: ~4 characters per token
skill = Path(__file__).parent / "skills" / "drafting-release-notes"
meta, body, problems = validate(skill)
print("== Validation ==")
print("problems:", problems or "none")
print("\n== Level 1: what sits in the system prompt for EVERY skill, always ==")
catalog = f"- {meta['name']}: {meta['description']}"
print(catalog)
print(f"~{est_tokens(catalog)} tokens")
print("\n== Level 2: SKILL.md body, loaded only when the skill triggers ==")
print(f"{len(body.splitlines())} lines, ~{est_tokens(body)} tokens")
print("\n== Level 3: bundled files, loaded or run only when the body points at them ==")
for f in sorted(p for p in skill.rglob("*") if p.is_file() and p.name != "SKILL.md"):
print(f"{str(f.relative_to(skill)):28} ~{est_tokens(f.read_text())} tokens if read; a script that is RUN costs only its output")
print("\n== Run the bundled script on sample input ==")
with tempfile.TemporaryDirectory() as tmp:
commits = Path(tmp) / "commits.txt"
commits.write_text("feat(export): add scheduled CSV exports\nfix(export): handle empty csv header\n"
"chore: bump deps\nperf(search): cache hot queries\nfeat(api)!: drop the v1 endpoint\n")
out = subprocess.run([sys.executable, str(skill / "scripts" / "group_commits.py"), str(commits)], capture_output=True, text=True)
print(out.stdout.rstrip())
commits.write_text("added some stuff\n")
bad = subprocess.run([sys.executable, str(skill / "scripts" / "group_commits.py"), str(commits)], capture_output=True, text=True)
print("bad input ->", bad.stdout.strip(), "| exit code", bad.returncode)
print("\n== Three broken skills ==")
with tempfile.TemporaryDirectory() as tmp:
for dirname, name, desc in [("PDF-Tools", "PDF-Tools", "Helps with PDFs."), ("pdf-extra", "pdf--extra", ""),
("claude-helper", "claude-helper", "Use when <tag>x</tag>")]:
d = Path(tmp) / dirname
d.mkdir()
(d / "SKILL.md").write_text(f"---\nname: {name}\ndescription: {desc}\n---\nBody\n")
print(dirname, "->", validate(d)[2])== Validation ==
problems: none
== Level 1: what sits in the system prompt for EVERY skill, always ==
- drafting-release-notes: Drafts user-facing release notes from a list of commit messages or merged pull request titles. Use when the user asks for release notes, a changelog entry, or "what shipped" for a version or date range.
~57 tokens
== Level 2: SKILL.md body, loaded only when the skill triggers ==
61 lines, ~433 tokens
== Level 3: bundled files, loaded or run only when the body points at them ==
references/STYLE.md ~106 tokens if read; a script that is RUN costs only its output
scripts/group_commits.py ~410 tokens if read; a script that is RUN costs only its output
== Run the bundled script on sample input ==
### Added
- add scheduled CSV exports
### Fixed
- handle empty csv header
### Changed
- cache hot queries
- Action needed: drop the v1 endpoint
bad input -> error: 1 line(s) are not conventional commits, for example: 'added some stuff'. Expected 'type(scope): message'. | exit code 1
== Three broken skills ==
PDF-Tools -> ["name 'PDF-Tools' breaks the naming rule"]
pdf-extra -> ["name 'pdf--extra' breaks the naming rule", "name 'pdf--extra' must match the directory 'pdf-extra'", 'description length 0 not in 1..1024']
claude-helper -> ['name contains a reserved word (Anthropic API rule)', 'XML tags not allowed (Anthropic API rule)']Reading the output:
- Level 1 is about 57 tokens for this skill (the demo estimates tokens as characters divided by four, a rough rule). Fifty skills like this would cost around three thousand tokens of always-on context, compared with the roughly four hundred tokens for just one skill's body.
- Level 2 is the body, loaded only when triggered: 61 lines, roughly 430 tokens, far under the 500-line and 5,000-token guidance.
- Level 3 files cost nothing until used, and the script costs only its output when run. The script's own code (about 410 tokens if read) never enters the context.
- The script's error message is written for the agent: it says what is wrong, gives an example of the bad line and states the expected format. That is "solve, don't defer" from rule 7.
- The three broken skills fail for the reasons in the specification: uppercase or double hyphens in the name, a name that does not match its directory, an empty description, a reserved word, and XML tags.
2.6 Where skills run, and the limits#
From Anthropic's overview (read 1 December 2026):
| Surface | How skills are provided | Notes |
|---|---|---|
| Claude API (Messages) | List each skill's type and skill_id in container.skills, together with the code execution tool, because skills run in its container |
Pre-built skills (pptx, xlsx, docx, pdf) or custom skills uploaded through the Skills API. No network and no package installation. Not eligible for zero data retention. Workspace-wide sharing |
| Claude Code | Folders in ~/.claude/skills/ (personal) or .claude/skills/ (project), also shareable through plugins |
Full network access like any local program |
| claude.ai | Upload skills as zip files (on paid plans with code execution enabled) | Network access depends on user and admin settings |
| Managed Agents | Attach skills in the agent's skills array, or load from a GitHub repository mounted on the session |
Skills do not sync across surfaces. A skill uploaded to claude.ai is not available on the API, and the reverse. Claude Code skills are files on disk and separate from both. For the API details see 08A.8, 3.4 (container.skills) and Anthropic's Skills guide. 08E.1, 6.6 covers the Skills over MCP extension, which lets a server ship its instructions along with its tools.
Because the format is an open specification, other vendors' agents can implement the same loading. This lesson did not verify OpenAI's or any other vendor's skill support on 2 December 2026 (unverified as of 2026-12-02), so check agentskills.io and each vendor's documentation before assuming a skill will work there.
2.7 Security: a skill is code you install#
A skill gives an agent instructions and scripts, so a malicious skill can direct the agent to call tools or run code in ways that do not match its stated purpose. Anthropic's guidance says to use skills only from sources you trust (ones you wrote or got from the vendor), and to audit everything in the folder: SKILL.md, scripts, images and other resources. Look for unexpected network calls, unusual file access and operations that do not fit the stated purpose. Skills that fetch external URLs are riskier, because the fetched content can carry instructions and even a trustworthy skill can be compromised if its external dependencies change. Treat adding a skill like installing software (12.6, 4.6 uses the same review mindset for MCP servers, and 14A.7 covers supply-chain governance).
2.8 Skills, tools, MCP and instruction files#
| What it is | Loaded | Best for | |
|---|---|---|---|
| Skill | A folder of instructions, scripts and references | On demand, in three levels | Repeatable procedures and domain know-how: "how we write release notes" |
| Tool | A function the model can call | Definition in context on every request (unless deferred, see Part 3) | Actions and queries with clear inputs |
| MCP server | A packaged set of tools, resources and prompts, served by someone else | Tool definitions in context | Reusing integrations across agents (08E.2) |
AGENTS.md and similar |
Always-on project instructions | Always | Short, universal rules for a repository (08B.5) |
| System prompt | The agent's base instructions | Always | Role and global rules |
A good split: rules that always apply go in the always-on file, procedures that apply sometimes go in skills, actions are tools. A skill can tell the agent how to use a tool well. A tool cannot teach a procedure.
Part 3: Tool selection at scale#
08A.6, 1.8 collects the accuracy evidence and 08A.8, Part 8 compares the provider mechanisms in one table. This part extends them with the ladder of fixes, the provider details (limits, data-retention and cache rules) and a runnable retrieval harness that measures recall@k.
3.1 Why a long tool list hurts#
Every tool definition is text in the model's context on every request. Three costs grow with the list:
| Cost | What happens |
|---|---|
| Tokens (money and latency) | Definitions are input tokens every turn. Anthropic's tool search page says a typical multi-server setup (GitHub, Slack, Sentry, Grafana and Splunk) can use about 55,000 tokens of definitions before any work starts |
| Accuracy | The same page says Claude's ability to pick the right tool degrades once you exceed 30 to 50 available tools. 08A.6, 1.8 collects independent evidence: the LongFuncEval study (arXiv 2505.10570) measured performance drops of 7 to 85 percent as the number of tools grew, and OpenAI's function calling guide gives a soft suggestion of fewer than 20 functions available at the start of a turn |
| Cache and complexity | Changing the tool list changes the prompt prefix, which can break prompt caching (03.7). More tools means more near-duplicate names for the model to confuse |
3.2 The ladder of fixes#
Take the steps in this order. Each one is cheaper and more predictable than the next.
- Design fewer, better tools. Merge near-duplicates, use task-level tools, write clear names and descriptions (08A.6). This is usually the right answer.
- Give each agent only the tools its role needs. A support agent does not need deployment tools. Roles, per-task tool sets and gateway allowlists (08E.3) keep the visible list short. Providers also let you restrict the active set per request (
allowed_toolsorallowed_function_names) while keeping definitions cached (03.5, 3.1). - Use tool search with deferred loading for genuinely large catalogues (dozens to thousands of tools): the model starts with a search tool and a few core tools, searches, and the matching definitions are loaded on demand.
- Build your own retrieval when you need a different ranking (embeddings, your own metadata, permissions) or a provider has no built-in search.
3.3 The pattern: search, load, call#
All forms of dynamic tool loading share one loop:
- The context starts with a small fixed set of tools plus a search tool.
- The model realises it needs a capability it does not see and calls the search tool with a query.
- The system returns the top few matching tool definitions and makes them callable.
- The model calls one of them. Loaded tools stay available for later turns.
The scripted loop in 3.5 runs this pattern. First, how the two primary providers implement it.
3.4 Provider tool search: Anthropic and OpenAI#
Anthropic: the tool search tool (platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool, read 2 December 2026). Status: stable. It is eligible for zero data retention (excluding certain models) and not eligible for HIPAA. It is supported on the models the page lists (the Claude 4.5 generation and later, and not Claude Opus 4.1 and earlier).
- Two variants.
tool_search_tool_regex_20251119, where Claude writes Python regular expressions (matched case-insensitively, pattern up to 200 characters) over tool names, descriptions and argument names and descriptions. Andtool_search_tool_bm25_20251119, where Claude writes natural-language queries (up to 500 characters). - How you use it. Include the search tool in
tools. Send every tool definition in thetoolsarray on every request, and mark the ones that should not load up front withdefer_loading: true. The deferred definitions stay out of the context until discovered. At least one tool must not be deferred (normally the search tool itself, which must never be deferred), and the page recommends keeping your three to five most-used tools non-deferred. - What comes back. Claude's search appears as a
server_tool_useblock. The API returns matches astool_referenceblocks (5 by default, and Claude can set alimitfrom 1 to 10,000), expands them into full definitions, and Claude calls the discovered tool. You do not return atool_resultfor the search call, and you pass the assistant content back unchanged on the next turn. - Limits. Up to 10,000 deferred tools per request.
- Cache. The API excludes deferred tools from the system-prompt prefix, which is how
defer_loadingpreserves prompt caching. A deferred tool cannot also carrycache_control(that is a 400 error). - MCP. For tools from the MCP connector you set
defer_loadingonce in themcp_toolset'sdefault_configor per tool inconfigs, not on individual definitions. - Your own search. You can return
tool_referenceblocks from a custom tool, so embeddings or any ranking you like can drive discovery. Every referenced tool still needs a definition intools. - When to use it (the page's guidance): 10 or more tools, definitions over 10,000 tokens, accuracy dropping as you add tools, aggregating several MCP servers, or a growing library. Standard tool calling is better for fewer than 10 tools, or when every tool is used in every request.
- Cost. Tool search is not metered as a separate server tool. The definitions it loads count as ordinary input tokens.
# anthropic_tool_search.py - illustrative: needs ANTHROPIC_API_KEY (not run here)
import anthropic
client = anthropic.Anthropic()
def tool(name, description, **props): # a tiny helper to keep the example short
return {"name": name, "description": description, "defer_loading": True,
"input_schema": {"type": "object", "properties": {k: {"type": v} for k, v in props.items()},
"required": list(props)}}
response = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=1024,
tools=[
{"type": "tool_search_tool_bm25_20251119", "name": "tool_search_tool_bm25"}, # never deferred
tool("billing_issue_refund", "Refund all or part of a paid invoice.", invoice_id="string"),
tool("slack_post_message", "Post a message to a Slack channel.", channel="string", text="string"),
# ... hundreds more, all sent on every request, all with defer_loading: true
],
messages=[{"role": "user", "content": "Refund invoice INV-9 and tell #support."}],
)
print([block.type for block in response.content])
# illustrative: text, server_tool_use (the search), tool_search_tool_result, text, tool_use (billing_issue_refund)OpenAI: tool_search (developers.openai.com/api/docs/guides/tools-tool-search, read 2 December 2026).
- In the Responses API, only
gpt-5.4and later models supporttool_search. - You add
{"type": "tool_search"}totoolsand setdefer_loading: trueon the functions to defer. For MCP servers you set it on the server's tool definition. Namespaces ({"type": "namespace", "name": ..., "description": ..., "tools": [...]}) group related functions.defer_loadingapplies to the functions inside the namespace, not to the namespace object. The guide recommends keeping each namespace to fewer than 10 functions. - Two modes. Hosted: OpenAI searches the tools you declared and returns the loaded subset in the same response (output items
tool_search_callandtool_search_output). Client: the model emits atool_search_call, your application does the lookup, and you return atool_search_output. - It is "designed to preserve the model's cache". Newly discovered tools are added at the end of the context window, and changing the loaded set mid-conversation breaks the cache from that point on.
# openai_tool_search.py - illustrative: needs OPENAI_API_KEY and a model that supports tool_search (not run here)
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6.2-astra", # example name; tool_search needs gpt-5.4 or later in the Responses API
input="Refund invoice INV-9 and tell #support.",
tools=[
{"type": "tool_search"},
{
"type": "namespace",
"name": "billing",
"description": "Invoices, refunds and credit notes.",
"tools": [{
"type": "function",
"name": "issue_refund",
"description": "Refund all or part of a paid invoice.",
"defer_loading": True,
"parameters": {"type": "object", "properties": {"invoice_id": {"type": "string"}},
"required": ["invoice_id"], "additionalProperties": False},
}],
},
# ... other namespaces, each under about 10 functions, each function deferred
],
)
print([item.type for item in response.output])
# illustrative: tool_search_call, tool_search_output, function_call (with a namespace field), ...Both patterns are in 08A.8, Part 8, which also covers OpenRouter and notes that Gemini had no documented equivalent when 08A.8 was written (not re-verified here).
3.5 Build your own tool retrieval, and measure it#
A provider's search is a black box. Building a small one shows what tool search actually does and, more important, how to measure whether it finds the right tool. The program below defines 50 fake tools across 10 services, scores them with BM25, and then runs a scripted agent that loads tools on demand.
# tool_retrieval.py - BM25 tool search over 50 fake tools, plus a scripted dynamic-loading loop (stdlib only).
import json, math, re
from collections import Counter
TOOLS = [ # (name, description) - 50 fake tools across 10 services
("github_create_issue", "Open a new issue in a repository with a title and body."),
("github_list_pull_requests", "List open pull requests for a repository."),
("github_merge_pull_request", "Merge an approved pull request into its base branch."),
("github_search_code", "Search source code across repositories by keyword."),
("github_get_commit", "Fetch one commit with its diff and author."),
("slack_post_message", "Post a message to a Slack channel."),
("slack_search_messages", "Search message history in Slack channels."),
("slack_list_channels", "List the public channels in the workspace."),
("slack_set_status", "Set the current user's status text and emoji."),
("slack_upload_file", "Upload a file to a channel or conversation."),
("billing_get_invoice", "Fetch one invoice by id with line items and totals."),
("billing_list_invoices", "List invoices for a customer, newest first."),
("billing_issue_refund", "Refund all or part of a paid invoice back to the customer's card."),
("billing_update_payment_method", "Replace the card on file for a customer."),
("billing_create_credit_note", "Issue a credit note that reduces a future invoice."),
("tickets_create_ticket", "Create a support ticket with subject, body and priority."),
("tickets_list_open", "List open support tickets assigned to a team."),
("tickets_add_comment", "Add a public or internal comment to a ticket."),
("tickets_close_ticket", "Close a ticket and record the resolution."),
("tickets_assign", "Assign a ticket to an agent or a queue."),
("calendar_create_event", "Create a calendar event with attendees and a time."),
("calendar_find_free_slot", "Find a time when all listed people are free."),
("calendar_list_events", "List events in a date range."),
("calendar_cancel_event", "Cancel an event and notify attendees."),
("email_send", "Send an email to one or more recipients."),
("email_search", "Search the mailbox by sender, subject or text."),
("email_draft_reply", "Create a draft reply to an email thread."),
("db_run_readonly_query", "Run a read-only SQL query against the analytics warehouse."),
("db_describe_table", "Show columns and types for a warehouse table."),
("db_list_tables", "List tables in the analytics warehouse."),
("db_export_csv", "Export a query result to a CSV file."),
("files_read", "Read a text file from the workspace."),
("files_write", "Write or overwrite a text file in the workspace."),
("files_list_directory", "List files in a workspace directory."),
("files_delete", "Delete a file from the workspace."),
("web_search", "Search the public web and return result snippets."),
("web_fetch_page", "Download a web page and return readable text."),
("monitoring_get_alerts", "List firing alerts from the monitoring system."),
("monitoring_query_metric", "Query a time series metric over a time window."),
("monitoring_silence_alert", "Silence an alert for a fixed duration."),
("monitoring_get_dashboard", "Return the panels of a monitoring dashboard."),
("deploy_start_release", "Start a production release of a service version."),
("deploy_rollback", "Roll a service back to the previous release."),
("deploy_get_status", "Show the status of a release or rollback."),
("deploy_list_services", "List services and their current versions."),
("hr_get_employee", "Look up an employee profile and manager."),
("hr_request_time_off", "Submit a vacation or sick leave request."),
("hr_list_holidays", "List company holidays for a year."),
("crm_find_contact", "Find a customer contact by name or email."),
("crm_log_call", "Log a call note on a customer account."),
]
STEM = False # flipped on below to show what stemming buys
def stem(word): # a deliberately crude stemmer: strip "ing", "es", "s"
for suffix in ("ing", "es", "s"):
if STEM and word.endswith(suffix) and len(word) - len(suffix) >= 3:
return word[: -len(suffix)]
return word
def tokens(text):
return [stem(w) for w in re.split(r"[^a-z0-9]+", text.lower()) if w]
class BM25:
def __init__(self, docs, k1=1.5, b=0.75):
self.docs, self.k1, self.b = [Counter(d) for d in docs], k1, b
self.len = [sum(c.values()) for c in self.docs]
self.avg = sum(self.len) / len(docs)
df = Counter(t for d in self.docs for t in d)
n = len(docs)
self.idf = {t: math.log(1 + (n - f + 0.5) / (f + 0.5)) for t, f in df.items()}
def score(self, query):
out = []
for d, ln in zip(self.docs, self.len):
s = 0.0
for t in tokens(query):
if t in d:
tf = d[t]
s += self.idf[t] * tf * (self.k1 + 1) / (tf + self.k1 * (1 - self.b + self.b * ln / self.avg))
out.append(s)
return out
def build(fields):
docs = []
for name, desc in TOOLS:
text = (name if "name" in fields else "") + " " + (desc if "desc" in fields else "")
docs.append(tokens(text))
return BM25(docs)
def search(index, query, k=5):
scores = index.score(query)
ranked = sorted(range(len(TOOLS)), key=lambda i: -scores[i])[:k]
return [TOOLS[i][0] for i in ranked if scores[i] > 0]
QUERIES = [ # (what the user/model wants, the tool that should be found)
("give the customer their money back for invoice 9", "billing_issue_refund"),
("open a bug report in the repo", "github_create_issue"),
("who is free on thursday afternoon", "calendar_find_free_slot"),
("revert the bad release", "deploy_rollback"),
("show me the columns of the orders table", "db_describe_table"),
("tell the team in chat that the deploy finished", "slack_post_message"),
("is anything alerting right now", "monitoring_get_alerts"),
("I need two weeks off in august", "hr_request_time_off"),
("merge the approved pull request", "github_merge_pull_request"),
("find emails from the supplier", "email_search"),
]
def recall(index, k):
return sum(want in search(index, q, k) for q, want in QUERIES) / len(QUERIES)
def approx_tokens(obj): # rough rule of thumb: ~4 characters per token
return math.ceil(len(json.dumps(obj)) / 4)
if __name__ == "__main__":
print(f"{len(TOOLS)} tools; full list ~= {approx_tokens([{'name': n, 'description': d} for n, d in TOOLS])} tokens (4 chars/token estimate)\n")
print("== Recall of the right tool in the top-k, by what the index sees (no stemming) ==")
for label, fields in [("name only", {"name"}), ("description only", {"desc"}), ("name + description", {"name", "desc"})]:
idx = build(fields)
print(f"{label:20} recall@1={recall(idx, 1):.1f} recall@3={recall(idx, 3):.1f} recall@5={recall(idx, 5):.1f}")
idx = build({"name", "desc"})
print("\n== Per-query results (name + description index, top 3) ==")
for q, want in QUERIES:
got = search(idx, q, 3)
print(f"{'HIT ' if want in got else 'MISS'} {q!r:52} want={want:26} got={got}")
print("\n== Fix 1: stemming (alerting/alerts, emails/email) ==")
STEM = True
idx = build({"name", "desc"})
print(f"name + description recall@3={recall(idx, 3):.1f}")
for q, want in QUERIES:
if want not in search(idx, q, 3):
print("still MISS:", repr(q), "want", want, "got", search(idx, q, 3))
print("\n== Fix 2: put the user's words in the description (the vocabulary gap) ==")
miss = "tell the team in chat that the deploy finished"
print("before:", search(idx, miss, 3))
TOOLS[5] = ("slack_post_message", "Post a message to a Slack channel: tell the team, chat, announce an update.")
idx = build({"name", "desc"})
print("after: ", search(idx, miss, 3))
print(f"name + description recall@3={recall(idx, 3):.1f}")
print("\n== Dynamic loading: a scripted agent with a tool_search meta-tool ==")
active = {"tool_search"}
defs = {n: {"name": n, "description": d} for n, d in TOOLS}
def tokens_in_context():
return approx_tokens([defs.get(n, {"name": n, "description": "Search the tool catalog."}) for n in active])
eager = approx_tokens(list(defs.values()))
script = [("tool_search", {"query": "refund invoice customer"}),
("billing_issue_refund", {"invoice": "INV-9"}),
("tool_search", {"query": "post message channel"}),
("slack_post_message", {"channel": "#support", "text": "refund done"})]
for turn, (tool, args) in enumerate(script, 1):
assert tool in active, f"model called {tool} but it was never loaded"
print(f"turn {turn}: context has {len(active):2d} tools (~{tokens_in_context():4d} tokens; eager would be {len(defs)} tools ~{eager} tokens) -> model calls {tool}")
if tool == "tool_search":
found = search(idx, args["query"], 3)
active |= set(found)
print(f" search {args['query']!r} loaded {found}")50 tools; full list ~= 1183 tokens (4 chars/token estimate)
== Recall of the right tool in the top-k, by what the index sees (no stemming) ==
name only recall@1=0.4 recall@3=0.4 recall@5=0.4
description only recall@1=0.6 recall@3=0.6 recall@5=0.6
name + description recall@1=0.7 recall@3=0.7 recall@5=0.7
== Per-query results (name + description index, top 3) ==
HIT 'give the customer their money back for invoice 9' want=billing_issue_refund got=['billing_issue_refund', 'billing_update_payment_method', 'billing_list_invoices']
HIT 'open a bug report in the repo' want=github_create_issue got=['github_create_issue', 'tickets_list_open', 'slack_list_channels']
HIT 'who is free on thursday afternoon' want=calendar_find_free_slot got=['calendar_find_free_slot', 'crm_log_call', 'billing_update_payment_method']
HIT 'revert the bad release' want=deploy_rollback got=['deploy_rollback', 'deploy_start_release', 'deploy_get_status']
HIT 'show me the columns of the orders table' want=db_describe_table got=['db_describe_table', 'deploy_get_status', 'monitoring_get_dashboard']
MISS 'tell the team in chat that the deploy finished' want=slack_post_message got=['slack_list_channels', 'deploy_rollback', 'deploy_get_status']
MISS 'is anything alerting right now' want=monitoring_get_alerts got=[]
HIT 'I need two weeks off in august' want=hr_request_time_off got=['hr_request_time_off', 'slack_search_messages', 'calendar_list_events']
HIT 'merge the approved pull request' want=github_merge_pull_request got=['github_merge_pull_request', 'github_list_pull_requests', 'hr_request_time_off']
MISS 'find emails from the supplier' want=email_search got=['files_delete', 'crm_find_contact', 'files_read']
== Fix 1: stemming (alerting/alerts, emails/email) ==
name + description recall@3=0.8
still MISS: 'tell the team in chat that the deploy finished' want slack_post_message got ['slack_list_channels', 'deploy_rollback', 'deploy_get_status']
still MISS: 'find emails from the supplier' want email_search got ['crm_find_contact', 'files_delete', 'files_read']
== Fix 2: put the user's words in the description (the vocabulary gap) ==
before: ['slack_list_channels', 'deploy_rollback', 'deploy_get_status']
after: ['slack_post_message', 'slack_list_channels', 'deploy_rollback']
name + description recall@3=0.9
== Dynamic loading: a scripted agent with a tool_search meta-tool ==
turn 1: context has 1 tools (~ 17 tokens; eager would be 50 tools ~1193 tokens) -> model calls tool_search
search 'refund invoice customer' loaded ['billing_issue_refund', 'billing_get_invoice', 'billing_create_credit_note']
turn 2: context has 4 tools (~ 100 tokens; eager would be 50 tools ~1193 tokens) -> model calls billing_issue_refund
turn 3: context has 4 tools (~ 100 tokens; eager would be 50 tools ~1193 tokens) -> model calls tool_search
search 'post message channel' loaded ['slack_post_message', 'slack_search_messages', 'slack_list_channels']
turn 4: context has 7 tools (~ 179 tokens; eager would be 50 tools ~1193 tokens) -> model calls slack_post_messageWhat the output teaches:
- What the index sees matters. Searching names only found 40 percent of the right tools, descriptions only 60 percent, and both together 70 percent. Tool names are short, so the description carries most of the signal. This matches Anthropic's advice that search covers names, descriptions and argument names and descriptions, and that you should add keywords people actually use.
- Keyword search has a vocabulary gap. "is anything alerting right now" returned nothing: the tool says "alerts", the query says "alerting". A crude stemmer (Fix 1) fixed that and "emails/email", lifting recall at 3 to 0.8. It also turned "files" into the odd token "fil", which is harmless here but shows why a real system uses a proper stemmer, or embeddings.
- Descriptions are the lever. "tell the team in chat that the deploy finished" still missed
slack_post_message, because the tool never uses the words "tell", "team" or "chat". Adding the words users actually say to the description (Fix 2) fixed it, lifting recall at 3 to 0.9. This is the same lesson as 08A.6 at larger scale: tool descriptions are retrieval text. - Common words add noise. The remaining miss, "find emails from the supplier", is pulled toward
crm_find_contactand the file tools by the common words "find", "from" and "the". A stop-word list, or embeddings, or hybrid scoring would help. We left it in on purpose: a retrieval step has a failure rate, and you should know yours. - Dynamic loading keeps the context small. In the scripted loop the context held 1 tool (about 17 estimated tokens) at turn 1, 4 after the first search and 7 after the second, against 50 tools (about 1,190 estimated tokens) if loaded eagerly. These 50 tools have one-line descriptions and no schemas, so the absolute numbers are small. Real definitions are much longer, which is why Anthropic's figure for a multi-server setup is about 55,000 tokens.
What a production retrieval step adds. Embedding-based or hybrid ranking (keywords plus vectors), metadata filters (only tools this user may use, from the gateway's allowlist), always-on core tools, a cap on how many tools are loaded in total, a fallback when the search returns nothing ("no matching tools: say so or ask the user"), and logging of every query and result so you can improve descriptions. Anthropic's recommendation to monitor which tools Claude discovers is the same loop.
3.6 Keeping the list small in practice#
| Technique | How |
|---|---|
| Namespaces | Prefix names by service (github_, slack_). One search then matches the whole group, and similar names stop colliding |
| Consolidate | One issue tool with an action argument can replace five. Do it when the actions share a schema (08A.6, 2.2) |
| Core set plus the rest deferred | Keep the three to five tools used in almost every task loaded. Defer the long tail |
| Per-role and per-task sets | Different agents get different lists. A planner may need none of the executor's tools |
| Per-server allowlists | Connect a server but expose only the tools you need (08E.2, Part 8 shows allowed_tools and mcp_toolset) |
| Sub-agents | A sub-agent with its own small tool list does a subtask and returns a summary (08A.11) |
| Keep the list stable within a conversation | Adding and removing tools mid-run breaks prompt caching. Load by appending, as the providers do |
| Measure | Recall@k for retrieval, and tool-call precision and recall end to end (Part 4) |
Part 4: Evaluate it#
Three mechanisms, three different things to test. In each case the evaluation has a deterministic layer you can run without a model and a model-in-the-loop layer.
Read the concept lessons first.
- 10A.7 Evaluating Agents, Tool Use and Multimodal Systems: tool-call precision and recall is exactly the metric for "did tool selection pick the right tools", efficiency, loops and recovery covers wasted searches, and task success rate and cost per successful task tells you whether dynamic loading paid off.
- 10A.11 Evaluating Agent Memory and Context: how much of the context window tool definitions and skills occupy is a context question.
- 10A.12 Evaluating Multi-Agent Systems and Validating User Simulators: handoff correctness and attribution apply when one agent delegates to another over A2A.
Then the DeepEval lessons (required track, tooling for the same ideas): 10B.2 fundamentals, 10B.3 judges and custom metrics, 10B.4 built-in metrics, 10B.5 tracing and agent evaluation (its Part 12 covers MCP metrics, relevant when the tool list comes from MCP servers, and its Part 13 covers multi-agent spans), 10B.6 datasets and simulation and 10B.7 red teaming, CI and platform.
Then, optionally, the Inspect lessons. 10B.14 Inspect: tools and agents (optional) covers MCP tools and multi-agent evaluation mechanics. The rest of the Inspect track is in 10B.8, 10B.9, 10B.10, 10B.11, 10B.12, 10B.13, 10B.15, 10B.16 and 10B.17, all optional.
4.1 What to measure for this topic#
Tool selection at scale
- Retrieval recall@k: with a labelled set of (task, correct tool) pairs, how often is the right tool in the top k? This is deterministic and cheap, so run it on every change to a tool name or description (the program in 3.5 is the harness).
- End-to-end tool-call precision and recall: with the model in the loop, did it pick the right tools, with and without tool search? Compare the two.
- Search behaviour: share of tasks where the model did not search when it should have, searches per task, and tasks where the search returned nothing.
- Cost and latency: input tokens per task and time to first tool call, with and without deferred loading.
Skills
- Trigger accuracy: for a set of prompts that should use the skill and a set that should not, how often does it load? (A description problem.)
- Task success with and without the skill on the same tasks. Anthropic's guide recommends a baseline run without the skill, then iterating until the skill closes the gap, with at least three evaluation scenarios and tests on each model you will use.
- Script behaviour: unit tests for bundled scripts, including the error paths.
A2A
- Task completion: share of delegated tasks that reach
COMPLETEDwith an artifact that passes your outcome check. - Interruption handling: for tasks that go to
INPUT_REQUIRED, does your agent answer correctly instead of looping? - Containment: when the remote agent returns text that contains instructions, does your agent ignore them? (Test with an injected artifact, 12.2.)
4.2 A concrete tiny eval design#
| Part | Choice |
|---|---|
| Inputs | 40 tasks over the 50-tool catalogue: 30 each needing one tool, 6 needing two tools, 4 needing no tool. Each with the expected tool names |
| Retrieval check (no model) | Recall@3 and recall@5 of the search step on the 36 tasks that need tools |
| End-to-end check (model or scripted model) | Run twice, once with all 50 tools loaded and once with tool search. Measure tool-call precision, tool-call recall, task success and input tokens per task |
| Skill check | 10 prompts that should trigger drafting-release-notes and 10 that should not. Count loads. Then 5 release-note tasks with and without the skill, scored by a rubric: sections present, no ticket ids, no invented entries |
| Pass rule | Retrieval recall@5 at least 0.9. With tool search, tool-call recall no more than 2 points below the all-tools baseline and input tokens per task at least 50 percent lower. Skill: at least 9 of 10 should-trigger prompts load it and at most 1 of 10 should-not prompts does. Rubric pass on at least 4 of 5 tasks with the skill, and better than without |
Choose the thresholds before you run, and re-run the whole set whenever you change a tool's name or description or edit a skill's description. Those edits change behaviour without changing code.
Part 5: Protocol watchlist#
Reference
MCP, A2A and Agent Skills are the three extension mechanisms this lesson teaches. Around them, a second wave of protocols is being proposed for two jobs: showing an agent's work in a user interface, and letting an agent pay for things. You do not need to build on any of them yet. You do need to recognise the names when they appear in a framework's docs or a vendor's announcement, and to know what each one is for. This table is a watchlist, not a recommendation.
As of 2 December 2026. Each row was checked against the project's own site or repository on that date. Statuses change fast, so treat every cell as a dated snapshot.
| Protocol | What it is | Who backs it | Status | When you would care | Official link |
|---|---|---|---|---|---|
| AG-UI (Agent User Interaction Protocol) | An event-based protocol for one bidirectional stream between an agent backend and a front end: streaming text, shared state, frontend tool calls and human-in-the-loop interrupts | Created by CopilotKit (with LangChain and CrewAI as partners). Open source under the MIT licence. Its docs list integrations with Microsoft Agent Framework, Google ADK, AWS Strands Agents, Mastra, Pydantic AI, LlamaIndex and others | The project's README says 1.0 is the current stable specification. The docs mark some integrations "in progress" | You build a chat or agent front end and want one event vocabulary across agent frameworks (13A.2 compares it with your own event contract) | docs.ag-ui.com |
| A2UI (Agent-to-User Interface) | A generative-UI format: the agent sends a description of an interface as data, and the app draws it with its own native components | Open source (Apache-2.0); the repository is under the google GitHub organization |
The site shows specification v1.0. The repository says some packages are not published yet and can be used from source | You want agents to produce forms and layouts that match your app's design and security rules | a2ui.org |
| MCP Apps | An official extension to MCP: a tool points to a ui:// resource, and the host shows that HTML in a sandboxed iframe inside the conversation, talking to the host over postMessage |
The Model Context Protocol project. The docs list Claude, Claude Desktop, VS Code GitHub Copilot, Microsoft 365 Copilot, Goose and Postman as hosts | An extension, not part of core MCP. Host support varies, so check the client matrix | You ship an MCP server and want an interactive view (chart, form, dashboard) in the chat | modelcontextprotocol.io/extensions/apps/overview |
| MCP-UI | The community SDK (@mcp-ui/server, @mcp-ui/client) that pioneered UI over MCP |
Open source (Apache-2.0), led by Ido Salomon with Liad Yosef | Standardized into MCP Apps: the project's site says so, and its packages now implement MCP Apps. A legacy adapter remains for hosts that have not adopted MCP Apps | You find older MCP-UI code, or you want a client library for hosting MCP Apps. For new work, read the MCP Apps row | mcpui.dev |
| WebMCP | A proposed browser API that lets a web page register JavaScript functions as tools for an AI agent, so the agent calls them instead of clicking and scraping | The W3C Web Machine Learning Community Group. Editors in the draft are from Microsoft and Google | A Draft Community Group Report dated 1 December 2026. It is not a W3C Standard and not on the Standards Track. The repository marks it experimental | You own a website and expect browser-based agents to use it | github.com/webmachinelearning/webmcp |
| AP2 (Agent Payments Protocol) | An open protocol that lets AI agents make payments with merchants securely and interoperably | Google. The site says it is an extension of A2A and works with MCP, and that standards work continues in FIDO Alliance working groups | The site references v0.2. The repository shows no published release | You build an agent that pays merchants and want a payments protocol designed to sit beside A2A and MCP | ap2-protocol.org |
| ACP (Agentic Commerce Protocol) | An open standard for checkout between a buyer, an AI agent and a business. It works over REST or MCP | OpenAI and Stripe, listed as founding maintainers (Apache-2.0) | Beta, with date-based versions. The latest stable spec date is 2026-04-17 | You sell online and want agents (ChatGPT is the first platform) to check out on your store | agenticcommerce.dev |
| UCP (Universal Commerce Protocol) | A common language for platforms, agents and businesses across discovery, cart, checkout and order management | The site lists Google, Shopify, Etsy, Wayfair, Target, Walmart, Stripe and others as co-developers, and Visa, Mastercard and PayPal among endorsers (Apache-2.0) | The site has "latest" and "draft" specification sections; some areas are draft | You build commerce features and need to know the second major standard next to ACP | ucp.dev |
The first five rows are about interfaces: AG-UI and A2UI describe how agent output reaches a screen, MCP Apps and MCP-UI put a UI inside an MCP host, and WebMCP lets a web page expose its own tools to an agent. They are not rivals in a strict sense. The AG-UI docs list A2UI and MCP Apps as generative-UI options that can travel over AG-UI, and the A2UI site says an A2UI surface can run inside an MCP App. The last three rows are about money, and they overlap more: ACP and UCP both cover checkout, while AP2 is a payments protocol that extends A2A.
How to tell whether a protocol has gone mainstream. Do not count logos on a landing page. Look for four things: a dated specification release that is not marked draft or beta, a neutral or multi-vendor home for its governance, support that shows up in the release notes of at least two unrelated frameworks or hosts you already use, and a working reference implementation you can run yourself. When a protocol you need passes all four, move it from this watchlist into your design.
Common misconceptions#
- "A2A replaces MCP." They solve different problems. MCP connects an agent to tools and data. A2A connects agents to each other. Real systems use both.
- "A2A is just remote function calling." The unit is a task with a lifecycle (including interrupted states where the remote agent asks you a question), messages, artifacts and streaming. A function call has none of that.
- "A2A skills and Agent Skills are the same." An A2A skill is an entry in an Agent Card advertising what a remote agent does. An Agent Skill is a folder an agent loads for itself.
- "Old A2A examples are current." Version 1.0 renamed methods, restructured the Agent Card and changed state names. Check the version of any snippet.
- "A skill is a long prompt." A skill is loaded in levels. Only the name and description are always in context, and scripts cost only their output. That is the point.
- "The description is just a label." It is the trigger. The agent decides whether to load the skill from the description alone.
- "More skills or tools always help." Every always-on description or definition costs context, and long tool lists reduce selection accuracy. Add capability on demand.
- "Tool search removes the need for good descriptions." It makes descriptions more important, because search matches on them. Both providers' guidance says to use clear names and keywords.
- "
defer_loadingmeans I send fewer tools." On Anthropic's API you still send every definition on every request. The flag controls what enters the model's context, not what is in the request. - "Installing a skill is safe because it is only text." Skills can include scripts and can direct the agent to use its tools. Treat them like software you install.
Key takeaways#
- A2A is for agent-to-agent work across boundaries. A client reads an Agent Card (at
/.well-known/agent-card.json), sends a message, and gets back a task that moves through states, with artifacts as results. The current specification is 1.0 (v1.0.0 released 12 March 2026). - Terminal task states are completed, failed, canceled and rejected. Interrupted states are input-required and auth-required.
- MCP is vertical, A2A is horizontal. Use a tool for a function, an in-process sub-agent for your own code, and A2A for an opaque agent run by someone else.
- A skill is a folder with a
SKILL.md. Required frontmatter:name(matches the directory, lowercase, hyphens, up to 64 characters) anddescription(up to 1,024 characters, what and when). - Progressive disclosure: about 100 tokens of metadata always, the body under 5,000 tokens and 500 lines when triggered, and resources only when needed. Scripts cost only their output.
- Write skills concisely, with a clear third-person description, one-level references, workflows with feedback loops, scripts that handle their own errors and evaluations built first.
- Long tool lists cost tokens and accuracy. Anthropic's docs report about 55,000 tokens for a typical multi-server setup and degraded selection above 30 to 50 tools.
- The ladder: fewer better tools, role-based lists, tool search with deferred loading, your own retrieval.
- Provider tool search: Anthropic's
tool_search_tool_regex_20251119andtool_search_tool_bm25_20251119withdefer_loading: true, and OpenAI'stool_search(gpt-5.4 and later) with deferred functions and namespaces. Both are designed to keep the prompt cache usable. - Retrieval has a failure rate. Measure recall@k, fix descriptions first, and filter by permission before ranking.
Terms introduced in this lesson#
| Term | Meaning |
|---|---|
| A2A (Agent2Agent) | An open protocol for one agent to delegate tasks to another agent and follow their progress |
| A2A task | A stateful unit of work with an id, a contextId, a status, artifacts and a history |
| Task state | One of SUBMITTED, WORKING, COMPLETED, FAILED, CANCELED, INPUT_REQUIRED, REJECTED, AUTH_REQUIRED (with a TASK_STATE_ prefix in v1.0) |
| Terminal state / interrupted state | Terminal: the task is over. Interrupted: the task waits for the client to supply input or credentials |
| Push notification (A2A) | A webhook the server calls when a task changes, so the client need not poll |
| Agent Skill | A folder with a SKILL.md and optional scripts, references and assets, loaded by an agent on demand |
SKILL.md |
The required file of a skill: YAML frontmatter plus Markdown instructions |
| Progressive disclosure | Loading a skill in levels: metadata always, body when triggered, resources when needed |
| Skill trigger | The agent's decision to load a skill, based on its description |
| Degrees of freedom | How tightly a skill constrains the agent: free text, a template, or an exact command |
Deferred loading (defer_loading) |
Marking a tool so its definition stays out of the context until it is discovered |
tool_reference |
The block Anthropic's API returns for a discovered tool, expanded into its full definition |
| BM25 | A keyword ranking formula that favours rare words and gives diminishing returns for repeats |
| Recall@k | The share of queries where the correct item is among the top k results |
| Tool budget | The maximum number of tools visible to an agent at once |
| AG-UI | An open event-based protocol for streaming an agent's output and state to a front end (Part 5) |
| MCP Apps | An official MCP extension that lets a tool return an interactive HTML view, shown in a sandboxed iframe by the host (Part 5) |
| WebMCP | A proposed browser API for a web page to register tools an AI agent can call (Part 5) |
| Agentic commerce protocols (AP2, ACP, UCP) | Open protocols for agents to pay or check out with merchants (Part 5) |
Exercises#
- Add stop words. Add a small stop-word list (
the,a,from,in,of,to,for,that) totool_retrieval.pyand re-measure recall@3. Which of the three misses does it fix? Hint: filter intokens()before stemming; the miss "find emails from the supplier" is the one most likely to move, but check, because removing words can also hurt. - Hybrid score. Add a second scorer that gives a bonus when a query word equals a tool's namespace (the part before the first underscore), and combine it with BM25 by adding the two scores. Does recall improve, and which query benefits? Hint: split the tool name on
_and take element 0; a bonus of about 1.0 is comparable to a typical BM25 score here. - Permission filter. Give each fake tool a set of allowed roles and make
search()accept a role, filtering before ranking. Show that a support role never getsdeploy_rollbackback, even for the query "revert the bad release". Hint: build a list of allowed indexes first and score only those, so a forbidden tool cannot appear in the top k. - A second skill. Write a skill
reviewing-sql-querieswith aSKILL.md, one reference file and a validating script, and runskills_demo.py'svalidateon it. Then make the description worse ("Helps with SQL.") and explain, with the rules from 2.4, why it will trigger badly even though the validator passes. Hint: the validator checks format, not quality; the spec only requires 1 to 1,024 characters and the quality rule is "what and when, with keywords". - A2A lifecycle. Extend
a2a_sketch.pyso that an agent can returnTASK_STATE_AUTH_REQUIREDfor a request that needs a credential, and make the client resume the same task after supplying it. Add the transition rules you need. Hint: addTASK_STATE_AUTH_REQUIREDas a state the working task can enter (the table already lists it as interrupted); the resume message carries the sametaskId. - Eval the trigger. Write 10 should-trigger and 10 should-not-trigger prompts for
drafting-release-notes. Without a model, write a crude trigger simulator that matches prompt words against the description, count hits and false positives, and list which prompts a better description would fix. Hint: use the BM25 class fromtool_retrieval.pywith the skill descriptions as documents, and treat the top match above a threshold as a trigger.
Check yourself#
- What is the difference between how MCP and A2A connect agents to things?MCP connects an agent to tools, resources and prompts: functions and data, mostly stateless. A2A connects an agent to another agent that works on a task, with state, several turns and opaque internals.
- Where does an A2A client find an agent's capabilities, and what are two things it lists?In its Agent Card at
/.well-known/agent-card.json. It lists, for example, supported interfaces (URL, binding, version), capabilities (streaming, push notifications), skills, security schemes and default input and output modes. - Name the terminal and the interrupted A2A task states.Terminal: completed, failed, canceled, rejected. Interrupted: input-required and auth-required.
- What are the two required fields of
SKILL.mdfrontmatter, and one constraint on each?nameanddescription. The name is 1 to 64 characters of lowercase letters, numbers and hyphens, with no leading or trailing hyphen and no--, and must match the directory name. The description is 1 to 1,024 characters and should say what the skill does and when to use it. - What are the three levels of progressive disclosure, and roughly what does each cost?Metadata (name and description), always loaded, about 100 tokens per skill. Instructions (the
SKILL.mdbody), loaded when triggered, under about 5,000 tokens and 500 lines. Resources (scripts, references, assets), loaded only when needed, with no cost until accessed. Scripts that are run cost only their output. - Why does a script bundled in a skill cost fewer tokens than asking the model to write the same code?When the agent runs a script, only the script's output enters the context. The code itself does not, and the model does not spend tokens generating it. It is also more reliable and consistent.
- Why should a skill's description be written in the third person and include "when to use"?The description is injected into the system prompt and is the only thing the agent sees when deciding to load the skill. A mismatched point of view can confuse discovery, and without "when" the agent cannot tell which tasks it fits.
- Give two reasons a long tool list hurts an agent.It costs input tokens on every request (Anthropic reports about 55,000 tokens for a typical multi-server setup), selection accuracy drops as the number of tools grows (Anthropic says beyond 30 to 50 tools), and changing the list can break prompt caching.
- What does
defer_loading: truedo on Anthropic's API, and what must you still send?It keeps the tool's definition out of the model's context until the tool is discovered through search. You must still send every tool's full definition in thetoolsarray on each request, because the API needs them to run the search and expand the results. At least one tool, normally the search tool, must not be deferred. - In the retrieval demo, why did "is anything alerting right now" return nothing, and what fixed it?The tool says "alerts" and the query said "alerting", so exact-word matching found no overlap. A crude stemmer that reduces both to "alert" fixed it.
Further resources#
Existing lessons:
- 08A.6 Designing Tools Models Can Use, especially 1.8 How many tools is too many?.
- 08A.8 Provider Built-in and Server-Side Tools, Part 8 on tool search.
- 08A.4 Harness Engineering: skills and MCP as harness components.
- 08A.15 Coding and Computer-Use Agents: instruction files and skills.
- 08D.3 Multi-Agent Systems, 08D.1 One Agent or Several, 08E.2 MCP in Depth and 08E.3 Remote MCP.
- 12.6 Securing Tools, Agents and MCP.
Official sources (all read on 1 December 2026):
- A2A Protocol Specification, What's new in v1.0, A2A and MCP and the A2A repository and releases.
- Agent Skills specification.
- Anthropic: Agent Skills overview and Skill authoring best practices.
- Anthropic: Tool search tool.
- OpenAI: Tool search.
- LongFuncEval, arXiv:2505.10570: the study on tool catalogue size and accuracy cited in 08A.6.
Back: 08E.3 — Remote MCP: OAuth, Gateways and Many Servers
← 08E.3 — Remote MCP: OAuth, Gateways and Many Servers | Module 08E overview | Module 08F: Frameworks and Platforms →