CLAUDE CODE
Installing it, then MCP, subagents, hooks, plugins and automation.
- PARTP4
- SECTIONS7
- PLATFORMWINDOWS 11
- REVISIONB · 7 OCT 2026
SECTION 09
Installing Claude Code on Windows
Installing Claude Code takes one PowerShell command and a browser sign-in. It needs a Pro, Max, Team or Enterprise plan, or a Console (API) account; the free plan does not include it.
Requirements, per Anthropic's setup page
- Windows 10 version 1809 or later, 4 GB RAM or more, x64 or ARM64 processor, internet connection.
- PowerShell or CMD. No administrator rights needed.
- Git for Windows is optional. With it, Claude Code runs shell commands through Git Bash; without it, through PowerShell. Installing it (section 4) is recommended.
EX-12 Install and verify
- Open PowerShell (not the "(x86)" entry) and run:
irm https://claude.ai/install.ps1 | iexirm downloads the installer script and iex runs it. Expected: scrolling output ending in "Claude Code successfully installed!"
- Close PowerShell, open a new window, and check:
claude --version
claude doctorExpected: a version number followed by (Claude Code), then a diagnostics report covering install health, settings-file errors and warnings with fixes.
Already installed through npm? Tested: the PC this guide was checked on had Claude Code 2.1.268 from npm install -g @anthropic-ai/claude-code (it lives in C:\nvm4w\nodejs), while winget listed 2.1.292 as current. Anthropic's install page lists npm under advanced options and calls the native install recommended. To switch, run the installer from Exercise 12, then npm uninstall -g @anthropic-ai/claude-code, open a new window, and check that where.exe claude lists only ...\.local\bin\claude.exe; if it lists nothing, run the PATH fix below. The CLI reference says claude install also installs the native binary (not tested here). The troubleshooting page says to keep only one install. Some behaviour in this guide, such as auto mode as the starting mode on every plan, needs v2.1.283 or later.
Alternative install through winget: winget install Anthropic.ClaudeCode. The native installer updates itself in the background; the winget version does not, so you would run winget upgrade Anthropic.ClaudeCode yourself.
EX-13 First session in the practice folder
cd ~\claude-practice
claude --permission-mode manual- The first launch opens a browser to sign in with your Claude account. Credentials are stored, so later launches skip this. Type
/logininside a session to switch accounts. Anthropic's security page adds that the first run in a folder asks you to confirm you trust it; say yes for your practice folder. Start Claude Code from a project folder rather than your home folder, since trust given to the home folder only lasts for that session. - Manual mode makes Claude ask before every edit and command, which is the best way to see what it does while learning. Claude Code v2.1.283 and later otherwise start in auto mode, where a second model reviews actions instead of you (section 10).
- Type:
what files are in this folder and what does each contain?Expected: it listshello.txt,hello.py,good.jsonand the rest, with a line on each. Reading needs no approval. - Type:
create notes.md with a one-line description of each file here. Expected: a permission prompt showing the file it wants to write. Choose Yes, then open the file to check it. - Type
/exit, or press Ctrl + D twice, to leave. Esc interrupts Claude mid-task.
If something goes wrong
| Message | Cause | Fix from Anthropic's terminal guide |
|---|---|---|
'irm' is not recognized |
You are in CMD | Open PowerShell, or use the CMD installer on the setup page |
The token '&&' is not a valid statement separator |
You pasted the CMD command into PowerShell | Use the irm command above |
'claude' is not recognized |
Install folder not on PATH | Run the two PATH lines below, then open a new window |
Could not create SSL/TLS secure channel |
Older Windows 10 TLS settings | Run [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 then retry |
Claude Code does not support 32-bit Windows |
You opened PowerShell (x86) | Open the entry without "(x86)" |
The PATH fix:
$currentPath = [Environment]::GetEnvironmentVariable('PATH', 'User')
[Environment]::SetEnvironmentVariable('PATH', "$currentPath;$env:USERPROFILE\.local\bin", 'User')Updating and uninstalling
claude updateapplies an update immediately; otherwise the native install updates in the background.- To remove a native install:
Remove-Item -Path "$env:USERPROFILE\.local\bin\claude.exe" -Force
Remove-Item -Path "$env:USERPROFILE\.local\share\claude" -Recurse -ForceSettings and history live in %USERPROFILE%\.claude and %USERPROFILE%\.claude.json. Deleting those erases all settings, MCP configuration and session history.
The two graphical alternatives
- Claude desktop app, Code tab: download from claude.com/download, open the Code tab, pick a project folder. Same engine with a visual diff viewer and no terminal. Settings are shared with the CLI.
- VS Code extension: needs VS Code 1.94 or later. Press Ctrl + Shift + X, search "Claude Code", install (publisher Anthropic, ID
anthropic.claude-code), then click the spark icon at the top right of an open file and sign in. The extension bundles its own private copy of Claude Code, so it does not makeclaudework in a terminal; for that you still need the install above. Conversations are shared:claude --resumein a terminal opens a picker that includes extension sessions.
For a first-time terminal user, the desktop app's Code tab is the gentlest start. The CLI is worth learning because scripting, claude -p and some commands exist only there.
SECTION 10
Claude Code essentials
Five things make Claude Code manageable: a handful of commands, a CLAUDE.md file of standing instructions, permission modes, plan mode, and settings files with permission rules.
Starting and steering a session
| From the terminal | What it does |
|---|---|
claude |
Start a session in the current folder |
claude "task" |
Start with a first prompt |
claude -c |
Continue the most recent conversation in this folder |
claude -r |
Pick an earlier conversation to resume |
claude -p "query" |
Answer once and exit, with no session (section 15) |
claude --permission-mode <mode> |
Start in a specific permission mode |
Inside a session: Esc interrupts Claude; Shift + Tab cycles permission modes; typing / lists commands and skills; typing @ followed by part of a file name attaches that file; Up arrow recalls earlier prompts.
The commands worth learning first
Descriptions condensed from Anthropic's commands reference.
| Command | Purpose |
|---|---|
/help |
List commands |
/init |
Generate a starter CLAUDE.md for the current project |
/memory |
Edit CLAUDE.md files; turn auto memory on or off |
/context |
Show what is filling the context window, including which memory files loaded |
/compact [focus] |
Summarise the conversation so far to free space |
/clear |
Start a fresh conversation, keeping project memory |
/resume |
Return to an earlier conversation |
/rewind |
Roll code and conversation back to a checkpoint |
/model |
Switch model |
/plan [task] |
Enter plan mode, optionally with a task |
/permissions |
View and edit allow, ask and deny rules |
/mcp |
Manage MCP server connections |
/hooks |
View configured hooks |
/plugin |
Manage plugins |
/skills |
List skills and change their visibility |
/usage |
Session cost, plan usage limits and what is driving them |
/status |
Version, model, account, and which settings files loaded |
/doctor |
Setup checkup that finds and offers to fix problems |
/btw <question> |
Side question that does not get added to the conversation |
/exit |
Leave |
CLAUDE.md: standing instructions
CLAUDE.md is a plain Markdown file Claude reads at the start of every session in that folder. It is the Claude Code equivalent of project instructions in claude.ai.
| Scope | Location | Applies to |
|---|---|---|
| User | ~/.claude/CLAUDE.md |
All your projects |
| Project | ./CLAUDE.md or ./.claude/CLAUDE.md |
Everyone working in this folder |
| Local | ./CLAUDE.local.md |
Only you, in this folder (keep it out of git) |
Guidance from Anthropic's memory page:
- Keep each file under about 200 lines; longer files cost context and get followed less reliably.
- Write instructions concrete enough to check: "Run
uv run tests.pybefore finishing" rather than "test your changes". - Add a line when Claude makes the same mistake twice.
- Pull in other files with
@path, such asSee @README.md. - Run
/contextand look under Memory files to confirm the file loaded. - Claude also keeps its own notes (auto memory) in
~/.claude/projects/<project>/memory/;/memoryshows and toggles them.
An example for a data-analysis folder:
# Sales data analysis
## Setup
- Python is managed with uv. Run scripts with `uv run <script>.py`.
- Raw data lives in `data/raw/` and is read-only.
- Outputs go in `outputs/`, one subfolder per analysis date.
## Conventions
- pandas for tables, matplotlib for figures. Save figures as PNG and PDF.
- Every script prints the input files and row counts it used.
## Checks
- Run a changed script on `data/sample/` before running it on the full data.CLAUDE.md is a request. A deny rule (below) is stronger: it stops Claude's own file tools, and shell commands Claude Code recognises such as > redirection and tee, from changing data/raw/. Per Anthropic's permissions page it does not cover a script that opens files itself, such as a Python file Claude writes and runs. The sandbox that would block that runs on macOS, Linux and WSL2; on native Windows, Claude Code runs commands unsandboxed. For raw research data, also mark the files read-only in Windows and keep a copy outside the project folder:
Get-ChildItem .\data\raw -Recurse -File | ForEach-Object { $_.IsReadOnly = $true }Permission modes
| Mode | Runs without asking | Use it for |
|---|---|---|
default (shown as Manual) |
Reads only | Learning, sensitive work |
acceptEdits |
Reads, file edits, common file commands (mkdir, mv, cp) inside the folder | Iterating when you will review changes afterwards |
plan |
Reads; edits blocked until you approve a plan | Anything large or unfamiliar |
auto |
Everything, with a second model reviewing each risky action | Long tasks you trust the direction of |
dontAsk |
Only pre-approved tools; everything else denied | Scripts and automation |
bypassPermissions |
Everything, no checks | Disposable containers only |
Facts from Anthropic's permission-modes page:
- Claude Code v2.1.283 and later start interactive sessions in auto mode by default.
- Shift + Tab cycles auto, Manual, acceptEdits and plan. The status bar shows the active mode.
- Auto mode blocks some actions by default, including downloading and running code (
curl | bash), force-pushing, and mass deletion. The docs warn it reduces prompts but does not guarantee safety. - Deny rules block in every mode, including bypassPermissions.
While learning, start sessions with claude --permission-mode manual, so every edit and command comes to you first.
Plan mode
- Press Shift + Tab until the status bar shows plan mode, or type
/plan <task>. - Claude reads files, explores, and writes a plan without changing anything.
- Choose "Yes, and use auto mode", "Yes, manually approve edits", or "No, keep planning" and say what to change. Ctrl + G opens the plan in your editor to edit it directly.
Planning first is a useful habit for anything larger than a one-file change: mistakes are cheap to fix in a plan and expensive in twenty edited files.
Settings files and permission rules
| Scope | File | Affects |
|---|---|---|
| User | ~/.claude/settings.json |
You, every project on this computer |
| Shared project | .claude/settings.json |
Everyone in the project |
| Project local | .claude/settings.local.json |
You, this project only |
| Managed | Set by an organisation | Everyone it is deployed to |
When the same key is set in several places, the higher one wins: managed, then command-line flags, then project local, then shared project, then user. List keys such as permission rules merge across files instead of replacing each other. Claude Code reloads most settings edits without a restart, and /status shows which files loaded.
An example ~/.claude/settings.json; the $schema line gives autocomplete and error checking in VS Code:
{
"$schema": "https://json.schemastore.org/claude-code-settings.json",
"permissions": {
"allow": [
"Bash(git status)",
"Bash(git diff *)"
],
"deny": [
"Read(./.env)",
"Read(./.env.*)"
]
}
}Each rule names a tool and what it may touch: Bash(...) for shell commands, Read(...) and Edit(...) for file paths. Choosing "Yes, and don't ask again" on a command prompt saves an allow rule to .claude/settings.local.json; for file edits, the approval lasts until the session ends.
BEST PRACTICE Best practices for CLAUDE.md and settings
From Anthropic's memory, best-practices and permissions pages:
- For every line, ask "would removing this cause Claude to make mistakes?" Keep commands Claude cannot guess, non-default style rules and known gotchas; leave out anything Claude can read from the files themselves.
@pathimports organise a file without saving context: imported files load at launch too. For instructions that only matter for some files, use.claude/rules/<topic>.mdwith apaths:list of glob patterns in its frontmatter, which loads when Claude reads, writes or edits a matching file.- Block-level HTML comments (
<!-- ... -->) in CLAUDE.md are stripped before it loads into context, so notes to yourself cost nothing; comments inside code blocks are kept. - Auto memory loads the first 200 lines or 25 KB of its
MEMORY.mdeach session; check it now and then with/memory. - Permission rules are checked deny first, then ask, then allow. In rules, Windows paths are written POSIX-style:
C:\Users\<you>becomes/c/Users/<you>, so a rule for every.envon drive C isRead(//c/**/.env). - To make Manual mode your default instead of auto, set
"permissions": { "defaultMode": "default" }in~/.claude/settings.json.
EX-14 A guarded practice project
mkdir ~\claude-practice\analysis
cd ~\claude-practice\analysis
mkdir data\raw
Set-Content data\raw\scores.csv "id,score`n1,12`n2,15`n3,9"
mkdir .claude
code .claude\settings.jsonPaste this into settings.json and save:
{
"permissions": {
"deny": ["Edit(./data/raw/**)"]
}
}Then:
claude --permission-mode acceptEdits- Ask:
add a row with id 4 and score 20 to data/raw/scores.csv. Expected: the edit is refused because of the deny rule, even though acceptEdits would normally allow file edits. - Ask:
write mean.py that prints the mean score from data/raw/scores.csv, then run it with uv. Expected: Claude createsmean.pywithout asking (acceptEdits), asks before running the command, and prints12.0. - Run
/init. Expected: a starterCLAUDE.mddescribing the folder. Open it and add the read-only rule from the example above. - Run
/contextand confirm CLAUDE.md appears under Memory files.
SECTION 11
MCP in depth
MCP (Model Context Protocol) is an open standard that lets any AI client use any tool server. In Claude Code you add a server with one claude mcp add command, and a working server of your own takes about 20 lines of Python.
The shape of it
- Client: the AI app. Claude Code, the Claude desktop app and claude.ai are all MCP clients.
- Server: a separate program that offers capabilities to clients. Per modelcontextprotocol.io, a server can offer three kinds:
- Tools: functions the model can call, such as "search issues" or "create design".
- Resources: file-like data you can pull in; in Claude Code you reference them with
@server:protocol://path. - Prompts: ready-made templates, which show up in Claude Code as
/commands.
- Transport: how client and server talk.
- stdio: the server runs on your computer as a child process; messages travel through its standard input and output.
- HTTP: the server runs somewhere on the internet; Anthropic's docs call this the recommended option for remote servers.
- SSE: older remote transport, marked deprecated.
- Messages: JSON-RPC objects like the one in section 5.
Adding servers to Claude Code
Remote (HTTP) server, then sign in from inside a session:
claude mcp add --transport http notion https://mcp.notion.com/mcpLocal (stdio) server. Everything after -- is the command that starts the server; everything before it is for Claude Code:
claude mcp add <name> -- <command> [args...]
claude mcp add --env API_KEY=<key> --transport stdio <name> -- npx -y <package>Anthropic's MCP page notes two traps: without --, Claude Code tries to read the server's own flags as its options; and --env must not sit directly before the server name, or the name is read as another variable.
Scope (--scope) |
Stored in | Loads in | Shared |
|---|---|---|---|
local (default) |
~/.claude.json, under this project |
This project only | No |
project |
.mcp.json in the project folder |
This project | Yes, if committed; Claude Code asks you to approve these |
user |
~/.claude.json |
All your projects | No |
Managing servers:
claude mcp list
claude mcp get <name>
claude mcp remove <name>
claude mcp login <name>Inside a session, /mcp shows each server's status, tool count and sign-in state.
Facts worth knowing, from the same page:
- If you sign in to Claude Code with your claude.ai account, your claude.ai connectors (your Google Drive and Canva) appear in Claude Code automatically, marked as coming from claude.ai. They do not appear when an API key is active instead.
- Tool search is on by default: only tool names load at the start, and full definitions load when Claude needs them, so extra servers cost little context.
- Claude Code warns when a tool's output passes 10,000 tokens and caps it at 25,000 by default (
MAX_MCP_OUTPUT_TOKENSchanges the cap).
EX-15 Add a ready-made server
The MCP project's reference filesystem server gives Claude file tools scoped to one folder. Claude Code already has file tools, so this is purely practice.
cd ~\claude-practice
claude mcp add files -- npx -y @modelcontextprotocol/server-filesystem "$HOME\claude-practice"
claude mcp listExpected: an Added ... line, then files in the list with a status such as Connected. Start claude, ask "using the files server, list what is in claude-practice", and the reply shows a tool call from that server. Remove it afterwards with claude mcp remove files.
If it shows "Failed to connect", run claude mcp get files and read its Issue line, then run the npx command on its own to see its error. Anthropic's MCP quickstart says claude mcp add works the same in PowerShell and Command Prompt. A slow first npx download can time out: start Claude Code with $env:MCP_TIMEOUT = "60000"; claude to allow 60 seconds. Older community guides suggest wrapping npx as cmd /c npx ...; the current docs do not, so keep that as a last resort.
EX-16 Inspect a server without any AI
The MCP Inspector is the reference testing tool. It needs Node 22.19.0 or newer, per its docs.
npx -y @modelcontextprotocol/inspector npx -y @modelcontextprotocol/server-filesystem "$HOME\claude-practice"Expected: a URL with a one-time token is printed. Open it in a browser, connect, open the Tools tab, pick a tool, fill in its arguments and run it. You see the raw request and response, which is what Claude sees when it calls the tool. --cli instead of the web UI gives a scriptable version.
EX-17 Build your own server in Python
This follows the official Python quickstart, which uses MCP Python SDK 2.x and Python 3.10 or newer.
cd ~\claude-practice
uv init text-tools
cd text-tools
uv add "mcp[cli]"
code server.pyPaste into server.py:
import logging
from mcp.server import MCPServer
logger = logging.getLogger(__name__)
mcp = MCPServer("text-tools")
@mcp.tool()
def word_count(text: str) -> int:
"""Count the words in a piece of text."""
return len(text.split())
@mcp.tool()
def reading_time(text: str, words_per_minute: int = 200) -> str:
"""Estimate how long a text takes to read at a given speed."""
minutes = len(text.split()) / words_per_minute
logger.info("reading_time called")
return f"{minutes:.1f} minutes at {words_per_minute} words per minute"
if __name__ == "__main__":
mcp.run(transport="stdio")How it works: the SDK reads each function's type hints and docstring and turns them into a tool definition, so the docstring is what Claude reads when deciding whether to call it. The quickstart's one hard rule for stdio servers: never print(), because anything written to standard output corrupts the JSON-RPC messages. Use logging, which writes to standard error.
Test it in the Inspector first:
npx -y @modelcontextprotocol/inspector uv --directory "$PWD" run server.pyExpected: the Tools tab lists word_count and reading_time. Run word_count with the quick brown fox and get 4.
Then give it to Claude Code for all your projects:
claude mcp add --scope user text-tools -- uv --directory "$HOME\claude-practice\text-tools" run server.pyStart claude, run /mcp to confirm text-tools is connected with 2 tools, and ask: "use text-tools to estimate reading time for this paragraph: <paste a paragraph>". Expected: a call to the reading_time tool and its answer.
To use the same server in the Claude desktop app's chat, open code $env:AppData\Claude\claude_desktop_config.json and add it under mcpServers in the shape the quickstart shows, with an absolute path and doubled backslashes, then fully quit the app from the system tray and reopen it:
{
"mcpServers": {
"text-tools": {
"command": "uv",
"args": ["--directory", "C:\\Users\\<you>\\claude-practice\\text-tools", "run", "server.py"]
}
}
}If the file already has content, add mcpServers alongside the existing keys. If the app then lists the server as failed, replace uv with the full path that (Get-Command uv).Source prints in PowerShell, with the backslashes doubled. (The quickstart says where uv, which in PowerShell runs a different command.)
BEST PRACTICE Best practices for MCP servers you build
From the MCP specification, its security page and Anthropic's connector review criteria:
- Tool names: 1 to 128 characters of letters, digits,
_,-and.; Anthropic's directory caps them at 64. - Descriptions say exactly what the tool does and when to call it. Keep reading tools separate from tools that change things, and mark them with
readOnlyHintordestructiveHintannotations. - When a call fails, return an error result (
isError: true) whose message tells the model what to fix, such as "date must be YYYY-MM-DD", rather than a bare "Internal error". - Validate every input, and request the narrowest scopes and tokens that work; servers must not accept tokens that were not issued for them.
- Prefer stdio for servers that only run on your computer, and log to standard error, never standard output.
CAUTION Safety
- A stdio server runs on your computer with your user permissions. Install only servers whose source you trust.
- Anthropic's docs warn that servers fetching outside content expose you to prompt injection: hidden instructions in what a tool returns.
- Prefer read-only database users and narrowly scoped tokens when a server asks for credentials.
SECTION 12
Subagents
A subagent is a separate Claude with its own clean context window. It does a side task and hands back only a summary, so the main conversation stays uncluttered. Claude Code ships with several; you can define your own as Markdown files.
When a subagent is worth it
Anthropic's subagents page gives the test:
- Use one when a side task would flood the conversation with search results, logs or file contents you will not look at again.
- Use one to restrict tools: a reviewer that cannot edit, a researcher that cannot run commands.
- Use one to run independent investigations in parallel.
- Stay in the main conversation for quick changes, back-and-forth refinement, and work where each step depends on the last.
Subagents send their own requests, which count towards the same usage limits as your main conversation.
Built-in subagents
| Name | What it does | Tools |
|---|---|---|
| Explore | Fast searching and reading of a codebase; skips CLAUDE.md to stay cheap | Read-only |
| Plan | Research during plan mode | Read-only |
| general-purpose | Multi-step tasks needing both reading and changing things | All tools available to subagents |
| claude | Catch-all when nothing more specific fits | All tools available to subagents |
| claude-code-guide | Answers questions about Claude Code itself (runs on Haiku) | Not listed in the docs |
| statusline-setup | Used by /statusline |
Not listed in the docs |
Claude picks these on its own. You will see them in the transcript as a row such as Explore(Find where scores are loaded).
Defining your own
A custom subagent is a Markdown file: YAML frontmatter, then the subagent's own system prompt.
| Location | Scope |
|---|---|
.claude/agents/<name>.md |
This project; commit it to share |
~/.claude/agents/<name>.md |
All your projects |
A plugin's agents/ folder |
Wherever the plugin is enabled |
Only name and description are required. The fields you will use most:
| Field | Purpose |
|---|---|
name |
Identifier; lowercase and hyphens; no colons |
description |
When Claude should delegate to it. Claude decides by matching this text |
tools |
Allowlist, such as Read, Grep, Glob. Omit to inherit everything |
disallowedTools |
Denylist, such as Write, Edit |
model |
sonnet, opus, haiku, a full model ID, or inherit |
permissionMode |
Permission mode for this subagent |
skills |
Skills preloaded in full at startup |
memory |
user, project or local: a folder of notes that persists across sessions |
isolation |
worktree gives it a separate copy of the repository |
maxTurns |
Cap on how many steps it takes |
A subagent receives only its own prompt plus basic environment details, not the main Claude Code system prompt, and not your conversation history. Everything it needs has to be in its file or in the task Claude hands it.
Worked example: a citation checker
For paper drafts: a read-only subagent that checks each in-text citation against the source files in a sources/ folder.
---
name: citation-checker
description: Checks that each citation in a paper draft is supported by the cited source file. Use after editing a draft or when asked to verify references.
tools: Read, Grep, Glob
model: sonnet
---
You check citations in academic drafts against the PDFs and notes in the sources/ folder.
For each in-text citation in the draft:
1. Find the matching source file in sources/. If none exists, report "No source file".
2. Find the passage that supports the claim. Quote at most one sentence.
3. Give a verdict: Supported, Partly supported, or Not found.
Return one table: claim (shortened), citation, verdict, location in the source.
Never edit files.Because tools lists only Read, Grep and Glob, it cannot change your draft even if asked.
EX-18 Create and use it
- In PowerShell, run
mkdir $HOME\.claude\agents -Force, thencode "$HOME\.claude\agents\citation-checker.md", paste the example and save. Alternatively, ask Claude in a session to "create a personal citation-checker subagent in ~/.claude/agents/" with the description above; the docs show Claude writing the file for you. - Make a test folder with a short
draft.mdcontaining two or three citations and asources/folder holding the matching files. - Start
claudein that folder and type:Use the citation-checker subagent on draft.md. - Expected: a transcript row reading
citation-checker(...), then a table of verdicts in the main conversation, without the source text cluttering it.
If Claude does not see the new subagent and the agents folder did not exist when the session started, restart Claude Code; the docs note a running session does not notice a newly created agents folder.
Three ways to call one
- Natural language: "Use the citation-checker subagent to...". Claude usually delegates.
- @-mention: type
@and pick it from the list, such as@"citation-checker (agent)" check draft.md. This guarantees that subagent runs. - Whole session:
claude --agent citation-checkerruns the main conversation as that subagent, with its tools and model.
Running, watching and stopping
- In interactive sessions, subagents run in the background by default. Permission prompts still reach you, labelled with the subagent's name.
/taskslists background work, including subagents; select one to read its transcript or stop it.- Ctrl + B sends a running task to the background.
/subtask <task>starts a fork: a subagent that inherits the whole conversation so far, useful when a fresh subagent would need too much explaining./agentsin current versions only prints a reminder to ask Claude or edit.claude/agents/directly.
BEST PRACTICE Best practices for subagents
- List the tools explicitly. Without a
toolsline a subagent inherits every tool, and leaving outAgentstops it starting subagents of its own. - Make each subagent do one job, and write its description so the right requests match it; the docs suggest adding "use proactively" when you want Claude to delegate without being asked.
- A subagent starts without your conversation, so repeat any rule that matters in the task you give it.
- Commit project subagents in
.claude/agents/to git, so they travel with the project.
Keeping them cheap
- Short descriptions. Every subagent's description loads into context; Claude Code warns when their combined size passes 15,000 tokens.
- A cheaper model where judgement matters less:
model: haikufor searching and listing. - Ask for summaries back instead of raw output: "report only failing tests with their error messages".
SECTION 13
Hooks
A hook is a command Claude Code runs automatically at a fixed moment: before a tool runs, after a file edit, when Claude needs you, when it finishes. Unlike CLAUDE.md or a skill, a hook does not depend on Claude remembering; it fires every time its event happens. Hooks exist only in Claude Code, not in claude.ai chat.
Three layers
Every hook is written as event, then matcher, then handler, inside a hooks key in a settings file:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "<what to run>" }
]
}
]
}
}- Event (
PostToolUse): the moment in the loop. - Matcher (
Edit|Write): narrows which occurrences count; for tool events it matches the tool name. Omit it, or use*, to match everything. - Handler: what runs. Usually
"type": "command"; other types send an HTTP request, call an MCP tool, or ask a model to decide ("prompt","agent").
The events worth knowing first
| Event | Fires | Can block? |
|---|---|---|
SessionStart |
A session starts or resumes | No; can add context |
UserPromptSubmit |
You send a message, before Claude reads it | Yes |
PreToolUse |
Before any tool call | Yes |
PermissionRequest |
When Claude Code is about to ask you for permission | Can answer for you |
PostToolUse |
After a tool call succeeds | No; can feed text back to Claude |
Notification |
Claude is waiting for you | No |
Stop |
Claude finishes responding | Yes; can make it keep working |
PreCompact |
Before the conversation is compacted | Yes |
SessionEnd |
The session ends | No |
The full list in the hooks reference has more than 30 events.
How a hook talks back
- Input: Claude Code sends the hook a JSON object on standard input, with fields such as
tool_name,tool_inputandcwd(the shape practised in Exercise 6). - Exit code 0: no objection; normal permission rules still apply.
- Exit code 2: block. For
PreToolUse, the tool call is cancelled and your standard-error text is shown to Claude as the reason. - Any other exit code: a non-blocking error. The action goes ahead and the transcript shows a hook error notice.
- JSON on standard output: finer control, such as
"permissionDecision": "deny"with a reason.
The reference's warning in plain terms: exit code 1, the usual "failure" code, does not block. A policy hook must exit 2 or print a deny decision.
Hooks on Windows
- A hook written as a plain command string runs in Git Bash when Git for Windows is installed, otherwise in PowerShell. Add
"shell": "powershell"to force PowerShell. - The reference's Windows examples run scripts in exec form:
"command": "powershell.exe"with anargslist. No shell quoting is involved, so paths with spaces are safe. ${CLAUDE_PROJECT_DIR}expands to the project root, so scripts can be referenced from any working directory.
EX-19 Get notified when Claude needs you
This is the Windows example from Anthropic's hooks guide. Open your user settings:
code $env:USERPROFILE\.claude\settings.jsonAdd a hooks key. If the file already has other keys, add it alongside them with a comma, keeping the whole file one JSON object:
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "powershell.exe -Command \"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Claude Code needs your attention', 'Claude Code')\""
}
]
}
]
}
}Test it: run /hooks in a session and check the hook is listed under Notification. Start claude --permission-mode manual, ask for something that needs permission, and switch to another window. Expected: a dialog titled "Claude Code" after a few seconds; the guide notes it can open behind your terminal.
EX-20 Block recursive deletes
This is the reference's Windows example, added to the analysis project from Exercise 14. Create the script file:
cd ~\claude-practice\analysis
mkdir .claude\hooks -Force
code .claude\hooks\block-rm.ps1Paste this and save:
# .claude/hooks/block-rm.ps1
$callInput = [Console]::In.ReadToEnd() | ConvertFrom-Json
$command = $callInput.tool_input.command
if ($command -match 'rm -rf|Remove-Item.*-Recurse') {
@{
hookSpecificOutput = @{
hookEventName = "PreToolUse"
permissionDecision = "deny"
permissionDecisionReason = "Destructive command blocked by hook"
}
} | ConvertTo-Json
} else {
exit 0
}Then open .claude\settings.json (code .claude\settings.json) and replace its contents with this merged version, which keeps Exercise 14's deny rule and adds the hook. A second { } object pasted below the first would make the file invalid JSON.
{
"permissions": {
"deny": ["Edit(./data/raw/**)"]
},
"hooks": {
"PreToolUse": [
{
"matcher": "Bash|PowerShell",
"hooks": [
{
"type": "command",
"if": "Bash(rm *)",
"command": "powershell.exe",
"args": ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.ps1"]
},
{
"type": "command",
"if": "PowerShell(Remove-Item *)",
"command": "powershell.exe",
"args": ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.ps1"]
}
]
}
]
}
}The if field narrows each handler further than the matcher: the script only starts for rm or Remove-Item commands, so ordinary commands pay no cost.
Test the script on its own before trusting it:
'{"tool_name":"PowerShell","tool_input":{"command":"Remove-Item data -Recurse"}}' | powershell -NoProfile -ExecutionPolicy Bypass -File .claude\hooks\block-rm.ps1Expected: a JSON object containing "permissionDecision": "deny". Then run mkdir junk, start claude in this folder, and ask: run rm -rf junk. Expected: the command is blocked and Claude reports "Destructive command blocked by hook". The script's pattern catches rm -rf and Remove-Item ... -Recurse; a plain rm -r gets past it, so test any hook against the exact commands you want stopped.
Project hooks only run after you accept the workspace trust prompt for that folder, which Claude Code shows the first time you start a session there.
EX-21 Log every commandneeds Git for Windows
Open your user settings again (code $HOME\.claude\settings.json). Add a PostToolUse entry beside Exercise 19's Notification entry, so one hooks object holds both. The whole file then looks like this, plus any other keys you already had:
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "powershell.exe -Command \"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Claude Code needs your attention', 'Claude Code')\""
}
]
}
],
"PostToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "jq -r '.tool_input.command' >> ~/.claude/command-log.txt" }
]
}
]
}
}Expected: every shell command Claude runs is appended to command-log.txt in your .claude folder; read it with Get-Content $HOME\.claude\command-log.txt. Useful for reviewing what an agent did after a long session.
When a hook does not work
/hooksshows nothing: check the JSON is valid (jq . <file>), with no trailing commas or comments, and that the file is in the right place.- Hook error notices: run the script by hand with sample JSON piped in, as above, and check
$LASTEXITCODE. - Full detail: start with
claude --debug-file $env:TEMP\claude.log, or run/debugmid-session, and read the log. - Matchers are case-sensitive:
bashdoes not matchBash. "disableAllHooks": truein settings turns every non-managed hook off without deleting them.
BEST PRACTICE Best practices for hooks
- Use a hook for anything that must happen every time; Anthropic's best-practices page calls CLAUDE.md advisory and hooks deterministic.
- A
PreToolUsedeny blocks the tool even in bypassPermissions mode, and a hook's "allow" never loosens a deny rule. - Keep matchers narrow; a
.*matcher onPermissionRequestthat approves would approve everything. - On Windows, set
"shell": "powershell"for PowerShell scripts, and test each one by piping sample JSON into it before relying on it.
CAUTION Safety
Hooks run arbitrary commands with your permissions, every time. Read the hooks in any repository you clone before running Claude Code there (the permissions page notes that a repository's hooks run even under claude -p or when you only trusted a parent folder), and the hooks inside any plugin before installing it. For everyday chat in claude.ai you will not need hooks; they become useful once Claude Code is editing real code or data.
SECTION 14
Plugins and marketplaces
A plugin is a package that installs several add-ons at once: skills, commands, subagents, hooks and MCP servers. A marketplace is a catalogue you install plugins from. This section covers what they do, how to keep the list short, and how to build one.
What a plugin can contain, and where each part works
Per Anthropic's plugin platform-support page:
| Component | What it adds | Chat (claude.ai) | Cowork | Claude Code |
|---|---|---|---|---|
| Skills | Instructions loaded when a task matches | Yes | Yes | Yes |
| Commands | Named actions run as /plugin-name:command |
Loads as a skill | Yes | Yes |
| MCP connectors | Access to an outside app or data source | Yes | Yes | Yes |
| Agents (subagents) | Specialists Claude can delegate to | No | Yes | Yes |
| Hooks | Commands run automatically on events | No | Yes | Yes |
So a plugin does more in Claude Code than in a chat. In chat, only its skills, commands and connectors take effect.
Cowork, in this table, is the platform-support page's term for "Cowork tasks in the desktop app": longer, multi-step tasks the Claude desktop app runs on your files.
Plugins in claude.ai
- Everything lives under Customize > Plugins.
- Discover lists plugins from Anthropic's marketplaces, the directory, and your organisation.
- Add > Add marketplace takes a Git repository such as
owner/repo; Add > Upload plugin takes a.zipor.pluginfile. - Open a plugin to see its Skills, Connectors and other tabs. Turn it off with its "Disable plugin" toggle, or remove it from its menu.
- Adding a plugin does not connect its connectors for you; its Connectors tab shows each as Connected, Not connected or Not added.
- Plugins on your account also sync into Claude Code when you sign in there with the same account, listed as
<name>@synced. - Per the same page, Anthropic reviews plugins listed in its directory, but not plugins added from a marketplace URL or uploaded by hand.
Keeping the list short
Every enabled skill's name and description loads into each conversation, and Anthropic's docs note that overlapping or excessive descriptions make Claude pick the wrong skill. So keep enabled only what you use:
- Open Customize > Plugins and go through the list once a month.
- Keep a plugin you used in the last few weeks; disable the rest.
- Turn off plugins that change how every reply starts, such as workflow plugins that tell Claude to check for skills first, when you are doing everyday writing; turn them on for the work they are built for.
- Disable anything that can act on your computer or your accounts until you need it for a specific task.
Disabling is reversible: the toggle brings a plugin back unchanged.
In Claude Code, /plugin shows a "Not used recently" group on its Installed tab, and claude plugin details <name> prints an "Always-on" figure: the tokens a plugin adds to every session.
Plugins in Claude Code
Anthropic's official marketplace, claude-plugins-official, is added automatically the first time you start an interactive session.
/plugin
/plugin install <plugin>@claude-plugins-official/plugin opens a panel with Discover, Installed, Marketplaces and Errors tabs. The install command opens the plugin's details, including a "Will install" list and, for official plugins, a context-cost estimate, then asks for a scope:
| Scope | Recorded in | Who gets it |
|---|---|---|
| User | ~/.claude/settings.json |
You, every project |
| Project | .claude/settings.json |
Everyone in the repository (each person still installs it once) |
| Local | .claude/settings.local.json |
You, this repository only |
From PowerShell, without starting a session:
claude plugin install <plugin>@<marketplace> --scope user
claude plugin list
claude plugin disable <plugin>@<marketplace>
claude plugin enable <plugin>@<marketplace>
claude plugin uninstall <plugin>@<marketplace>
claude plugin marketplace add <owner>/<repo>Official-marketplace plugins update automatically; most other marketplaces do not unless you turn auto-update on in the Marketplaces tab.
EX-22 Install an official plugin
Anthropic's skills page uses skill-creator as its example, a plugin that helps write and test skills:
/plugin install skill-creator@claude-plugins-officialChoose "Install for you (user scope)". Expected: an install summary ending in "Plugin is now active" or a reload note. Then ask: "evaluate my meeting-notes skill with skill-creator". It walks you through writing test prompts and compares results with and without the skill.
EX-23 Package your own kit
Bundle the meeting-notes skill (section 8) and the citation-checker subagent (section 12) into one plugin.
cd ~\claude-practice
mkdir work-kit\.claude-plugin
mkdir work-kit\skills\meeting-notes
mkdir work-kit\agents
Copy-Item ~\skills\meeting-notes\SKILL.md work-kit\skills\meeting-notes\
Copy-Item $env:USERPROFILE\.claude\agents\citation-checker.md work-kit\agents\
code work-kit\.claude-plugin\plugin.jsonPaste into plugin.json, the manifest:
{
"name": "work-kit",
"description": "Meeting notes and citation checking",
"version": "1.0.0",
"author": { "name": "<your name>" }
}Then check and try it:
claude plugin validate .\work-kit
claude --plugin-dir .\work-kitExpected: Validation passed, then inside the session the skill appears as /work-kit:meeting-notes and the subagent as work-kit:citation-checker. Only plugin.json goes inside .claude-plugin/; the docs warn that components placed there do not load.
To use it in claude.ai, zip the work-kit folder with File Explorer as in Exercise 10, or with tar.exe as below, and upload it at Customize > Plugins > Add > Upload plugin:
tar.exe -a -c -f work-kit.zip work-kitIn chat, the meeting-notes skill works and the citation-checker agent is skipped, per the component table above.
BEST PRACTICE Best practices for plugins
- Before installing, read the "Will install" list, and in the plugin's source look at
hooks/hooks.json,.mcp.jsonand anybin/folder; permission rules and the sandbox do not cover a plugin's own hooks or servers. - Try new plugins at local or user scope before adding them at project scope.
- Third-party marketplaces do not auto-update by default; turning it on means code you reviewed can change later.
- Check what a plugin costs every turn with
claude plugin details <name>, and remove ones listed under "Not used recently".
CAUTION Safety
A plugin's hooks and MCP servers run on your computer as you. Read its "Will install" list before installing, prefer the official marketplace and Anthropic's directory, and install from other sources only when you trust whoever maintains them.
SECTION 15
Automation and headless use
claude -p runs Claude Code once from a single command and exits, which turns it into an ordinary CLI you can put in scripts. Scheduled tasks re-run a prompt on a timer.
One-shot runs
cd ~\claude-practice
claude -p "List the files in this folder and say what each contains, one line each"Expected: the answer prints and the command ends. Per Anthropic's headless page, it exits with code 0 on success and non-zero on failure, so $LASTEXITCODE works as in section 4. A -p run loads the same CLAUDE.md, skills, hooks and MCP servers an interactive session would.
The flags that matter for scripts:
| Flag | Effect |
|---|---|
--allowedTools "Read,Edit" |
Pre-approve listed tools; Bash(git diff *) pre-approves only commands starting git diff |
--permission-mode dontAsk |
Deny anything not pre-approved instead of waiting for an answer nobody will give |
--permission-mode acceptEdits |
Allow file edits and common file commands |
--output-format json |
Return JSON including result, session_id and total_cost_usd |
--output-format stream-json |
One JSON event per line as the run progresses |
--json-schema '<schema>' |
Force the answer into a given shape, returned in structured_output |
--continue, --resume <id> |
Carry on an earlier conversation |
The docs also describe --bare, which skips all local configuration for reproducible CI runs. It does not use your subscription login and needs an API key, so it is not for you yet.
EX-24 Pipe data in, get JSON out
$r = Get-Content .\analysis\data\raw\scores.csv | claude -p "What is the highest score and which id has it?" --output-format json | Out-String | ConvertFrom-Json
$r.result
$r.total_cost_usdExpected: the answer (id 2, score 15) and an estimated cost figure. The docs call that figure a client-side estimate that can differ from your bill. Piped input is capped at 10 MB.
Windows PowerShell 5.1 removes the double quotes inside a string passed to a program, which breaks --json-schema and similar flags. Tested: passing '{"a": "b"}' to a program in 5.1 arrived as {a: b}. Microsoft's about_Parsing page describes the behaviour, and says PowerShell 7.3 and later preserve the quotes. When a flag needs a JSON string, run the command in PowerShell 7 (winget install --id Microsoft.PowerShell -e, then open "PowerShell 7") or in Git Bash. Also note that in 5.1, > writes UTF-16 files, which tools expecting UTF-8, such as jq, may fail to read; | Out-File -Encoding utf8 <file> writes UTF-8 instead. Text captured from claude can come out garbled, because PowerShell decodes program output with the console's code page (IBM437 on a default US setup). Tested: a curly apostrophe captured that way became ΓÇÖ; after [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 the same text came through intact. Run that line at the start of any script that captures claude output.
EX-25 Batch-process meeting transcripts
This runs the meeting-notes skill (section 8) over every transcript in a folder, one fresh session each. The docs confirm that /skill-name inside a -p prompt expands the skill. Text after the skill name reaches it as its arguments; since the skill has no $ARGUMENTS placeholder, Claude Code appends it as an ARGUMENTS: line.
cd ~\claude-practice
mkdir transcripts, notes -Force
# Copy one or two meeting transcripts (.txt) into transcripts first
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
Get-ChildItem .\transcripts\*.txt | ForEach-Object {
$out = ".\notes\$($_.BaseName)-notes.md"
claude -p "/meeting-notes $($_.FullName)" --allowedTools "Read" | Out-File -Encoding utf8 $out
Write-Host "Done: $out"
}Expected: one -notes.md file per transcript. Each run counts towards your usage, so test on one file first. Check a few outputs against the transcripts before trusting the batch.
Running things on a schedule
| Where | How | Runs while |
|---|---|---|
| Inside a Claude Code session | /loop 10m <prompt> |
That session stays open |
| Claude desktop app | Scheduled tasks in the Code tab (Anthropic's desktop scheduled-tasks page) | Your computer is on and the app is running |
| Anthropic's cloud | Routines, set up with /schedule |
Always; runs on a fresh copy of a GitHub repository |
| This Claude app | Ask: "every Sunday at 6 pm, summarise what is due next week from my Projects" | Runs in the cloud on the schedule; results arrive as a new chat |
A cloud routine cannot see files on your computer, and, per the skills page, it does not read skills stored only in ~/.claude/skills/. Put anything a scheduled cloud run needs into your claude.ai account or the repository.
The Agent SDK, briefly
The same engine is available as Python and TypeScript packages (the Agent SDK) for building your own agent apps: a research assistant with your own tools, a bot for a team Slack. Worth knowing it exists; not needed for anything in this guide.
Agent-ready apps: three ways to drive one
An app described as agent-ready, drivable "from a CLI, a JSON control channel or an MCP server", offers up to three doors into the same program. A web search for the blurb's exact wording on 7 October 2026 found no matching product, so the routine below is general and works for any app that offers these doors.
| Door | What it means | How it gets used | Background |
|---|---|---|---|
| CLI | A command you type, with subcommands and flags | You run it in PowerShell; Claude Code runs it through its shell tool | Section 4 |
| JSON control channel | The app accepts commands as JSON objects, on standard input, a local socket or a web address, and answers in JSON | A script, or Claude, sends one object and reads the reply | Section 5 |
| MCP server | The app lists its actions as MCP tools | claude mcp add in Claude Code, or a connector in claude.ai; Claude calls the tools by name |
Section 11 |
A routine for getting to know any such app, safest steps first:
- Read its docs for the three doors. Search them for "CLI", "JSON", "API" or "RPC", and "MCP".
- CLI: run
<app> --help, then<app> <subcommand> --help. Look for a flag such as--jsonthat makes it print JSON; scripts and agents read JSON more reliably than tables. - JSON channel: send one read-only command by hand and read the reply. For a web address, PowerShell's
Invoke-RestMethod -Method Post -Uri <address> -ContentType 'application/json' -Body '<json>'does this; the address and command names come from the app's docs. - MCP: open the server in the MCP Inspector (Exercise 16) before giving it to Claude, so you see every tool it offers and what each one takes.
- Before Claude drives it, add deny rules (section 10) or Needs approval settings (Exercise 9) for anything that deletes, sends or publishes.
- Start with a read-only task in Manual mode and watch the tool calls.
Claude Code is itself an agent-ready app, so you can practise on it:
- CLI:
claude -p "<task>"(this section). - JSON:
--output-format jsonreturns one JSON object (Exercise 24);--output-format stream-json --verboseprints one JSON event per line as the run progresses, per the headless page. - MCP server:
claude mcp serveruns Claude Code as a stdio MCP server that offers its own tools, such as reading and editing files, to another MCP client like the Claude desktop app. Per Anthropic's MCP page it prints nothing when it starts, and the client is responsible for asking you to confirm each tool call.
Desktop Commander, a popular plugin, is another example of the MCP door: an MCP server that gives Claude a terminal and file tools on your computer.
An app with none of the three doors can still be driven through its screen. Claude in Chrome operates websites, and computer use operates desktop apps, by clicking and typing the way you would. Both are slower and less predictable than a CLI or MCP server, so they suit apps with no other way in.