Level 2 Agentic Coding · Agentic Coding
Extending Your Agent: Skills, Hooks, MCP and Subagents
A coding agent out of the box knows nothing about your procedures, enforces none of your rules, can't reach your other systems and does everything in one crowded context. Skills, hooks, MCP servers and subagents fix one of those each. This chapter explains what each is for, when to reach for it, and shows small working examples for a real project.
- Level
- ●●●●● Easy
- Reading
- 19 min
- To learn it well
- 45 minutes to read, an afternoon to set up
- Builds on
- 19 concepts →
- Quiz
- 5 questions ↓
This leads to
Running Agents in Parallel and in the BackgroundThe full path from zero — 19 concepts before this one
- What Is AI?
- Vectors
- Python for AI
- How Machines Learn
- Dot Product, Norms and Similarity
- Large Language Models, Explained Simply
- AI Fluency: Working Well with AI
- Prompt Engineering
- Using LLM APIs
- Asking Well: Everyday Prompting
- Embeddings and Semantic Search
- Structured Output and JSON
- What Is Agentic Coding?
- Retrieval-Augmented Generation
- Tool Use and Function Calling
- Planning and Specs: Telling an Agent What to Build
- Context Engineering and Memory
- Model Context Protocol
- Project Context and Memory Files
- Extending Your Agent: Skills, Hooks, MCP and Subagents
Read them roughly in this order. See it on the concept map →
Why it matters
After a few weeks with a coding agent, the same frustrations come back:
- You type the same long prompt every time you add a command to your project: "add the subcommand in
main(), write a pure function that takes aPath, test it withtmp_path, update the README, run ruff and mypy". - You wrote "never push" and "never touch
expenses.csv" in the memory file, and the agent almost always obeys. Almost. - The agent can't see your issue tracker, your database or the web page it just broke, so you copy and paste between windows.
- A big search fills the conversation with hundreds of lines of file contents you will never look at again, and the agent gets worse for the rest of the session.
Each has its own fix, and most agents now offer all four. Skills package a procedure so you write it once. Hooks run your own scripts at fixed moments, so rules are enforced, not requested. MCP servers give the agent new tools that reach other systems. Subagents do side jobs in a separate context and hand back a summary. This chapter uses Claude Code's versions as the main example, because they are the most complete and well documented (as of late 2026), and notes where Codex CLI and others do the same thing.
The idea
Four ways to plug into the loop
Every coding agent runs the same loop: the model reads its context, chooses a tool call (read a file, edit a file, run a command), the agent runs it, the result goes back into the context, and round it goes until the model says it is done (AI Agents explains the loop in general). Each extension plugs into a different point of that loop.
| Extension | What it is | When it acts | Use it when |
|---|---|---|---|
| Memory file | Always-on briefing (Project Context and Memory Files) | Every session, in full | The agent should always know it |
| Skill | A folder of instructions (and scripts) the agent loads on demand | When you invoke it, or the agent judges it relevant | You keep pasting the same procedure or reference material |
| Hook | Your script, run automatically on an event | Before or after a tool call, at session start, when the agent stops… | Something must happen every time, with no judgment |
| MCP server | A program that offers extra tools and data (Model Context Protocol) | When the agent calls one of its tools | The agent needs to reach a system it can't otherwise |
| Subagent | A helper agent with its own prompt, tools and context | When the main agent delegates to it | A side job would flood the main context, or needs a narrow role |
The most important line runs between hooks and everything else. Memory files and skills are text the model reads and usually follows. Hooks are code the agent program runs whatever the model thinks. Claude Code's documentation puts it plainly: an instruction like "never edit .env" is a request, not a guarantee, while a hook that blocks the edit is enforcement.
Key idea Use the weakest tool that does the job. Put knowledge in the memory file or a skill, rules that must hold every time in hooks (and permission rules), access to other systems in MCP servers, and messy side jobs in subagents. Add each one only when a real, repeated problem calls for it.
Skills: procedures written once
An agent skill is a folder containing a SKILL.md file: a short block of front matter (at least a name and a description) followed by Markdown instructions. The folder can also hold scripts, templates and reference documents that the instructions point to. Anthropic introduced skills in October 2025 and published the format as an open standard, Agent Skills, at agentskills.io. As of late 2026 it is read by Claude Code, Codex, and a growing list of other agents, so one skill can serve several tools.
What makes skills cheap is progressive disclosure: loading information in stages, only as far as the task needs. At the start of a session the agent sees just each skill's name and one-paragraph description, a few dozen tokens apiece. When a task matches a description (or you invoke the skill by name), the full SKILL.md is loaded. Files the skill mentions are read only if the instructions call for them. So you can keep a dozen skills installed, including long reference documents, for almost no context cost until one is used.
Here is a skill for tally, the expense tracker this part of the guide has been building. It captures the procedure for adding a new command, which until now lived in your head:
---
name: add-command
description: Add a new subcommand to the tally CLI, with tests and docs. Use when the user asks for a new tally command or option.
argument-hint: "[command name and what it does]"
---
Add this command to tally: $ARGUMENTS
1. Read docs/specs/ for a spec of this command. If there is none, write a
five-line spec with acceptance criteria and ask me to confirm it.
2. Put the logic in a pure function in tally.py that takes a Path, never in main().
3. Register the subcommand in main() next to the existing ones.
4. Write tests in test_tally.py using tmp_path. Cover one error case.
5. Add one usage line to README.md.
6. Run: python -m pytest -q && ruff check . && mypy tally.py
Fix anything that fails.
7. Ask the spec-reviewer subagent to check the diff, then report back.
Saved as .claude/skills/add-command/SKILL.md, it can be run as /add-command export --json writes all expenses as JSON, where $ARGUMENTS is replaced by everything after the name. Because its description says when to use it, the agent may also pick it up by itself when you just ask "add a top command". For skills with side effects, such as a deploy, add disable-model-invocation: true to the front matter so it runs only when you type its name. Skills in ~/.claude/skills/ are personal and apply to every project. Older Claude Code custom commands (.claude/commands/*.md) have been merged into skills and still work.
Codex reads the same format from .agents/skills/ in the repository (and ~/.agents/skills/ for personal ones), where you invoke a skill by typing $ and its name, or list them with /skills.
Hooks: rules that always run
A hook is a command that the agent program runs automatically when a particular event happens. The model doesn't decide whether to run it and can't skip it. Claude Code has many events (as of late 2026); four do most of the work:
PreToolUse: before a tool call runs. The hook sees the tool name and its arguments and can block the call. This is where guardrails go.PostToolUse: after a tool call succeeds. Good for formatting a file the agent just edited, or running the linter and sending any errors back to the agent.Stop: when the agent thinks it has finished. A hook can run the tests and, if they fail, tell the agent to keep going.SessionStart: at the start of a session. Its output can add context, such as the current branch's open issues.
Hooks are configured in the settings file (.claude/settings.json for a project, committed so the whole team gets them). This one formats every Python file the agent edits:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "f=$(jq -r '.tool_input.file_path'); case \"$f\" in *.py) ruff format \"$f\";; esac"
}
]
}
]
}
}
The matcher picks which tools the hook applies to. The agent passes the event to the hook as a JSON object on standard input, which is why the command uses jq to pull out tool_input.file_path. The hook reports back through its exit code, the number every program returns when it finishes:
- Exit 0: no objection. For
PreToolUse, the normal permission rules then decide; exit 0 doesn't approve anything. - Exit 2: block. Whatever the hook printed to standard error is shown to the agent as the reason, so it can adjust ("Blocked: use git stash instead") rather than simply fail.
- Anything else: an error in the hook. On most events the action goes ahead and the error is logged.
Hooks can also print a JSON object for finer control, for example "permissionDecision": "ask" to force a confirmation prompt. Besides shell commands, Claude Code supports hooks that call a URL, call an MCP tool, or ask a model to judge the situation. Codex CLI has a hook system built the same way, configured in .codex/hooks.json, with the same event names for the main events and the same exit-code-2 convention.
MCP servers: new tools
The Model Context Protocol is the open standard for plugging tools into AI applications, and coding agents are among its most common hosts. Connecting a server gives the agent new tools: a browser it can drive, an issue tracker, a database, up-to-date library documentation. In Claude Code:
# A local server, run as a subprocess (everything after -- is the server's command)
claude mcp add playwright -- npx @playwright/mcp@latest
# A remote server over HTTP, shared with the team through .mcp.json
claude mcp add --scope project --transport http notion https://mcp.notion.com/mcp
claude mcp list # each server and whether it is connected
Inside a session, /mcp shows server status and handles logins. With --scope project, the server is written to .mcp.json at the project root, which you commit. Claude Code asks each person to approve project servers before first use. Codex CLI has codex mcp add and keeps servers in ~/.codex/config.toml. Cursor, VS Code and the other IDE agents have their own MCP settings files.
Two practical rules. First, if the agent can already run a command-line tool, it may not need a server. An agent with shell access can use gh for GitHub or psql for Postgres, and command-line tools are often more flexible. MCP earns its place for things with no good CLI (a browser, a hosted SaaS product), for remote access with proper logins, and for narrow, safe access, as in the example below. Second, connect only what you use. Each server's tools take a little context. Claude Code loads only tool names until a tool is needed (its "tool search", on by default as of late 2026), but a long tool list still makes the agent's choices harder.
Subagents: a clean desk for side jobs
Multi-Agent Systems explains why sub-agents help: context isolation. The subagent reads forty files in its own context window and hands the main agent a twenty-line summary, so the main conversation stays focused. Claude Code ships built-in subagents (a fast, read-only Explore agent, a Plan agent, a general-purpose one), and saying "use a subagent to find every place amounts are parsed" is often enough.
A custom subagent is one you define yourself, with its own instructions, a restricted tool list and, optionally, a cheaper or stronger model. In Claude Code it is a Markdown file in .claude/agents/. Here is the spec reviewer promised in Planning and Specs: Telling an Agent What to Build:
---
name: spec-reviewer
description: Checks the current diff against the feature's spec in docs/specs/. Use after implementing a feature and before committing.
tools: Read, Grep, Glob, Bash
model: sonnet
---
You review changes; you never edit files.
1. Run git diff and find the matching spec in docs/specs/.
2. For each acceptance criterion, say MET, NOT MET or UNTESTED, citing the
test or line that shows it.
3. List any change the spec did not ask for (scope creep).
Reply in under 25 lines.
The front matter is the point. tools leaves out the editing tools (Edit, Write), so it can't change files through them whatever it decides. It keeps Bash to run git diff, which means a shell command could still write; the project's permission deny rules and hooks apply to subagents too, and the instructions say never to edit. The body becomes its system prompt. The main agent delegates to it when the description matches, or when you ask ("have the spec-reviewer check this"). A reviewer that didn't write the code, starting from a clean context, also catches mistakes the author's context has normalised, which matters for Reviewing and Debugging AI-Written Code.
Codex defines custom agents as TOML files in .codex/agents/ (with name, description and developer_instructions), and ships built-in worker and explorer agents.
Plugins: the packaging
Once you have a good set of skills, hooks, subagents and MCP servers, you will want them in your next project too. A plugin bundles any mix of them into one installable unit. In Claude Code you install plugins from a marketplace (a Git repository that lists plugins) with the /plugin command. Plugin skills get a prefix, such as /code-review:code-review, so plugins don't clash.
In code
A guardrail hook in Python
Hooks can be written in any language. This one is a PreToolUse hook for tally that turns three rules from the memory file into guarantees: no pushing, no destructive resets or deletes, and no touching the real data files or secrets. It reads the event from standard input, and exits with 2 and a reason to block.
#!/usr/bin/env python3
"""PreToolUse hook: block dangerous commands and protected files."""
import json, re, sys
BLOCKED_COMMANDS = [
(r"\bgit\s+push\b", "pushing is done by a human after review"),
(r"\bgit\s+reset\s+--hard\b", "use git stash or git restore instead"),
(r"\brm\s+-[a-z]*r[a-z]*f|\brm\s+-[a-z]*f[a-z]*r", "no recursive force deletes"),
]
PROTECTED_FILES = [".env", "expenses.csv", "budgets.json"]
event = json.load(sys.stdin) # Claude Code sends one JSON object
tool = event.get("tool_name", "")
args = event.get("tool_input", {})
text = args.get("command", "") if tool == "Bash" else args.get("file_path", "")
for pattern, why in BLOCKED_COMMANDS:
if tool == "Bash" and re.search(pattern, text):
print(f"Blocked: {why}.", file=sys.stderr)
sys.exit(2) # 2 = block; stderr goes back to the agent
for name in PROTECTED_FILES:
if re.search(rf"(^|[\s/'\"]){re.escape(name)}\b", text):
print(f"Blocked: {name} holds real user data or secrets.", file=sys.stderr)
sys.exit(2)
sys.exit(0) # 0 = no objection; normal permissions apply
Save it as .claude/hooks/guard.py and register it for every tool that can touch files or run commands:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash|Read|Edit|Write",
"hooks": [
{ "type": "command", "command": "python3 \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard.py" }
]
}
]
}
}
$CLAUDE_PROJECT_DIR is set by Claude Code to the project root, so the path works whichever folder the agent is in. Always test a hook by feeding it fake events before trusting it:
for e in '{"tool_name":"Bash","tool_input":{"command":"python -m pytest -q"}}' \
'{"tool_name":"Bash","tool_input":{"command":"git push origin main"}}' \
'{"tool_name":"Read","tool_input":{"file_path":"/home/you/tally/expenses.csv"}}' \
'{"tool_name":"Bash","tool_input":{"command":"rm -rf build"}}'; do
echo "$e" | python3 .claude/hooks/guard.py; echo "exit $?"
done
# exit 0
# Blocked: pushing is done by a human after review.
# exit 2
# Blocked: expenses.csv holds real user data or secrets.
# exit 2
# Blocked: no recursive force deletes.
# exit 2
Pattern matching on command text is a speed bump, not a wall: python -c "open('exp'+'enses.csv')" would get past it. Treat hooks as one layer, alongside permission deny rules and, for unattended work, an operating-system sandbox (From Prototype to Production).
A narrow MCP server
The memory file tells the agent never to read expenses.csv, and the hook now enforces it. But sometimes the agent legitimately needs to know something about the data, for example "which categories exist?" when designing a report. A small MCP server can answer that without exposing a single row. This uses the official mcp Python SDK (version 2.3; pip install mcp), as in Model Context Protocol:
# tally_stats.py: a read-only MCP server that exposes totals, never raw rows
import csv
from collections import defaultdict
from decimal import Decimal
from pathlib import Path
from mcp.server import MCPServer
DATA_FILE = Path(__file__).with_name("expenses.csv")
mcp = MCPServer("tally-stats")
@mcp.tool()
def category_totals(month: str) -> dict[str, str]:
"""Total spent per category in one month (YYYY-MM). Returns amounts as strings."""
totals: dict[str, Decimal] = defaultdict(Decimal)
with DATA_FILE.open(newline="") as f:
for row in csv.DictReader(f):
if row["date"].startswith(month):
totals[row["category"]] += Decimal(row["amount"])
return {cat: str(amount) for cat, amount in sorted(totals.items())}
if __name__ == "__main__":
mcp.run(transport="stdio")
Register it with claude mcp add tally-stats -- python3 /home/you/tally/tally_stats.py. Called by an MCP client on a four-row test file, it returns:
['category_totals'] # the tools the server offers
{'groceries': '45.00', 'lunch': '15.70'} # category_totals(month="2026-11")
The agent can now ask an aggregate question about real data, while the raw rows stay out of the model's context, and therefore out of the model provider's logs. That is the general pattern: an MCP tool can be a narrower door than a shell.
Worked example: tally's extension kit
After this chapter, tally's repository has a small .claude/ folder:
tally/
├── AGENTS.md, CLAUDE.md # memory: what the agent should always know
├── .mcp.json # tally-stats server, shared with the team
└── .claude/
├── settings.json # permissions + the two hooks
├── hooks/guard.py # PreToolUse guardrail
├── skills/add-command/SKILL.md # the "new command" procedure
└── agents/spec-reviewer.md # read-only reviewer
A session with all of it in place:
> /add-command top: show the 3 biggest expenses this month
● Read(docs/specs/) no spec for "top"
Spec draft: top prints the 3 largest expenses of the current month, newest
first on ties; --month YYYY-MM overrides; empty month prints "no expenses".
Confirm?
> Yes.
● Update(tally.py) +24
⎿ PostToolUse hook: ruff format tally.py (1 file reformatted)
● Update(test_tally.py) +31
● Bash(python -m pytest -q && ruff check . && mypy tally.py)
⎿ 14 passed; All checks passed!; Success: no issues found
● spec-reviewer(check the diff against the top spec)
⎿ 4/4 criteria MET. No unrequested changes.
● Bash(git push origin top-command)
⎿ PreToolUse hook: Blocked: pushing is done by a human after review.
The branch is ready. I couldn't push (blocked by a project hook); please
review and push it yourself.
Notice what you did not have to type: the procedure (the skill), "format the file" (a hook), "check it against the spec" (the subagent, called by the skill's last step), and "don't push" (a hook that held even though the agent tried). Each extension removed one recurring correction from your day.
Common mistakes
- Building the whole toolkit on day one. Add an extension when the same problem has happened at least twice: a skill when you paste the same procedure for the third time, a hook when something must happen every time, an MCP server when you keep copying data the agent can't see.
- Vague skill descriptions. The description is how the agent decides to load a skill. "Helpful utilities" never triggers; "Use when the user asks for a new tally command or option" does.
- Rules in prose that should be hooks, and the opposite: hooks that try to encode judgment ("is this a good test?") as regular expressions. Judgment belongs in a skill or a reviewer subagent.
- Slow or noisy hooks. A
PostToolUsehook that runs the full test suite after every edit makes the agent crawl. Format per file after edits; run the tests in aStophook or let the agent run them. AStophook that always says "keep going" traps the agent in a loop, so make it stop blocking once the check passes. - Too many MCP servers. Ten servers with dozens of tools blur the agent's choices. Disconnect what you aren't using.
- Subagents for tightly coupled work. A subagent sees only its brief, not your conversation. Delegate self-contained jobs (search, review, a test run), not "the next half of the feature".
Watch out Every extension is code or instructions that run with your permissions, and they arrive with repositories and plugins you didn't write. A cloned project's
.claude/settings.jsoncan define hooks that run shell commands automatically. Its skills can contain scripts, and its.mcp.jsoncan launch servers. Read a repository's.claude/(or.codex/) folder and.mcp.jsonbefore running an agent in it, install plugins and MCP servers only from sources you trust, and treat a third-party skill like any other code you are about to execute. This is Prompt Injection and LLM Security and supply-chain risk in a new form.
Where it leads
- Running Agents in Parallel and in the Background: subagents and skills scale up to several agents working at once, in the background and in CI.
- Tests as Guardrails: hooks and subagents are natural homes for automatic checks.
- Reviewing and Debugging AI-Written Code: reviewer subagents are a second pair of eyes, not a replacement for yours.
- Model Context Protocol: how the protocol works, and how to build a full server.
- Context Engineering and Memory: progressive disclosure and context isolation are general context-engineering techniques.
- From Prototype to Production: sandboxing and security when agents run with less supervision.
A bit of history
Claude Code had custom slash commands from its first release in February 2025, added hooks and custom subagents in mid-2025, then skills and plugins in October 2025. In December 2025 Anthropic published Agent Skills as an open standard, and MCP moved to the Linux Foundation's Agentic AI Foundation. Through 2026 other agents converged on the same four ideas, often with near-identical formats: Codex CLI reads Agent Skills and uses hooks with the same event names. The details change often, but the division of labour (knowledge, rules, tools, isolation) has proved stable.
Try it
- Look back at your last week of agent sessions and find one instruction you typed at least three times. Turn it into a skill with a precise description, then start a fresh session and check that the agent picks it up without being told.
- Install the guard hook (or write your own for your project's dangerous commands). Test it with fake events as above, then ask the agent to "push this branch" and watch what happens.
- Write a read-only reviewer subagent with only
Read,GrepandGlob. Ask it to review a change you know has a bug. Did it find it? What did it miss?Hint for 2: if the hook seems not to run, check that
/hookslists it, that the script is executable or called throughpython3, and that it prints its reason to standard error, not standard output.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Extend Claude Code
One page comparing CLAUDE.md, skills, subagents, hooks, MCP and plugins: what each is for, when it loads, what it costs in context, and the order most teams add them.
Claude Code: get started with hooks
Shell commands that run automatically at points in Claude Code's lifecycle: format after every edit, block dangerous commands, notify you, with copy-paste examples and the exit-code rules.
Claude Code: skills
How to package instructions and scripts as a SKILL.md that Claude loads when relevant or you invoke as a slash command, with front-matter options and arguments.
Agent Skills
The open format for agent skills: a folder with a SKILL.md file, loaded by progressive disclosure. Specification, quickstart and the list of agents that read it.
Claude Code: subagents
Define specialised helpers in .claude/agents with their own prompt, tools and model, so focused jobs such as review or test running happen in a separate context window.
Claude Code: connect to tools via MCP
Adding MCP servers with claude mcp add, the local, project and user scopes, sharing servers through .mcp.json, and authentication for remote servers.
Equipping agents for the real world with Agent Skills
The engineering post that introduced skills: why they are folders, the three levels of progressive disclosure, bundled scripts, and security advice for third-party skills.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/agentic/extending-coding-agents.md