little cups of claude

tips and techniques for Claude and Claude Code

Today we'll look at customizing the bar at the bottom of Claude Code with a status line.

A status line is a shell command that Claude Code runs for us. It receives session data as JSON on stdin, and whatever it prints shows up in its own row above the built-in footer. It runs locally, so it doesn't use any API tokens.

Let's dive in.

Let Claude Write It

The quickest way to get one is to describe what we want with the /statusline command:

/statusline show model name and context percentage with a progress bar

Claude Code writes a script into ~/.claude/ and updates our settings for us. To get rid of it later, /statusline clear (or /statusline delete) removes it.

The Setting

Under the hood, it's just a statusLine entry in ~/.claude/settings.json or our project settings:

{
  "statusLine": {
    "type": "command",
    "command": "~/.claude/statusline.sh",
    "padding": 2,
    "refreshInterval": 5
  }
}

type is always "command", and command can be a script path or an inline shell command. padding adds a little horizontal spacing. refreshInterval re-runs the command every N seconds, which is handy for clocks or anything that changes while the session sits idle. Without it, the script only runs on events, like a new assistant message, /compact finishing, or a permission mode change.

Writing Our Own

Here's a small script that shows the model, the folder we're in, and how full the context window is:

#!/bin/bash
input=$(cat)

MODEL=$(echo "$input" | jq -r '.model.display_name')
DIR=$(echo "$input" | jq -r '.workspace.current_dir')
PCT=$(echo "$input" | jq -r '.context_window.used_percentage // 0' | cut -d. -f1)

echo "[$MODEL] ${DIR##*/} | ${PCT}% context"

We make it executable and we're done. Claude Code reloads settings automatically, so the bar shows up as soon as we save:

chmod +x ~/.claude/statusline.sh

Every echo becomes its own row, so multi-line status lines work too. ANSI color codes like \033[32m work as well.

Fields Worth Knowing

The JSON has quite a bit in it. A few favorites:

  • cost.total_cost_usd and cost.total_duration_ms for an estimated session cost and running time
  • context_window.used_percentage and context_window.context_window_size
  • rate_limits.five_hour.used_percentage for Pro, Max, and Ultra subscribers
  • session_name, effort.level, and pr.number
  • worktree.name and worktree.branch while we're in a worktree session

Here's a cost and time readout:

#!/bin/bash
input=$(cat)

COST=$(echo "$input" | jq -r '.cost.total_cost_usd // 0')
MS=$(echo "$input" | jq -r '.cost.total_duration_ms // 0')
SECS=$((MS / 1000))

printf '$%.2f | %dm %ds\n' "$COST" $((SECS / 60)) $((SECS % 60))

Some fields are absent or null depending on the session. rate_limits only appears after the first API response, and vim only appears with vim mode on. The // 0 and // empty fallbacks in jq keep things from breaking.

Testing And Gotchas

We don't need a live session to try a script. We can pipe in some mock JSON ourselves:

echo '{"model":{"display_name":"Hal"},"workspace":{"current_dir":"/home/dave/discovery"},"context_window":{"used_percentage":25}}' \
  | ~/.claude/statusline.sh

Neat! A few things to watch for:

  • The output only shows when the script exits with code 0. An error or empty output leaves the bar blank.
  • The script runs often, so slow commands like git status can lag. The docs suggest caching results in a file keyed by session_id.
  • tput cols can't see the terminal from inside the script. We read the COLUMNS environment variable instead.
  • Until we accept the workspace trust dialog for a folder, the status line stays blank.

More info about status lines can be found at the Claude Code docs.

Today we'll look at checkpoints in Claude Code, and how /rewind lets us back up when a session heads somewhere we didn't want.

Every time we send a prompt, Claude Code captures the state of our code first. If the next few changes go sideways, we can roll the code, the conversation, or both back to that point.

Let's get started.

How It Works

Each prompt that starts a turn creates a new checkpoint. A few details worth knowing:

  • Claude Code keeps file snapshots for the 100 most recent checkpoints in a session.
  • Checkpoints are saved with the conversation, so /rewind still works after we resume a session.
  • Snapshots get cleaned up around 30 days after the session last saved one.

To keep them longer, we can raise cleanupPeriodDays in our settings:

{
  "cleanupPeriodDays": 60
}

Opening the Menu

There are two ways in. We can type the command:

> /rewind

Or press Esc twice while the prompt input is empty. If there's text in the input, double Esc clears it instead, but the text goes into our input history, so Up brings it back later.

The menu lists the prompts we've sent this session. We pick the point we want to go back to.

Picking What to Restore

After choosing a prompt, we get a few options:

  • Restore code and conversation: everything goes back to that point
  • Restore conversation: rewind the chat, keep the current code
  • Restore code: revert the files, keep the chat
  • Never mind: back out without changing anything

Restore conversation is handy when the code turned out fine but the conversation went down a rabbit hole. Restore code is the reverse: we keep everything Claude learned along the way and throw away the edits.

After restoring the conversation, our original prompt comes back in the input field, ready to edit and resend.

Summarize Instead

The same menu has two options that don't undo anything. Summarize from here compresses everything after the selected point into a summary, and Summarize up to here compresses everything before it.

It works like a targeted /compact, and files on disk aren't touched. If we highlight a summarize option with the arrow keys, we can type instructions to steer what the summary focuses on.

To try a different approach while keeping the original session intact, the docs suggest branching instead:

claude --continue --fork-session

What Isn't Tracked

Checkpoints cover edits from Claude's file editing tools. Some changes fall outside that:

# Edited by Claude's Edit tool: restored
src/hal/pod-bay-doors.ts

# Only ever changed by a Bash command: not restored
generated/schema.ts

Once Claude has edited a file with its editing tools, later Bash changes to that same file are covered. A file that only Bash touched stays as it is.

Subagent edits usually aren't captured either, beyond files Claude had already edited in our conversation. Changes we make by hand outside Claude Code, edits from other sessions, and symlinked or hard-linked files are also left alone.

Not a Replacement for Git

Checkpoints are for quick, session-level recovery. For anything we want to keep, or anything a Bash command changed, version control is still the safety net:

git status
git diff
git restore generated/schema.ts

A small commit before letting Claude loose on a big refactor gives us both kinds of undo.

More info about checkpoints can be found at the Claude Code docs.

Today we'll look at connecting MCP servers to Claude Code, so Claude can reach tools and data that live outside our project.

The Model Context Protocol (MCP) is an open standard for hooking AI tools up to outside services. Once a server is connected, its tools show up next to the built-in ones, and Claude can call them as part of its normal work.

Let's take a look.

Adding a Server

Remote servers over HTTP are the recommended option. One command does it:

claude mcp add --transport http notion https://mcp.notion.com/mcp

# With a bearer token
claude mcp add --transport http hal-api https://api.example.com/mcp \
  --header "Authorization: Bearer $HAL_TOKEN"

Local servers run as a process on our machine over stdio. Everything after the -- is the command that starts the server:

claude mcp add --env AIRTABLE_API_KEY=YOUR_KEY --transport stdio airtable \
  -- npx -y airtable-mcp-server

That -- matters. Without it, Claude Code would try to read the server's own flags, like -y, as its options. The order of --env matters too: if the server name comes right after it, the CLI reads the name as another KEY=value pair, so we keep another option like --transport in between.

The older SSE transport is deprecated. Newer versions of Claude Code try HTTP first and fall back to SSE on their own.

Picking a Scope

Every server is added at one of three scopes:

  • local (the default): this project only, private to us, stored in ~/.claude.json
  • project: this project, shared with the team through a .mcp.json file at the root
  • user: every project on our machine, also stored in ~/.claude.json
claude mcp add --transport http shared-server --scope project https://example.com/mcp
claude mcp add --transport http hubspot --scope user https://mcp.hubspot.com/anthropic

If the same server name is defined at more than one scope, local wins over project, and project wins over user. Entries aren't merged, the whole winning definition is used.

Sharing With .mcp.json

Project-scoped servers land in .mcp.json, which we check into git so everyone gets the same tools:

{
  "mcpServers": {
    "marvin-db": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@example/db-server"],
      "env": { "DB_URL": "${MARVIN_DB_URL}" }
    },
    "data-api": {
      "type": "http",
      "url": "${DATA_API_URL:-https://api.example.com}/mcp",
      "headers": { "Authorization": "Bearer ${DATA_API_KEY}" }
    }
  }
}

${VAR} expands an environment variable, and ${VAR:-default} falls back to a default when it isn't set. Expansion works in command, args, env, url, and headers, so secrets stay out of the repo.

For safety, Claude Code asks before using servers from a project's .mcp.json in interactive sessions. claude mcp reset-project-choices resets those approvals.

Managing Servers

A few commands cover the day-to-day:

claude mcp list          # every server, with health status
claude mcp get notion    # details for one server
claude mcp remove notion

Inside a session, /mcp shows each server's status. It's also where we sign in to servers that use OAuth: pick the server, follow the browser flow, and Claude Code stores and refreshes the tokens for us. From the shell, claude mcp login <name> does the same thing.

We can also toggle a server off in /mcp without deleting its config.

Prompts and Resources

Servers can offer more than tools. Their prompts show up as slash commands, and their resources can be @-mentioned like files:

/mcp__github__pr_review 456
Can you analyze @github:issue://123 and suggest a fix?

Typing @ lists resources from every connected server right alongside our files. Neat!

More info about MCP in Claude Code can be found at the Claude Code docs.

#8: Permission Modes 🎚️

Today we'll look at permission modes in Claude Code, which set how much Claude can do in a session before it stops to ask us.

Where permission rules handle individual tools, a mode sets the baseline for the whole session. Picking the right one for the job saves a lot of prompts, or adds a few where we want them.

Let's dive in.

The Modes

Here's what runs without a prompt in each one:

  • default: reads only. The CLI labels it Manual, and manual works as an alias.
  • acceptEdits: reads, file edits, and common filesystem commands like mkdir, mv, and cp, for paths in our working directory.
  • plan: reads and exploring. Claude researches and writes a plan, but doesn't edit our source.
  • auto: everything, with a background classifier checking actions against what we asked for.
  • dontAsk: only pre-approved tools. Anything that would prompt is denied instead.
  • bypassPermissions: everything. For isolated containers and VMs only.

Our deny rules still block in every mode, bypassPermissions included.

Switching Mid-Session

Pressing Shift+Tab cycles through modes, and the status bar shows which one we're in:

⏸ manual mode on
⏵⏵ accept edits on
⏸ plan mode on
⏵⏵ auto mode on

The cycle runs default, acceptEdits, plan, then any optional modes. auto joins the cycle when it's available to our session. bypassPermissions only shows up if we started with it, and dontAsk never appears in the cycle at all.

Picking One at Startup

The --permission-mode flag starts a session in any mode:

claude --permission-mode plan

To make a mode the default, we set defaultMode in a settings file:

{
  "permissions": {
    "defaultMode": "acceptEdits"
  }
}

One gotcha: auto and bypassPermissions don't take effect from a project's .claude/settings.json or .claude/settings.local.json. For auto, the docs say to put it in ~/.claude/settings.json instead.

Plan Mode

Plan mode is great for unfamiliar code or big changes. Besides Shift+Tab, we can put /plan in front of a single prompt:

/plan Move Samantha's settings screen to the new layout system

When the plan is ready, Claude asks how to continue. We can approve it and let Claude work in auto mode, approve it and review each edit by hand, or keep planning. Pressing Ctrl+G opens the plan in our text editor so we can change it first. Neat!

Auto and dontAsk

In auto mode, a separate classifier model reviews actions before they run and blocks anything that goes beyond our request. Recent versions of Claude Code start interactive terminal sessions in auto mode by default. Explicit ask rules still force a prompt.

dontAsk is the opposite: nothing prompts, and anything not pre-approved is denied. That makes it a good fit for CI, paired with an exact allowlist:

claude -p "run the test suite" \
  --permission-mode dontAsk \
  --allowedTools "Bash(npm test)" "Read"

Bypass Permissions

bypassPermissions skips permission prompts entirely, including for writes to protected paths like .git and .claude. The docs are clear that this belongs only in containers or VMs where Claude Code can't do damage:

claude -p "<prompt>" --dangerously-skip-permissions

To make sure nobody turns it on by accident, we can disable it in settings:

{
  "permissions": {
    "disableBypassPermissionsMode": "disable"
  }
}

That works from any settings file, and in managed settings it can't be overridden.

More info about permission modes can be found at the Claude Code docs.

#7: Permission Rules 🚦

Today we'll look at permission rules in Claude Code, the settings that decide which tools run without asking, which always ask, and which never run at all.

Clicking "Yes" on the same npm test prompt for the fifth time gets old fast. A few lines in a settings file fix that, and they can block the things we never want Claude touching.

Let's get started.

Allow, Ask, Deny

Permission rules live under permissions in a settings file. .claude/settings.json is shared with the team, .claude/settings.local.json stays on our machine, and ~/.claude/settings.json applies everywhere:

{
  "permissions": {
    "allow": ["Bash(npm run *)", "Bash(git commit *)"],
    "ask": ["Bash(git push *)"],
    "deny": ["Read(./.env)", "Read(./secrets/**)"]
  }
}

Allow rules run without a prompt, ask rules always prompt, and deny rules block the call.

Rules are checked in a fixed order: deny, then ask, then allow. The first match wins, and specificity doesn't matter. A broad deny like Bash(aws *) blocks aws s3 ls even if we also allowed that exact command.

Bash Rules

A rule is either a bare tool name like Bash, or a tool plus a specifier in parentheses. For Bash, * matches any text, and where we put the space matters:

Bash(npm run build)   exactly that command
Bash(npm run *)       npm run build, npm run test --watch
Bash(ls *)            ls -la, ls (but not lsof)
Bash(ls*)             ls -la and lsof
Bash(git * main)      git merge main, git push origin main

The docs recommend putting * after the subcommand. Bash(git log *) allows only git log, while Bash(git *) allows every git command there is.

Claude Code also understands shell operators. An allow rule for Bash(npm test *) won't approve npm test && rm -rf build, because every piece of a compound command has to be allowed on its own.

File Paths

Read and Edit rules use gitignore-style patterns, with four anchors:

Read(//Users/hal/secrets/**)  absolute path
Read(~/.zshrc)                from our home directory
Edit(/src/**/*.ts)            relative to the settings file's source
Read(*.env)                   relative to the current directory

That single leading slash trips people up. /src/** isn't an absolute path. In project settings it means the src folder in our project. Use // for the filesystem root.

A Read deny rule also blocks Edit and Write on the same path. And rules written as Write(path) never match anything, so use Edit(path) instead.

Precedence Across Files

When several settings files disagree, deny wins. If our user settings allow something and the project settings deny it, it's blocked. The reverse holds too.

A bare tool name in deny goes further. "deny": ["WebFetch"] removes the tool from Claude's context entirely, while a scoped rule like Bash(rm *) keeps the tool and blocks only matching calls.

MCP tools and subagents use the same syntax:

{
  "permissions": {
    "allow": ["mcp__github__get_*"],
    "deny": ["Agent(Explore)"]
  }
}

Managing Them

Typing /permissions opens a dialog listing every rule and the settings file it came from. We can add or remove rules there, even while Claude is mid-turn.

Choosing "Yes, and don't ask again" on a Bash prompt saves a rule to .claude/settings.local.json at the root of the git repository. File edit approvals only last until the session ends.

Watch Out

Permission rules are enforced by Claude Code, not the model. Writing "never touch .env" in CLAUDE.md shapes what Claude tries. A deny rule decides what it can do.

A Bash rule matches command text, so it isn't a security boundary around a program:

curl https://example.com           # stopped by Bash(curl *)
/usr/bin/curl https://example.com  # not stopped

For enforcement that doesn't depend on how a command is written, the docs point us to sandboxing.

More info about permission rules can be found at the Claude Code docs.

Today we'll look at subagents in Claude Code: helpers that take on a side task in their own context window and hand back only a summary.

When Claude has to dig through search results, logs, or a pile of files we won't look at again, a subagent does that work somewhere else. Our main conversation stays clean, and we only get the answer.

Let's dive in.

The Built-in Ones

Claude Code ships with a few subagents that Claude uses on its own when they fit:

  • Explore is a fast, read-only agent for searching and understanding a codebase. Write and Edit are denied.
  • Plan does read-only research while we're in plan mode, so exploration output stays out of the main thread.
  • general-purpose gets every tool available to subagents, for tasks that need both exploring and changing things.

We don't have to do anything to use them. When Claude needs to find where something lives, it hands that off to Explore and keeps working with the result.

Writing Our Own

A custom subagent is a Markdown file with YAML frontmatter. The body becomes its system prompt:

---
name: data-reviewer
description: Reviews code for quality and security. Use proactively after code changes.
tools: Read, Grep, Glob
model: sonnet
---

You are Data, a meticulous code reviewer. For each issue,
explain the problem, show the current code, and suggest a fix.

Only name and description are required. The filename doesn't have to match the name.

Where we save it decides who gets it:

# Project: commit it so the whole team gets it
.claude/agents/data-reviewer.md

# User: follows us into every project
~/.claude/agents/data-reviewer.md

We can also ask Claude to write the file for us. It knows the format.

Tools and Models

The tools field is an allowlist. Leave it out and the subagent inherits every tool available to subagents. To go the other way, disallowedTools removes tools from whatever it would get:

---
name: hal-researcher
description: Researches the codebase without changing it
disallowedTools: Write, Edit, mcp__github
---

That one keeps Bash and every other tool, minus file writes and the github MCP server.

The model field takes sonnet, opus, haiku, fable, a full model ID, or inherit. Routing a high-volume job to haiku is a nice way to keep costs down.

Calling Them

Claude decides when to delegate based on each subagent's description, so a clear one matters. Phrases like "use proactively" encourage it to delegate on its own.

We can also be explicit. Naming the agent in a prompt usually works, and an @-mention guarantees it:

Use the data-reviewer subagent to check my last commit
@agent-data-reviewer look at the auth changes

Or we can run the whole session as that agent, with its tools and model:

claude --agent data-reviewer

Setting "agent": "data-reviewer" in .claude/settings.json makes it the default for the project. Neat!

Watch Out

Frontmatter field names are camelCase and must match exactly. A typo like disallowed-tools is ignored without an error, so the subagent quietly gets more tools than we meant.

If ~/.claude/agents/ didn't exist when the session started, a newly created agent won't show up until we restart Claude Code. Edits to existing agent files are picked up within a few seconds.

To keep Claude from using a particular subagent, deny it like any other tool:

{
  "permissions": {
    "deny": ["Agent(Explore)"]
  }
}

More info about subagents can be found at the Claude Code docs.

#5: Auto Memory 🧠

Today we'll look at how Claude Code remembers things between sessions with auto memory, and how it fits next to the CLAUDE.md files we write ourselves.

The split is simple. We write CLAUDE.md to give Claude instructions. Claude writes auto memory to keep notes for itself. Auto memory is on by default in local sessions.

Let's dive in.

What Gets Saved

As it works, Claude saves four kinds of notes, and records the kind in each file's frontmatter:

  • user: our role, expertise, and how we like to work
  • feedback: corrections we give and approaches we confirm
  • project: ongoing work, deadlines, and decisions the code doesn't show
  • reference: where to find things outside the project, like an issue tracker

It skips anything it can work out from the codebase, and anything our CLAUDE.md files already say. It also doesn't save something every session, only what looks useful later. When it does, we'll see a message like "Saved 2 memories".

Where It Lives

Each project gets its own folder:

~/.claude/projects/<project>/memory/
  MEMORY.md                 # the index, one line per memory
  user_role.md              # one memory per file
  feedback_testing.md
  reference_dashboards.md

The <project> comes from the git repository, so every worktree and subdirectory of the same repo shares one memory folder. It stays on our machine, and isn't synced to other machines or cloud sessions.

What Loads

At the start of each conversation, Claude Code loads the first 200 lines or 25KB of MEMORY.md, whichever comes first. The topic files don't load at startup. Claude reads them when it needs them.

- [Prefers bun](feedback_bun.md): use bun, never node or npm
- [Staging deploys](reference_staging.md): how we ship to staging
- [Q4 freeze](project_freeze.md): no schema changes until Jan 5

That's why the index stays short. When MEMORY.md gets close to the limit, Claude Code reminds Claude to tighten it up. Neat!

The /memory Command

/memory is the control panel:

> /memory

It lists our CLAUDE.md and CLAUDE.local.md files, has a toggle for auto memory, and opens the memory folder. Picking a file opens it in our editor. Memory files are plain markdown, so we can edit or delete anything that's wrong.

Telling It What To Remember

When we say something like "remember that the API tests need a local Redis", Claude saves it to auto memory. If we want it in CLAUDE.md instead, we just ask: "add this to CLAUDE.md".

For instructions that only matter in part of the codebase, .claude/rules/ is the tidier spot:

---
paths:
  - "src/api/**/*.ts"
---

# API rules
- Validate every request body with zod
- Use the shared error response format

A rule with paths only loads once Claude reads or edits a matching file. Rules without paths load at launch, like CLAUDE.md does.

Turning It Off

The /memory toggle saves autoMemoryEnabled to our user settings. To switch it off for one project, set it in that project's settings:

{
  "autoMemoryEnabled": false
}

And autoMemoryDirectory moves the whole thing somewhere else, if we'd rather keep it in a synced folder.

Watch Out

Subagents don't get the main conversation's auto memory, apart from forks, which inherit the whole parent conversation. And memory files are never cleaned up automatically. They stay until we or Claude edit or delete them, so it's worth a look through /memory every so often.

More info about auto memory can be found at the Claude Code docs.

Today we'll look at running Claude Code without the interactive UI, which turns it into a building block for scripts, CI, and cron jobs.

The -p flag (short for --print) is the key. It sends one prompt, lets Claude work, prints the result, and exits. The same engine powers the Agent SDK, so anything we learn here carries over.

Let's take a look.

The Basics

At its simplest, we pass a prompt and read the answer:

claude -p "Explain what this project does"

It reads stdin too, so it fits right into a pipeline:

git diff HEAD~5 | claude -p "Summarize these changes" > changelog.txt

For scripts and CI, the docs recommend adding --bare. It skips discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md, so startup is faster and the run doesn't depend on whatever happens to be configured on the machine:

claude --bare -p "Summarize README.md" --allowedTools "Read"

Output Formats

The --output-format flag picks what comes back:

  • text: just the final answer (the default)
  • json: the answer plus metadata like session_id, usage, and total_cost_usd
  • stream-json: one JSON event per line while Claude works
claude -p "Analyze this codebase" --output-format json | jq -r '.result'

For structured data, --json-schema makes the answer match a schema, and it shows up in a structured_output field:

claude -p "List the exported functions in src/hal.ts" \
  --output-format json \
  --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \
  | jq '.structured_output'

Neat! If Claude declines or the run fails, that field is missing, so it's worth checking for it before using it.

Turn And Budget Limits

Unattended runs need guardrails:

claude -p "Review this PR for bugs" \
  --max-turns 5 \
  --max-budget-usd 1.00 \
  --fallback-model sonnet,haiku

--max-turns caps the agentic turns and exits with an error when it hits the limit. --max-budget-usd stops the run once estimated spend reaches the cap (it's a client-side estimate, so leave some headroom). --fallback-model takes a list of models to try if the main one is overloaded.

Permissions

There's nobody around to click "Allow" in a script. --allowedTools pre-approves exactly what the job needs, using permission rule syntax:

claude -p "Look at the staged changes and write a commit" \
  --allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)"

The space before * matters. Bash(git diff *) matches git diff --cached but not git diff-index.

For a locked-down CI run, --permission-mode dontAsk denies anything that would otherwise prompt, while still allowing reads and whatever our allow rules cover.

In GitHub Actions

Anthropic publishes an official action, so we don't have to install the CLI by hand:

name: Claude review
on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: "Review this pull request for bugs and security issues"

Continuing Conversations

Multi-step scripts can pick a conversation back up:

# Save the session ID from the first run
session_id=$(claude -p "Start a review of src/" --output-format json | jq -r '.session_id')

# Continue that exact conversation
claude -p "Now focus on the database queries" --resume "$session_id"

# Or continue the most recent one
claude -p "Summarize everything we found" --continue

Watch Out

Without --bare, a -p run in a project folder runs that project's hooks and connects its .mcp.json servers, even in a folder we've never trusted, and there's no trust dialog to stop it. On CI or with code we didn't write, --bare is the safer default.

To add instructions for one script without touching any settings, there's --append-system-prompt.

More info about running Claude Code from scripts can be found at the Claude Code docs.

Today we'll check out how to build our own slash commands in Claude Code using skills.

Custom slash commands started out as single Markdown files in a commands folder. They've since been merged into skills. Both still work, and both show up in the same / menu, but skills can do quite a bit more.

Let's get started.

Commands And Skills

A file at .claude/commands/deploy.md creates /deploy. So does a folder at .claude/skills/deploy/ with a SKILL.md inside:

# Older format (still works)
.claude/commands/deploy.md

# Skill (recommended for new work)
.claude/skills/deploy/SKILL.md
.claude/skills/deploy/checklist.md
.claude/skills/deploy/scripts/smoke.sh

The big difference is the folder. A skill can carry templates, checklists, and scripts alongside its instructions, and Claude can load a skill on its own when it's relevant, without us typing the command.

If both exist with the same name, the skill wins.

Frontmatter

Skills are configured with YAML frontmatter at the top of SKILL.md:

---
name: deploy
description: Build, test and deploy the app to production
disable-model-invocation: true
argument-hint: [environment]
allowed-tools: Bash(bun run build) Bash(bun run deploy *)
---

Deploy to $ARGUMENTS following our release checklist
in checklist.md.

A few fields worth knowing:

  • name is the command we type. It defaults to the folder name.
  • description is how Claude decides when the skill applies, so put the main use case first.
  • disable-model-invocation: true means only we can run it. Good for anything with side effects.
  • allowed-tools pre-approves tools while the skill runs, so we don't get permission prompts for them.

Arguments

Everything after the command name lands in $ARGUMENTS. For individual pieces, indexes start at zero:

---
name: fix-issue
arguments: [issue, branch]
---

Fix issue #$issue on the $branch branch.
Same thing by index: #$0 on $1.

Running /fix-issue 42 main fills in 42 and main. Quotes group words, so /fix-issue 42 "release candidate" passes two arguments, not three.

Live Context

Lines with !`command` run before Claude ever sees the skill, and the output replaces the line:

---
name: commit
description: Write a commit for the staged changes
allowed-tools: Bash(git status) Bash(git diff *) Bash(git log *) Bash(git commit *)
---

## Context
- Status: !`git status`
- Staged diff: !`git diff --cached`
- Recent commits: !`git log --oneline -10`

Write one clear commit message for these changes and commit.

Claude gets the real diff already inlined, no extra tool calls needed. Neat!

${CLAUDE_SKILL_DIR} points at the skill's own folder, which makes bundled scripts easy to call from anywhere.

Bundled Skills

Claude Code ships with a set of skills of its own, like /code-review, /batch, /debug, /loop, and /claude-api. They're good examples of how to structure longer workflows, and we can turn them off with the disableBundledSkills setting.

Personal vs Project

Project skills live in .claude/skills/ and get committed for the whole team. Personal ones live in ~/.claude/skills/ and follow us into every project:

mkdir -p ~/.claude/skills/explain

cat > ~/.claude/skills/explain/SKILL.md << 'END'
---
description: Explain code for someone new to the project
---

Explain this code for a new teammate. Cover what it does,
why it's built this way, and any gotchas.
END

Watch Out

If a !`command` line fails, the whole skill invocation stops, and Claude never sees the skill. Commands that are expected to exit non-zero need || true on the end.

Those commands also never prompt for permission. Outside auto mode, anything not already allowed makes the skill fail, which is why the commit example lists its git commands in allowed-tools.

More info about skills can be found at the Claude Code docs.

#2: Hook Basics 🪝

Today we'll look at one of the best ways to make Claude Code behave the same way every time: hooks.

Hooks run our own code at key moments in a Claude Code session. Instead of hoping Claude remembers to format a file or skip a protected directory, we make it happen automatically, on every matching event.

Let's dive in.

Setting Them Up

Hooks live in our settings files. The user file (~/.claude/settings.json) applies to every project, .claude/settings.json is shared with the team, and .claude/settings.local.json stays on our machine. Plugins, skills, and subagents can bring their own hooks too.

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.file_path' | xargs bunx prettier --write"
          }
        ]
      }
    ]
  }
}

This one runs Prettier every time Claude Code edits or writes a file. Every hook gets a JSON payload on stdin, so jq pulls the file path right out of it. Neat!

The Events

Claude Code has more than 30 hook events now. These are the ones we'll reach for most:

  • PreToolUse fires before a tool call and can block it
  • PostToolUse fires after a tool call succeeds
  • UserPromptSubmit fires when we send a prompt, before Claude sees it
  • SessionStart fires when a session begins or resumes
  • Stop fires when Claude finishes responding, and can make it keep going
  • Notification fires when Claude Code wants our attention
  • PreCompact and PostCompact wrap context compaction
  • SubagentStart and SubagentStop wrap subagent runs

There are also events for config changes, file changes on disk, worktrees, model switches, permission requests, and MCP elicitations.

{
  "hooks": {
    "Notification": [
      {
        "matcher": "permission_prompt|idle_prompt",
        "hooks": [{ "type": "command", "command": "say 'HAL needs us'" }]
      }
    ]
  }
}

That one uses macOS say so we hear it when Claude is waiting on us.

Five Handler Types

Each hook handler has a type:

  • command runs a shell command (the most common)
  • http POSTs the event JSON to a URL
  • mcp_tool calls a tool on one of our MCP servers
  • prompt asks a Claude model for a quick yes/no style decision
  • agent spawns a subagent that can read files before deciding (still experimental)

Matchers And if

The matcher field filters what a hook fires on. For tool events it matches the tool name, so Bash, Edit|Write, and mcp__.* all work. For more precise filtering on tool events, the if field takes one permission rule:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "if": "Bash(git push *)",
            "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/check-branch.sh"
          }
        ]
      }
    ]
  }
}

Note that if goes on the handler, next to type. It holds exactly one rule, so two conditions means two handlers.

Exit Codes

How our hook exits decides what happens next:

  • Exit 0: success, and the action goes ahead
  • Exit 2: a blocking error. On a PreToolUse hook the tool call is stopped, and our stderr goes back to Claude as the reason
  • Anything else: a non-blocking error, and the action still goes ahead
#!/usr/bin/env python3
import json, sys

data = json.load(sys.stdin)
path = data.get("tool_input", {}).get("file_path", "")

if any(p in path for p in [".env", "bun.lock", ".git/"]):
    print(f"Blocked: {path} is protected", file=sys.stderr)
    sys.exit(2)

Claude reads that message and tries another approach.

Watch Out

Exit code 1 does not block anything, even though it's the usual Unix failure code. If a hook is enforcing a policy, use exit 2.

The timeout field is in seconds, and command hooks default to 600. All matching hooks for an event run in parallel. Edits to hooks in our settings files are picked up automatically, and /hooks opens a read-only browser showing every hook and where it came from.

More info about hooks can be found at the Claude Code docs.

Page 2 of 3