Claude Code's built-in tools cover most coding work. Expert-level leverage comes from the extension layer. Instruction files steer every session. MCP servers reach systems Claude can't see. Skills package procedures. Plugins ship all of it to other repos and people, and mods change Claude Code itself. Core 2 covered these features from the user's side, and Core 3 treated them as a knowledge library. This session is the builder's view. For each extension you'll learn how to author it, scope it, test it and version it, and where its trust boundary sits.

By the end you will be able to:

Version stampEverything on this page is as of 2026-10-24 · v2.1.310 (the newest changelog entry checked). Claude Code ships weekly, so a version-gated feature says "requires v2.1.xxx+" beside it. Each concept links its docs page under code.claude.com/docs. Re-check a default there before you build on it.
Always-on text (instruction files), on-demand content (skills), external tools (MCP), deterministic code on events (hooks, mods), isolated workers (subagents), and packaging (plugins). The dashed box is what Claude Code's permission rules and sandbox govern. Code outside it runs as you. Hover or focus an extension for what it adds; each spoke says when it reaches the loop.

Instruction Files

Instruction files are the cheapest extension and the weakest: text that Claude reads every session and is free to weigh against everything else. Two things set an expert apart here. You know which file loads where and when, down to the subdirectory and the compaction boundary. And you know when text is the wrong tool and a hook or deny rule should do the job instead.

CLAUDE.md Versus AGENTS.md

CLAUDE.md is Claude Code's native instruction file. AGENTS.md is the convention other coding agents read. Since v2.1.277, Claude Code reads AGENTS.md on its own. It does so through a built-in mod, cc-plugin-agents-md, so a repository set up for other tools works without a CLAUDE.md, an import or a setting (memory docs).

How the default works. With the default Project instructions value, claude-md-or-agents-md, Claude reads AGENTS.md only when no CLAUDE.md counts. Three files count, in your working directory or any directory above it: CLAUDE.md, .claude/CLAUDE.md and CLAUDE.local.md. Three others don't count and keep loading alongside AGENTS.md: your ~/.claude/CLAUDE.md, your organization's managed CLAUDE.md, and .claude/rules/ files. When nothing counts, Claude loads every AGENTS.md and .claude/AGENTS.md from the working directory upward and prints no CLAUDE.md found; AGENTS.md loaded: …. It also loads a subdirectory's AGENTS.md when it opens a file there with Read, provided that subdirectory has no CLAUDE.md files of its own. It never reads AGENTS.local.md, AGENTS.override.md or anything under .agents/.

Project instructions valueWhat Claude reads
claude-md-or-agents-md (default)CLAUDE.md files, or AGENTS.md files when no CLAUDE.md or CLAUDE.local.md exists at the working directory or above
claude-md-and-agents-mdBoth, each directory's CLAUDE.md first and its AGENTS.md after; an AGENTS.md already imported or symlinked isn't read twice
claude-mdCLAUDE.md files only
managed-onlyOnly the managed CLAUDE.md and auto memory at launch. Subdirectory CLAUDE.md, subdirectory rules and path-scoped rules still load on demand

Set it in /config, or in a settings file under the built-in plugin's ID. Claude Code reads that entry only from ~/.claude/settings.json, a --settings file or managed settings, and ignores it in project and local settings. Before v2.1.285 the ID was agents-md@builtin; v2.1.285+ reads either.

{
  "pluginConfigs": {
    "cc-plugin-agents-md@builtin": {
      "options": { "instructionFiles": "claude-md-and-agents-md" }
    }
  }
}

Why it matters. Most teams now share a repository with Codex, Cursor, Copilot or Gemini users. Your goal is a single source of truth with Claude-specific additions layered on top, and no silent duplication. The robust pattern works in every session type, including ones that can't read AGENTS.md directly: an import at the top of CLAUDE.md, followed by Claude-only notes.

@AGENTS.md

## Claude Code
- Use plan mode for changes under `src/billing/`.
- Run `make check` before declaring a task done; paste its last 20 lines as evidence.

A symlink (ln -s AGENTS.md CLAUDE.md) also works if you need nothing Claude-specific. It has two costs. Edit and Write refuse to write through the symlink and redirect Claude to AGENTS.md. On Windows, Git checks a committed symlink out as a one-line text file unless core.symlinks is on. If anyone clones on Windows, use the import.

Toggle the files in a repository and the Project instructions value, then compare session start with Claude reading a file in packages/api/. This follows the rules on the memory docs page as of v2.1.310. "Loads" means delivered into context, not obeyed. A lamp marks each delivered file, numbered in delivery order; the staple is the @AGENTS.md import, and the small lamp on the right is the built-in mod that reads AGENTS.md.
Pitfalls that bite AGENTS.md repos
  • Adding a personal CLAUDE.local.md switches AGENTS.md off for you. It counts for the check. Fix it with claude-md-and-agents-md.
  • A CLAUDE.md that says "read AGENTS.md" in words isn't an import. Claude sees the file only if it decides to open it. Use @AGENTS.md.
  • Old workarounds now duplicate. A SessionStart hook that prints AGENTS.md adds a second copy once Claude reads it directly. Remove the hook.
  • Support can be absent. This happens on versions before v2.1.277, when the built-in plugin is disabled in /plugin, sometimes in the first session after upgrading from v2.1.276 or earlier, and before v2.1.281 on Bedrock or telemetry-off sessions. The import pattern works in all of them.
Where AGENTS.md read through the setting differs from CLAUDE.md

The memory docs list two behavioral differences for an AGENTS.md that Claude reads through the Project instructions setting, as opposed to one a CLAUDE.md imports:

  • InstructionsLoaded hooks don't fire for it. They fire as usual for an imported or symlinked AGENTS.md. If you audit instruction loading with that hook (its load_reason values are session_start, nested_traversal, path_glob_match, include, compact), a directly read AGENTS.md is invisible to it. That's another argument for the import.
  • --add-dir directories. With CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1, an added directory's CLAUDE.md loads but its AGENTS.md doesn't.

Inside an AGENTS.md, @path imports are expanded and claudeMdExcludes applies. Subagents that start without project instructions start without it too. The setting change "applies from the next message you send", so you don't need a restart. Migrating the other way? /init reads Cursor and Copilot rule files (plus AGENTS.md, Devin, Windsurf and Cline rules with CLAUDE_CODE_NEW_INIT=1), and /import brings over another agent's instruction files, MCP servers, commands, subagents and skills. Source: memory.

Rules

Rules are Markdown files under .claude/rules/, discovered recursively (subfolders and symlinks work). Each file should cover one topic: testing.md, api-design.md. They exist for two reasons. They keep the root CLAUDE.md short, and they let you scope instructions to the files they're about, so the API rules don't cost context while Claude edits CSS.

Mechanism. The only frontmatter field Claude Code reads is paths. Any other field is ignored without error, and the frontmatter is stripped before loading.

  • No paths: the rule loads at launch, with the same priority as .claude/CLAUDE.md.
  • With paths: it loads when Claude uses Read, Write or Edit on a matching file. It also loads when Claude views a matching file with a Bash command that counts as a read, such as cat or head on a single file.
  • User rules in ~/.claude/rules/ load before project rules. Neither set overrides the other, so if they conflict Claude may follow either one.
---
paths:
  - "src/api/**/*.ts"
  - "tests/api/**/*.test.ts"
---

# API rules
- Validate every request body with the zod schema in `src/api/schemas/`.
- Errors use `ApiError` from `src/api/errors.ts`; never throw raw `Error` from a handler.
- Every new endpoint gets a contract test in `tests/api/`.

Glob details that matter in practice. Brace expansion works (src/**/*.{ts,tsx}), but every brace group multiplies the pattern count. A rule's whole paths list shares one budget of 1,000 expanded patterns and 4 MiB. A pattern over budget is used unexpanded, and its literal braces then match nothing. A stray [ starts a bracket expression, so photos [2024/** matches nothing; escape it as \[. If the YAML doesn't parse, the rule loads as if it had no paths. A typo therefore turns a scoped rule into an always-on one. claude --debug shows the parse error.

Sharing rules across repositories. You can symlink a shared directory into .claude/rules/. A link whose target is outside the working directory is treated like an external import: you approve it once per project, and after that only the linked rules without paths load. Links to network paths (UNC, /net) aren't followed. For personal cross-project rules, ~/.claude/rules/ avoids the approval entirely.

Pitfall: scoped rules don't survive compactionPath-scoped rules and nested CLAUDE.md files enter message history when their trigger file is touched, so compaction summarizes them away with everything else. They come back only when Claude touches a matching file again. The docs' fix: "If a rule must persist across compaction, drop the paths: frontmatter or move it to the project-root CLAUDE.md." (context-window)

Two version notes. Excluding project from --setting-sources skips project rules; before v2.1.211, on-demand rules loaded anyway. Before v2.1.217, a paths value with many brace groups could stall the CLI at startup.

Scoping

Scoping answers one question: for the file Claude is touching right now, which instructions are in context? The answer is additive, not override. "All discovered files are concatenated into context rather than overriding each other" (memory). Precedence therefore means order, and later text is read last. When files conflict, Claude reconciles them with judgment. That's why the writing guidance says to keep levels consistent rather than rely on one to win.

LevelPathLoads
Managed policymacOS /Library/Application Support/ClaudeCode/CLAUDE.md, Linux/WSL /etc/claude-code/CLAUDE.md, Windows C:\Program Files\ClaudeCode\CLAUDE.md, or the managed claudeMd keyFirst; can't be excluded
User~/.claude/CLAUDE.md and ~/.claude/rules/Launch, every project
Ancestors and cwdCLAUDE.md, .claude/CLAUDE.md, then CLAUDE.local.md in each directory, root firstLaunch
SubdirectoriesSame files below the cwdOn demand, when Claude reads, writes or edits a file there
Added directoriesCLAUDE.md, rules and CLAUDE.local.md in --add-dir dirsOnly with CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1

In a monorepo, the other teams' CLAUDE.md files are noise. Exclude them per machine with claudeMdExcludes, which takes globs matched against absolute paths. Arrays merge across settings layers, and managed files can't be excluded. Put it in .claude/settings.local.json so the exclusion stays yours:

{
  "claudeMdExcludes": [
    "**/apps/payments/CLAUDE.md",
    "**/apps/payments/.claude/rules/**"
  ]
}
A monorepo with root, package and personal files, launched from ~/work/acme. Pick the file Claude touches and the toggles, and the list shows what's in context, in order. It also shows when each file arrived and whether it comes back after compaction. Each column is a directory, outermost on the left: lit cards are in context and numbered in load order, and the touched file sits under its package.

Delivery and cost. "CLAUDE.md content is delivered as a user message after the system prompt, not as part of the system prompt itself." Claude treats it "as context, not enforced configuration". A CLAUDE.md that loads at launch arrives whole up to 4 MiB (a larger one is skipped). A subdirectory CLAUDE.md or a rules file that loads on demand has a smaller per-file limit (40,000 characters on a 200K context window): over it, Claude receives only the start, with a note to read the rest (memory). The target is under 200 lines per file. Block-level HTML comments (<!-- … -->) are stripped before injection, which makes them a free place for maintainer notes. @path imports resolve relative to the importing file, up to four hops deep. Imports organize a file, but "don't reduce its context cost, because imported files load together with the CLAUDE.md that imports them."

Why a CLAUDE.md edit mid-session seems ignored

Claude Code builds the prefix of each request (system prompt, tools, instruction files) so that prompt caching can reuse it. Rewriting CLAUDE.md mid-session would invalidate that cached prefix on the next turn. So Claude Code doesn't re-read it: edits apply after /clear, /compact or a restart (prompt-caching). The trade is deliberate, cheap turns over live updates. Practical consequences:

  • When you tune CLAUDE.md, test the change in a fresh session. A long session tells you nothing about the new text.
  • After compaction, the project-root CLAUDE.md and unscoped rules are re-read from disk. Your edit lands then, possibly mid-task.
  • Nested CLAUDE.md files and path-scoped rules are different: "Editing one yourself before it loads does take effect." Once loaded, the content is part of history, and later edits don't change it retroactively.
  • An @-mention of a file also pulls in CLAUDE.md files from that file's directory and its parents. Referencing a deep file is one way to bring in its package's instructions on purpose.

To audit what loaded and why, combine /context (its "Memory files" list) with an InstructionsLoaded hook that logs load_reason. The Debug your configuration page walks through the full checklist.

Shared Conventions

A team convention is only as strong as the mechanism that carries it. Instruction files are advisory by design. The docs say so twice: CLAUDE.md is "context, not enforced configuration. To block an action regardless of what Claude decides, use a PreToolUse hook instead." Shared conventions therefore need placement decisions, not just good prose. The ladder below is the mental model: move a convention up a rung each time a lower rung has failed it.

The lower rungs are cheap and flexible but advisory. The upper rungs are deterministic and cost nothing in context, but they can't use judgment. Hooks are deterministic but defense in depth. Deny rules bind Claude's tool calls. The sandbox (and a container) is the OS-level boundary. Text is not. Hover a mechanism for what it binds. The context-cost bars under the scale are qualitative, not to scale.

What to commit. ~/.claude doesn't travel to teammates or cloud sessions, so team conventions live in the repo. That means CLAUDE.md, .claude/rules/, .claude/skills/, .claude/agents/, .mcp.json, and the hooks and permissions in .claude/settings.json. Personal preferences go in CLAUDE.local.md or ~/.claude/. Organization rules split the same way. The memory docs keep a table: block tools and paths with managed permissions.deny, enforce isolation with managed sandbox.enabled, and use the managed CLAUDE.md for style, compliance reminders and behavioral guidance.

How to write them so they work on current models (best practices):

  • Make each line concrete and checkable: "Use pnpm, not npm" beats "follow our package conventions".
  • Prune with the docs' test: "Could it find this by reading the code?" and "Would it actually go and look?" If both are yes, leave it out.
  • Skip the emphasis. All-caps IMPORTANT is outdated advice: current models "follow a plainly worded line, and piling on emphasis mostly makes Claude over-apply the rule." A rule that can't bend belongs in managed settings or a hook.
  • Point to documentation instead of @-importing it, so it isn't paid for at launch.
  • Audit periodically with /doctor prompt-audit [path] (v2.1.283+). It covers CLAUDE.md, CLAUDE.local.md, AGENTS.md, rules, skills, commands, subagents and output styles, and flags patterns written for older models.

The features overview gives a trigger for each extension. Claude gets a convention wrong twice → CLAUDE.md. You paste the same playbook a third time → a skill. You keep copying data from a browser tab → an MCP server. A side task floods the conversation → a subagent. Something must happen every time → a hook. A second repository needs the same setup → a plugin. The decision tool below encodes those triggers, adds the "must it draw UI?" question that leads to mods, and shows each choice's context cost.

Pick a scenario to preset the answers, or answer the questions yourself. The need rolls past the slots in the order drawn and drops into the first one it fits. The recommendation follows the features-overview triggers and its advice to put rules that must hold every time in hooks, so deterministic needs beat everything (a UI part goes in a mod alongside). Packaging is a layer on top of whatever you chose.

Exercise: split a bloated CLAUDE.md

Pick a repository whose CLAUDE.md is over 150 lines (or concatenate two). Run /context and note the Memory files size. Then sort every section into one of five places: stays in CLAUDE.md (needed every session), a path-scoped rule (needed for some files), a skill (a procedure or reference needed sometimes), a hook or deny rule (must happen every time), or delete (Claude does it right anyway). Apply the split, start a fresh session and re-run /context. Finally, ask Claude to edit a file covered by one of your new rules, and confirm the rule appears in the Memory files list only after that.

Show a reference solution

A typical 220-line file splits roughly like this. About 60 lines stay: build and test commands, repo map, three or four non-obvious conventions, and the Compact Instructions section. Two or three path-scoped rules take about 70 lines (API, frontend, migrations). Two skills (/release and a schema-reference background skill) take about 60. "Never commit .env" and "run the formatter" become a Read(./.env)/Edit(./.env) deny rule and a PostToolUse formatter hook. About 30 lines of "write clean code" boilerplate are deleted. Expect the Memory files line to drop by more than half. The scoped rule appears after the first Read of a matching file, which proves on-demand loading. If it appeared at launch, check its YAML: a parse error makes it unscoped.

Key takeaways

  • Instruction files concatenate root-first. "Precedence" is order, not override, so keep levels consistent.
  • AGENTS.md (v2.1.277+) loads only when no CLAUDE.md, .claude/CLAUDE.md or CLAUDE.local.md counts. @AGENTS.md at the top of CLAUDE.md works everywhere.
  • Path-scoped rules load on file touch and are summarized away by compaction. Rules that must persist go unscoped or in the root CLAUDE.md.
  • Mid-session edits apply after /clear, /compact or a restart, so test instruction changes in a fresh session.
  • Text is advisory. Conventions that must hold become hooks, deny rules or sandbox settings.

MCP

MCP is how Claude Code reaches anything outside your repository and shell: issue trackers, databases, design tools, internal APIs. This topic is Claude Code's side of the wire: how to add and scope servers, how they authenticate, why their tools cost almost nothing until used, how to build one, and how to keep one from becoming the weakest link.

Each configured server gets its own client inside Claude Code. Stdio servers are child processes; HTTP servers are remote endpoints. Tool search keeps only names and server instructions in context until Claude asks for a schema. Every server runs outside Claude Code's sandbox, but your permission rules still gate each tool call. Hover a client, a process or the network line; the server names and the simplified pstree output are illustrative.

claude mcp add

An MCP server becomes available to Claude once Claude Code knows how to start it (stdio) or where to reach it (HTTP). claude mcp add writes that configuration. It "saves the configuration without validating credentials", so a bad token shows up only later as a failed connection. Always follow an add with claude mcp list or /mcp (mcp docs).

# Remote server over Streamable HTTP (the recommended transport)
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp

# Local stdio server: everything after -- is the server's own command line
claude mcp add --transport stdio airtable --env AIRTABLE_API_KEY="$AIRTABLE_API_KEY" \
  -- npx -y airtable-mcp-server

# From a JSON entry (the object that sits inside "mcpServers"); the only CLI way to add a WebSocket server
claude mcp add-json events '{"type":"ws","url":"wss://events.example.com/mcp"}'

claude mcp list            # health per server: ✔ Connected, ! Needs authentication, ✘ Failed to connect …
claude mcp get sentry      # one server's details, including whether OAuth credentials are configured
claude mcp remove sentry   # also deletes stored OAuth tokens and the client registration

Transports. Streamable HTTP (--transport http; JSON "type": "http" or the alias "streamable-http") is the remote default. SSE "is deprecated": since v2.1.265, adding an SSE-only endpoint with --transport http falls back to SSE automatically. With stdio, Claude Code spawns your command. The -- separates Claude's options (--transport, --env, --scope) from the server's command line, which is passed through untouched. WebSocket servers exist ("type": "ws"), but --transport doesn't accept ws, and WebSocket supports neither OAuth nor the flag. Use HTTP unless the server must push events.

Pitfall: flag order--env and --header each accept several values. "If the server name comes directly after --env, the CLI reads the name as another pair and rejects it" (Invalid environment variable format: <name>). Write the options that take one value (--transport, --scope) first, then the name, then --env pairs, then -- and the server command: claude mcp add --transport stdio --scope project db --env 'PGPASS=${PGPASS}' -- npx -y @bytebase/dbhub. For the same reason, write --header after the URL, as the docs' examples do: claude mcp add --transport http github https://api.githubcopilot.com/mcp/ --header 'Authorization: Bearer ${GITHUB_PAT}'. Single quotes keep your shell from expanding ${VAR}, so the file stores the reference rather than your secret.

Names and tool names. Server names may contain only letters, numbers, hyphens and underscores. workspace, claude-in-chrome, computer-use, Claude Preview and Claude Browser are reserved. Claude sees each tool as mcp__<server>__<tool>, with characters outside A-Z a-z 0-9 _ - turned into _. Those are the names you write in permission rules and hook matchers.

Inside the session, /mcp shows status, sign-in, per-server toggles and the tool list. /mcp reconnect <server> retries one server, and /mcp reconnect all retries every failed one (interactive terminal needs v2.1.284+). /mcp enable|disable <server> toggles a server without deleting its config. Claude Code also sets CLAUDE_PROJECT_DIR in a stdio server's environment, so the server can resolve project paths. It answers the MCP roots/list request with the launch directory plus every --add-dir directory.

Build an add command and see where it writes and what it writes. Warnings come from documented behavior: naming rules, SSE deprecation, WebSocket via add-json, secrets in committed files, and the project-scope approval prompt. The grid is scope as audience × reach: click a cell (or use the Scope menu) and the command's write lands there.
Outdated advice you'll still see--mcp-debug is gone; use --debug or --debug-file. A JSON entry with a url but no type is read as stdio and rejected with MCP server "<name>" has a "url" but no "type". A "type": "sdk" entry in .mcp.json is skipped, because only an SDK host application can register in-process servers (see Agents 2).

Scopes and .mcp.json

Every server definition lives in one of three MCP scopes. The scope decides which projects load it and whether your team gets it:

ScopeLoads inSharedStored in
local (default)current project onlyno~/.claude.json, under projects["/path/to/project"].mcpServers
projectcurrent project onlyyes, via git.mcp.json at the project root
userall your projectsno~/.claude.json (top level)

Note the naming trap: MCP "local scope" lives in ~/.claude.json, not in .claude/settings.local.json. Precedence for a server defined in several places, highest first: the organization's managedMcpServers (v2.1.259+), then local, project, user, plugin-provided servers, and claude.ai connectors. "The entire server entry from that source is used; fields are not merged across scopes." The three scopes match duplicates by name. Plugins and connectors match by endpoint, so a plugin server pointing at the same URL as your user-scope server is a duplicate.

{
  "mcpServers": {
    "issues": {
      "type": "http",
      "url": "${ISSUES_MCP_URL:-https://mcp.example.com/mcp}",
      "headers": { "Authorization": "Bearer ${ISSUES_TOKEN}" }
    },
    "db-readonly": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@bytebase/dbhub", "--dsn", "${READONLY_DSN}"],
      "env": {}
    }
  }
}

.mcp.json expands ${VAR} and ${VAR:-default} in command, args, env, url and headers. A shared file can therefore carry the shape while each developer supplies the secret. An unset variable with no default stays as literal ${VAR} text, and claude mcp list shows a warning. One trap: credential variables such as ANTHROPIC_AUTH_TOKEN read as empty in a remote server's url and headers, even with a :-default, so Bearer ${ANTHROPIC_AUTH_TOKEN} gives a 401.

Approval. "For security reasons, Claude Code prompts for approval in interactive sessions before using project-scoped servers from .mcp.json files." Until you answer, the server shows ⏸ Pending approval (run `claude` to approve). claude mcp reset-project-choices resets your answers. A cloned repository can't approve its own servers: a committed enableAllProjectMcpServers or enabledMcpjsonServers is ignored in an untrusted folder. The crucial exception is non-interactive runs. In claude -p, Agent SDK and cloud sessions, Claude Code "can't show that prompt: it loads project-scoped servers without asking". There are three ways to keep a server out:

  • disabledMcpjsonServers rejects it by name in every permission mode, and claude mcp get then shows ✘ Rejected.
  • --setting-sources (SDK: settingSources) without project excludes project settings and .mcp.json.
  • --strict-mcp-config --mcp-config ./servers.json uses only the servers you pass.
No field merging: when issues is defined at several scopes, "The entire server entry from that source is used; fields are not merged across scopes" (MCP scopes). The winning card lifts and is used whole, and the stamp under the gap stops a lower card's url, headers or env from carrying over. Define the server at several scopes, then vary the session type, workspace trust and approval state: the resolver applies the documented precedence, the by-endpoint matching for plugins and connectors, and the .mcp.json approval rules. The headers on the cards are illustrative.
Practical tipdisabledMcpServers/enabledMcpServers (the /mcp per-project toggles) "are unrelated to enabledMcpjsonServers and disabledMcpjsonServers." The first pair switches a configured server off for this project (⊘ Disabled for this project). The second pair answers the .mcp.json approval question.

OAuth

Most hosted MCP servers authenticate with OAuth 2.0, and Claude Code acts as the OAuth client. You add the server without credentials. The first connection returns 401 Unauthorized (or 403), the server shows ! Needs authentication, and you complete sign-in in a browser from /mcp, or from your shell with claude mcp login <name>. Discovery follows RFC 9728 (/.well-known/oauth-protected-resource) and then RFC 8414 (/.well-known/oauth-authorization-server). Claude Code registers itself through Dynamic Client Registration, or a Client ID Metadata Document where the server supports one, unless you supply credentials.

# Server pre-registered a redirect URI http://localhost:8080/callback
claude mcp add --transport http --callback-port 8080 my-server https://mcp.example.com/mcp

# No dynamic registration: bring your own client (secret prompted, masked)
claude mcp add --transport http --client-id my-app-id --client-secret --callback-port 8080 \
  my-server https://mcp.example.com/mcp
#   non-interactive: MCP_CLIENT_SECRET=... claude mcp add ... --client-secret ...

claude mcp login my-server              # opens a browser; over SSH it prints the URL (use ssh -t)
claude mcp login my-server --no-browser # always use the paste-the-redirect flow
claude mcp logout my-server

Least privilege. Pin scopes in the server entry with oauth.scopes, a space-separated string. It takes precedence over discovered scopes, and offline_access is appended when advertised so tokens can refresh. A later 403 insufficient_scope names the missing scope. Add it to the pinned list and re-authenticate, or the new token will lack it again.

{ "mcpServers": { "slack": {
  "type": "http", "url": "https://mcp.slack.com/mcp",
  "oauth": { "scopes": "channels:read chat:write search:read" }
} } }
From claude mcp add to a refreshed token. Watch which party talks to which, and where claude -p can't follow. Each step adds a numbered arrow and earlier ones stay, so the whole handshake builds up; turn on the headless view to see the fence close around the browser.

Not OAuth? For Kerberos, short-lived tokens or internal SSO, headersHelper runs a shell command at connection time and merges the headers it prints. It gets 10 seconds, re-runs on every connection and is never cached. For project and local servers it runs "only after you accept the workspace trust dialog". When its output includes Authorization, Claude Code doesn't fall back to OAuth.

Pitfall: headless runs can't sign in"A claude -p or Agent SDK run has no /mcp panel, so Claude Code can't run the OAuth flow there." Sign in once interactively (or with claude mcp login) on the machine that runs the job. With tool search on, Claude is told the server's tools are unavailable until you authorize. On the v2 MCP runtime, Claude Code also refuses to send credentials to a plain http:// token endpoint that isn't localhost.

Resources and Prompts

Tools are only one of the three server primitives. Resources are content the user attaches. Type @ and resources from connected servers appear next to files in autocomplete. The form is @server:protocol://resource/path, and a referenced resource is fetched and attached to your prompt. When a server supports resources, Claude Code also gives Claude tools to list and read them. Prompts are server-supplied templates that become commands: listed as /servername:promptname (MCP), also runnable as /mcp__servername__promptname. Arguments are space-separated, one token each.

userCompare @postgres:schema://users with @docs:file://database/user-model and list mismatches.
attachmentspostgres:schema://users (table definition) · docs:file://database/user-model (markdown)
assistantThree mismatches: the doc lists email_verified as boolean (the table has a timestamp)…
user/mcp__github__pr_review 456
promptThe github server's pr_review prompt, rendered with argument 456, is injected into the conversation.

Elicitation runs the other way: a server asks you for structured input mid-task. Claude Code shows a form dialog (form mode) or offers to open a link (URL mode, for sign-in-style flows). The Elicitation hook can answer automatically, for example by filling a known tenant ID in CI. On protocol revision 2026-07-28 connections, Claude Code declares elicitation: {form: {}, url: {}}. Two smaller notes. MCP Apps UI resources (ui:// URIs or text/html;profile=mcp-app) are hidden from @ suggestions because they're pages for a host to render. Prompts from a server named anthropic-skills are hidden because that name is reserved for synced claude.ai skills.

When to use which, as a server author:

  • Use a tool for anything Claude should decide to do, especially with side effects.
  • Use a resource for read-only context a human picks, like an issue, a schema or a runbook. It costs nothing until attached.
  • Use a prompt for a canned workflow a human starts, like "review PR N". In Claude Code a skill often does this better because it can carry scripts, but a prompt travels with the server to every MCP host.

Building a Server

Build a server when the system you need has no CLI, when you want typed and permission-scoped operations instead of free-form shell, or when the same capability must serve several MCP hosts. The official SDKs reached v2 in mid-2026 alongside protocol revision 2026-07-28. In Python, FastMCP became MCPServer. In TypeScript, the server lives in @modelcontextprotocol/server. v1 was @modelcontextprotocol/sdk, whose README promises fixes "for at least six months after the v2 release (2026-07-27)", and serveStdio() / createMcpHandler() replace hand-wired transports. Code you find online is often v1. The shape is the same, but imports and transport wiring changed (build a server, Python v1→v2, TypeScript v2).

# server.py  —  uv add "mcp[cli]"   (MCP Python SDK 2.x; the migration guide imports from mcp.server.mcpserver)
import logging
import subprocess
from mcp.server import MCPServer

log = logging.getLogger(__name__)          # logging writes to stderr: safe for stdio
mcp = MCPServer("release-notes")

@mcp.tool()
def list_releases(limit: int = 5) -> str:
    """List the most recent git tags (newest first) with their dates.
    Use before drafting release notes or a changelog entry."""
    out = subprocess.run(
        ["git", "for-each-ref", "--sort=-creatordate", f"--count={min(limit, 20)}",
         "--format=%(refname:short) %(creatordate:short)", "refs/tags"],
        capture_output=True, text=True, check=False,
    )
    if out.returncode != 0:
        raise RuntimeError(out.stderr.strip() or "git failed")   # becomes an isError result
    log.info("listed %d tags", limit)
    return out.stdout.strip() or "No tags yet."

@mcp.resource("release://{tag}")          # a resource template: type the full URI, e.g. @release-notes:release://v2.4.0
def release(tag: str) -> str:
    """The annotated message of one tag."""
    return subprocess.run(["git", "tag", "-l", "--format=%(contents)", tag],
                          capture_output=True, text=True).stdout

if __name__ == "__main__":
    mcp.run(transport="stdio")             # never print() in a stdio server
uv run mcp dev server.py                                    # MCP Inspector in the browser
claude mcp add release-notes -- uv run --directory "$PWD" server.py
# Same file; only the run() call changes. v2 moved host/port/path options from the constructor to run().
if __name__ == "__main__":
    mcp.run(transport="streamable-http", host="127.0.0.1", port=8000)   # endpoint: http://127.0.0.1:8000/mcp
uv run server.py &
claude mcp add --transport http release-notes http://127.0.0.1:8000/mcp

Binding to loopback keeps the server private. Before exposing it on any other interface, add authorization (the SDKs ship OAuth resource-server helpers) and Host/Origin validation. Never put an unauthenticated tool server on a shared network.

// src/index.ts — npm install @modelcontextprotocol/server zod   (SDK v2, "type": "module")
import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import * as z from "zod/v4";

// serveStdio calls the factory whenever it needs an instance, so return a fresh server each time
function createServer() {
  const server = new McpServer({ name: "release-notes", version: "1.0.0" });
  server.registerTool(
    "list_releases",
    {
      description: "List the most recent git tags (newest first). Use before drafting release notes.",
      inputSchema: z.object({ limit: z.number().int().min(1).max(20).default(5) }),
    },
    async ({ limit }) => ({ content: [{ type: "text", text: await recentTags(limit) }] }),  // recentTags: your helper that runs git
  );
  return server;
}

serveStdio(createServer, { onerror: (err) => console.error("release-notes:", err) });
console.error("release-notes MCP server running on stdio");   // stderr, never stdout
npm run build
npx @modelcontextprotocol/inspector node build/index.js
claude mcp add release-notes -- node "$PWD/build/index.js"
// npm install @modelcontextprotocol/server @modelcontextprotocol/express @modelcontextprotocol/node express
import { createMcpExpressApp } from "@modelcontextprotocol/express";
import { toNodeHandler } from "@modelcontextprotocol/node";
import { createMcpHandler } from "@modelcontextprotocol/server";

const handler = createMcpHandler(createServer);   // factory runs once per request: stateless, scales out
const app = createMcpExpressApp();                // express.json() + Host/Origin validation for localhost binds
const node = toNodeHandler(handler);
app.all("/mcp", (req, res) => void node(req, res, req.body));
app.listen(3000, "127.0.0.1");                    // loopback only until you add auth (requireBearerAuth)
claude mcp add --transport http release-notes http://127.0.0.1:3000/mcp

The rules that break servers in Claude Code:

  • stdout is the protocol channel in stdio. One print() or console.log() puts a line into the stream that no JSON-RPC parser accepts. Log to stderr.
  • Tool results are context. Return summaries, paginate, and keep successful text under 50,000 characters, or Claude Code writes it to a file. For tools that must return large data (a full schema), set _meta["anthropic/maxResultSizeChars"] in the tools/list entry, up to 500,000.
  • Errors are messages for Claude. Return isError: true with an actionable message. Error text over about 11,000 characters is cut to its first and last 5,000.
  • Schemas and names. Claude Code leaves out a tool whose input schema fails the API's checks (valid against JSON Schema draft 2020-12, top-level property names 1–64 characters), so one bad schema doesn't break the whole server. A root-level anyOf/oneOf/allOf is flattened into one object with a hint in the description, so validate argument combinations server-side. A tool whose full name mcp__server__tool is over 128 characters is left out too.
  • Consent tools. For a tool whose approval prompt is the point, such as granting access, set _meta["anthropic/requiresUserInteraction"]: true. It prompts on every call in every mode, allow rules don't skip it, and in dontAsk mode it is denied.
# Smoke-test the server through Claude Code itself, read-only and capped
claude -p "Use the release-notes server to list the last 3 tags." \
  --mcp-config ./mcp.dev.json --strict-mcp-config \
  --allowedTools "mcp__release-notes__list_releases" --permission-mode dontAsk \
  --max-turns 4 --output-format stream-json --verbose \
  | jq -c 'select(.type=="system" and .subtype=="init") | {mcp_servers, mcp_server_errors}'

What you build: lab-docs, a standard-library stdio MCP server over a folder of decision records and runbooks. It has two read-only tools (search_docs, get_doc), resources and a prompt, and a test client that drives it the way Claude Code does, one JSON-RPC line at a time. Run:

cd labs && python3 agents-3/mcp_server/test_client.py        # add -v to see every JSON-RPC line
python3 agents-3/mcp_server/test_client.py --write-config                        # writes agents-3/out/mcp.json
python3 agents-3/mcp_server/test_client.py --real --model haiku --max-budget-usd 0.05   # optional, costs money

Observe: version negotiation, a 2026-era server/discover probe answered with -32601 and the fallback to initialize, protocol errors versus isError: true tool errors, and the stdout-hygiene check. The tools become mcp__lab-docs__search_docs / mcp__lab-docs__get_doc in Claude Code. The client prints the install block.

Open the lab walkthrough

Integration Security

An MCP server is code that runs as you, or a remote service you hand credentials to, and everything it returns enters Claude's context. The docs are blunt. "Verify you trust each server before connecting it. Servers that fetch external content can expose you to prompt injection risk." And Anthropic "doesn't security-audit or manage any MCP server," even for connectors listed in its directory (mcp, security).

Threats to plan for.

  • Malicious or compromised server code. A stdio server is a process with your privileges, outside the sandbox.
  • Remote behavior drift. A remote server can change after you approved it, adding tools or new descriptions.
  • Prompt injection through results. An issue body, web page or ticket can carry instructions.
  • Over-broad credentials. A server holding a write-scoped token can do anything Claude is talked into.
  • Config smuggling. A cloned repo ships a .mcp.json that a headless run connects without asking.

Controls, from the individual to the fleet:

  • Permission rules per tool. Allow read tools narrowly (mcp__github__get_*) and leave write tools on prompt. A deny rule on a tool name removes it from context. An allow glob is honored only after a literal mcp__<server>__ prefix, so "mcp__*" in allow "is skipped and doesn't auto-approve anything". To match MCP parameters, use --disallowedTools, because settings files skip mcp__ rules with parentheses. Hook matchers need regex, as in mcp__github__.*.
  • Least-privilege credentials. Use a read-only database user (the docs' DBHub example says so), oauth.scopes, per-developer ${VAR} tokens instead of shared keys, and nothing secret in committed .mcp.json.
  • Headless hygiene. In repos you didn't write: --strict-mcp-config, --setting-sources user or --bare, plus disabledMcpjsonServers.
  • Organization policy. managed-mcp.json takes exclusive control ("users can't add, modify, or use any other MCP servers"), and { "mcpServers": {} } disables MCP. managedMcpServers (v2.1.259+) provides https servers alongside users' own. allowedMcpServers/deniedMcpServers filter what users configure (managed-mcp).
Pick a server a user tries to add and an organization policy. The evaluator runs the three documented checks in order: merge the lists, check the denylist ("Nothing overrides a denylist match"), then the allowlist with its serverUrl/serverCommand/serverName rules. The server shows its badge at the door: watch a reused name walk in when the guest list holds only serverName entries.
Pitfall: serverName is not a security controlUsers choose labels, so an allowlist entry {"serverName": "github"} admits any server a user names github. That holds only while the allowlist has no serverUrl entries (for remote servers) or no serverCommand entries (for stdio). Enforce with serverUrl wildcards and exact serverCommand argv. Keep in mind that serverCommand doesn't compare env, and "some environment variables change what node loads at startup". Any user can read managed-mcp.json, so it must contain no credentials.

Exercise: add, share and lock down one server

In a scratch repo, add the release-notes server from the building tab (or any stdio server) at project scope, with a secret passed as ${VAR}. Then: (1) start claude and note the approval prompt; (2) run claude mcp list before and after approving; (3) write a permission setup that auto-approves only its read tool and keeps every other tool from that server on prompt; (4) run a headless smoke test that can't load any other server; (5) set disabledMcpjsonServers and confirm claude mcp get shows it rejected.

Show a reference solution
claude mcp add --scope project release-notes --env GH_TOKEN='${GH_TOKEN}' -- uv run --directory "$PWD/server" server.py
cat .mcp.json                     # "env": { "GH_TOKEN": "${GH_TOKEN}" }: no literal secret committed
claude mcp list                   # release-notes: ⏸ Pending approval (run `claude` to approve)
{ "permissions": {
    "allow": ["mcp__release-notes__list_releases"],
    "ask":   ["mcp__release-notes__create_release"]
} }
printf '{"mcpServers":{"release-notes":{"type":"stdio","command":"uv","args":["run","--directory","%s/server","server.py"]}}}' "$PWD" > /tmp/mcp.dev.json
claude -p "List the last 3 tags with the release-notes server" --mcp-config /tmp/mcp.dev.json --strict-mcp-config \
  --allowedTools "mcp__release-notes__list_releases" --permission-mode dontAsk --max-turns 4
echo '{ "disabledMcpjsonServers": ["release-notes"] }' > .claude/settings.local.json
claude mcp get release-notes      # ✘ Rejected (see disabledMcpjsonServers in settings)

Single quotes keep your shell from expanding ${GH_TOKEN}, so the literal reference lands in .mcp.json and each developer's environment supplies the value. Tools you don't allow stay unmatched, so Manual mode prompts for them. Listing a write tool in ask by exact name keeps it on prompt in auto mode too. Don't put mcp__release-notes__* in ask: rules are evaluated deny, then ask, then allow, and "a matching ask rule prompts even when a more specific allow rule also matches", so the glob would prompt for the read tool too. In dontAsk mode, anything not pre-approved is denied rather than prompted, which suits CI. If you merge the disabledMcpjsonServers line into an existing settings.local.json, don't overwrite it as the one-liner does.

Why MCP sits outside the sandbox, and what that means for defense in depth

Claude Code's sandbox isolates the Bash tool's processes (filesystem and network). It doesn't wrap MCP servers, hooks or the file tools. In the sandboxing docs' words, "The sandbox covers shell commands only." A stdio server you add can therefore read ~/.ssh and reach the internet no matter how tight your sandbox.network allowlist is. The layers that do apply to MCP are:

  1. The permission check on each tool call: rules, mode, and the auto-mode classifier.
  2. What the server can do: its own credentials, scopes and deployment, such as running it in a container with no host mounts.
  3. Who may configure servers: approval prompts, workspace trust and managed policy.
  4. What returns to context: output limits, plus your habit of treating results as data.

For a remote server you don't control, layer 2 is the vendor's. That's why scopes and read-only accounts matter more than any client-side setting. Anthropic's engineering post on containment (How we contain Claude) frames egress allowlists as capability grants. A connected MCP server is one too.

Key takeaways

  • claude mcp add --transport http for remote, -- <command> for stdio. Adding doesn't validate, so check claude mcp list.
  • Local scope (default) lives in ~/.claude.json. Same name in several scopes: local, project, user, whole entry, no merge.
  • .mcp.json servers prompt interactively but load without asking in -p, SDK and cloud sessions.
  • OAuth needs an interactive sign-in once; pin oauth.scopes. headersHelper covers non-OAuth schemes after trust.
  • Tool search defers schemas by default, so write server instructions and the first part of descriptions for search.
  • Servers run as you, outside the sandbox. Gate per tool, scope credentials, and enforce fleets with serverUrl/serverCommand policy.

Skills

A skill is a folder of instructions, references and scripts that Claude loads only when it's relevant, or when you type its name. Core 2 covered discovery and invocation. Here you author them: every frontmatter field and what it really does, what each layer costs in context, how scripts keep bulk out of the window, why allowed-tools grants but never restricts, and how to prove a skill helps rather than hoping it does.

SKILL.md Authoring

A skill is <skills-dir>/<name>/SKILL.md: YAML frontmatter followed by Markdown, following the Agent Skills open standard with Claude Code extensions. Skills live in several places. The enterprise copy sits in the managed directory. Personal skills go in ~/.claude/skills/ and project skills in .claude/skills/; nested apps/web/.claude/skills/ skills appear as /apps/web:deploy on a name clash. Plugin skills are namespaced /plugin:skill. When names collide, enterprise beats personal, and personal beats project. A same-named skill from an --add-dir directory outside the project runs under a prefixed name instead, such as /cli:verify for --add-dir ../cli (v2.1.309+; resolve skills that share a name). "Custom commands have been merged into skills". .claude/commands/deploy.md still works and accepts the same fields except name and paths, but new work should be a skill (skills docs).

There are two kinds of content, and choosing one decides most of the frontmatter:

Reference skill

Knowledge Claude applies while it works: API conventions, a schema, a style guide. Let Claude invoke it (the default). Consider user-invocable: false if a human should never type it, and paths to activate it only near matching files.

Task skill

A procedure with side effects: deploy, release, migrate, commit. Set disable-model-invocation: true so only you trigger it. Its description also leaves the listing, so it costs nothing until used. Add context: fork if the work is verbose.

The description is the router. Claude matches your request against each skill's description (plus when_to_use). Write it like a search target: what the skill does, then when to use it, in the words a user would actually type. Put the key use case first, because the combined text is truncated at 1,536 characters in the listing.

✗ Weak
description: Helps with releases.

No trigger words, no scope, so it collides with every other release-ish skill.

✓ Strong
description: Draft release notes and the CHANGELOG
  entry for a version from merged PRs since the last
  tag. Use when the user asks for release notes, a
  changelog, or "what changed since vX".

Action, input, output, and the phrases that should trigger it.

The body is a recurring cost. Once invoked, the rendered SKILL.md "enters the conversation as a single message and stays there across later turns". Claude Code doesn't re-read it. So write standing instructions ("Run the tests after every edit") rather than one-time steps, keep it under 500 lines, and put the most important instructions at the top. After compaction only the first 5,000 tokens of each skill come back.

---
name: release-notes
description: Draft release notes and the CHANGELOG entry for a version from merged PRs since the last tag. Use when the user asks for release notes, a changelog, or "what changed since vX".
argument-hint: "[version]"
disable-model-invocation: true
allowed-tools: Bash(git describe *) Bash(gh pr list *) Bash(${CLAUDE_SKILL_DIR}/scripts/classify.py *)
---

# Release notes for $ARGUMENTS

Standing rules for this task:
- Group entries under Added / Changed / Fixed / Security. One line per user-visible change.
- Never invent a PR number; every line cites one from the data below.

## Data (collected before you read this)
- Last tag: !`git describe --tags --abbrev=0 || true`
- Recently merged PRs: !`gh pr list --state merged --limit 50 --json number,title,labels,mergedAt`

## Steps
1. Run `${CLAUDE_SKILL_DIR}/scripts/classify.py` on the PRs merged after the last tag and use its grouping.
2. For wording conventions, read [style.md](style.md) only if a PR title is ambiguous.
3. Write the entry at the top of CHANGELOG.md and show the diff.
Outdated advice.claude/commands/x.md "runs as /project:x" is from before the merge (v2.1.3). It now runs as /x. Live reload watches skill directories, but a brand-new top-level skills directory needs /reload-skills. Synced claude.ai skills live in ~/.claude/skills/synced/ as /anthropic-skills:<name> and never run ! commands on your machine.

Frontmatter

Frontmatter is read "only when the opening --- is the file's first line". "All fields are optional. Only description is recommended." Field names are lowercase-hyphenated except when_to_use, and a name "must match the table exactly, hyphens included: Claude Code ignores a field it doesn't recognize without reporting an error". allowed_tools with an underscore silently does nothing. If the YAML doesn't parse, "the skill still loads with no fields set", so /name works but Claude can't match the description. Booleans accept yes/no/on/off/1/0 from v2.1.218 (only true/false before). The full table, verbatim in meaning (skills: frontmatter reference):

FieldWhat it does (default)
nameCommand name in the / menu (directory name)
descriptionWhat it does and when to use it; Claude matches on it (first non-empty body line if omitted). Key use case first
when_to_useExtra trigger phrases; appended to description and counts toward the 1,536-char cap
argument-hintAutocomplete hint, e.g. [issue-number]
argumentsNamed positional args for $name substitution (string or list)
disable-model-invocationtrue: Claude can't auto-load it; also blocks subagent preloading and session-scoped scheduled tasks (false)
user-invocablefalse: hidden from / menu, only Claude invokes (true)
allowed-toolsTools usable without asking during the invoking turn; clears on your next message
disallowed-toolsTools removed from Claude's pool while the skill is active; clears on next message
modelModel for the rest of the current turn (not saved), or inherit; with context: fork, the fork's model
effortlow…max while active, model permitting
contextfork: run in a forked subagent context
agentSubagent type for context: fork (general-purpose; also Explore, Plan, custom)
backgroundOnly with context: fork; false waits for the result in the invoking turn (true; v2.1.218+)
hooksHooks registered on invocation, kept for the rest of the session
pathsGlobs limiting automatic activation, same format as path-specific rules
shellbash (default) or powershell for ! commands
metadata, license, compatibilityAccepted, not acted on (spec fields; compatibility ≤500 chars)

Portability. Claude Code accepts every field. claude.ai uploads, the Skills API and package_skill.py accept only name, description, license, compatibility, metadata, allowed-tools. Anything else is a hard error: Unexpected key(s) in SKILL.md frontmatter: argument-hint. Body features such as ! injection don't work outside Claude Code. If a skill must travel, keep to the six fields and put Claude Code-only behavior in a plugin or a separate wrapper skill.

Paste or edit a SKILL.md, or load a preset. The linter applies the documented rules: silent unknown fields, the 1,536-character listing cap, fork-only fields, broad grants, side-effect workflows without a guard, the portable subset, and body length. It also previews the listing entry Claude sees, as one line of the menu between two illustrative neighbours, with numbered pins for the notes below and the 1,536-character cut where it falls.

Progressive Loading

Progressive loading is why you can install fifty skills without paying for fifty bodies. Each layer loads only when the previous one says it's needed:

  1. Listing (every turn). Each model-invocable skill's name and description. The listing budget "scales at 1% of the model's context window" (fallback 8,000 characters), and each entry is capped at 1,536 characters. On overflow Claude Code keeps every name but "drops descriptions starting with the skills you invoke least". A dropped description means Claude is less likely to pick that skill. disable-model-invocation: true skills aren't listed at all.
  2. Body (on invocation). The rendered SKILL.md, once, persisting across turns. Re-invoking with identical rendered content adds only a short note that the skill is already loaded. Different arguments or new ! output append the full content again.
  3. References (on read). Files the body points to, loaded only if Claude opens them.
  4. Scripts (on run). Executed, so only their output enters context. The source never does.

After compaction, the most recent invocation of each skill is re-attached with its first 5,000 tokens, within a combined 25,000-token budget filled newest first. The listing is rebuilt and re-injected (v2.1.304+). Subagents work differently: skills named in a subagent's skills: field are preloaded in full at startup.

Toy model. Token sizes are illustrative, and the listing budget converts 1% of the window to characters at about 2.5 characters per token, the models overview's rough figure. Set up your skill library, then step through a session that invokes a task skill, reads a reference, runs a script and compacts. The playhead follows the stepper and the layer that just changed is highlighted; hover a step for its layers.
Listing math, persistence and subagent preloading

Budget arithmetic. The listing is capped at 1% of the context window, and the docs call it a character budget (SLASH_COMMAND_TOOL_CHAR_BUDGET overrides it as a fixed character count, fallback 8,000). The skills docs give no token-to-character conversion. Anthropic's models overview gives a rough one, "1M tokens is roughly 555k words or 2.5M Unicode characters on the current tokenizer" (models overview). At about 2.5 characters per token, as the toy widget assumes, 1% of a 1M window is roughly 25,000 characters and 1% of 200K roughly 5,000, below the documented 8,000-character fallback. Each entry costs its name plus up to 1,536 characters of description and when_to_use. Under that assumption, forty skills with 300-character descriptions (about 13,000 characters with names) fit on 1M. The same forty with 1,200-character descriptions on a 200K window would overflow, and the least-invoked skills lose their descriptions first. Claude can still invoke them by name, but rarely picks them on its own. Moving to a smaller-window model can therefore quietly change which skills trigger. /context shows the post-budget size of the Skills row, and --debug logs an overflow warning.

Why bodies persist and aren't re-read. An invoked body is part of the conversation, so it rides the prompt cache like any other message. Re-reading it each turn would add a fresh copy (cost) or mutate history (cache break). The design accepts staleness, since edits to SKILL.md apply on the next invocation, in exchange for cheap turns. Two consequences: write standing instructions, and front-load what matters. On compaction, only the most recent invocation of each skill comes back, capped at 5,000 tokens each and 25,000 total, newest first. Ten heavy skills in one session means the oldest come back empty.

Subagents invert the model. A subagent's skills: field preloads full bodies at startup instead of listing descriptions. Per the sub-agents docs, the first 32 names are preloaded in full. Subagents can still discover and invoke other skills through the Skill tool. disable-model-invocation: true blocks preloading as well, so a side-effect skill can't be smuggled into an autonomous worker by name. A skill with context: fork is the reverse direction: the skill body becomes the prompt of a forked subagent, running agent (default general-purpose), with model setting the fork's model.

Practical tip: manage the listing like a budget/context shows the Skills row after the budget is applied (since v2.1.196). /doctor estimates the listing's cost and its biggest contributors. /skill-doctor (v2.1.252+) shows never-invoked skills and their cost in the /plugin Stats tab. Levers: skillOverrides to "name-only" for low-priority entries, skillListingBudgetFraction (e.g. 0.02), skillListingMaxDescChars, SLASH_COMMAND_TOOL_CHAR_BUDGET (fixed characters), or trimming descriptions at the source.

Scripts and References

A skill directory can hold anything. The docs' canonical layout separates what is read from what is run:

release-notes/
├── SKILL.md          # required: overview + navigation (keep < 500 lines)
├── style.md          # reference: loaded only when SKILL.md tells Claude to read it
├── examples.md       # reference
└── scripts/
    └── classify.py   # executed, not loaded: only stdout enters context
A 900-line classification script costs context only for what it prints. The same logic written as prose instructions would be loaded, kept across turns, and followed less reliably than code. Files are drawn to scale on the shelf and each casts its footprint on the context floor; hover a file. Sizes are illustrative.

Point to files explicitly. Link references from SKILL.md with a sentence saying what each contains and when to open it. Claude decides whether to read them from that sentence. Reference scripts through ${CLAUDE_SKILL_DIR}, the skill's own directory, because the session's working directory moves when Claude runs cd. That variable and ${CLAUDE_PROJECT_DIR} are substituted in the body and in allowed-tools Bash rules, so you can pre-approve exactly your script: allowed-tools: Bash(${CLAUDE_SKILL_DIR}/scripts/classify.py *). Other substitutions: $ARGUMENTS, $ARGUMENTS[N]/$N, $name (from arguments), ${CLAUDE_SESSION_ID}, ${CLAUDE_EFFORT}, and the plugin variables in plugin skills.

Dynamic context injection runs commands before Claude sees the skill. Use !`command` at the start of a line or after whitespace (not in KEY=!`cmd`), or a fenced block opened with ```! for several lines. The output replaces the placeholder as plain text and is never re-scanned. Facts to design around:

  • A failing command "aborts the entire skill invocation", and Claude never sees the skill. Exit 1 from search and comparison commands (grep, diff, git diff…) counts as normal. Append || true to anything else that can exit non-zero.
  • Injected commands never prompt. They're checked against your permission rules, and outside auto mode anything short of allow aborts with Shell command permission check failed for pattern "…". Pre-approve them in allowed-tools.
  • They use the Bash tool's 2-minute timeout and output limits. Stderr is merged into the injected text under the default bash shell.
  • "disableSkillShellExecution": true replaces each command with [shell command execution disabled by policy] for user, project, plugin and add-dir skills. Bundled and managed skills are unaffected. It's most useful as a managed setting.
Pitfall: forked background skills and checkpointsA skill with context: fork runs in a forked subagent, in the background by default (the background field, v2.1.218+, lets you wait instead). It applies its edits "outside your session's checkpoints": /rewind then restores only the files Claude had already edited in your conversation, and the skill's edits to other files stay. Commit first, or set background: false for skills that edit.

Exercise: move logic from prose to a script

Take a skill (or CLAUDE.md section) that tells Claude to "check that every migration has a down step and a matching test". Rewrite it as scripts/check_migrations.py, which prints one line per violation and exits 0. Have SKILL.md run it through ${CLAUDE_SKILL_DIR} and pre-approve exactly that script in allowed-tools. Compare /context after invoking the old and new versions on the same repo.

Show a reference solution
---
name: check-migrations
description: Verify database migrations have down steps and tests. Use before merging any change under db/migrations/.
allowed-tools: Bash(${CLAUDE_SKILL_DIR}/scripts/check_migrations.py *)
---
Run `${CLAUDE_SKILL_DIR}/scripts/check_migrations.py db/migrations` and fix every line it prints.
If it prints nothing, say so and stop.

The script prints a short list instead of Claude reading every migration file. The skill body shrinks to a few lines and stays cheap across turns. A deterministic check becomes reproducible. Exiting 0 even when it finds problems matters if you call it from a ! injection, because a non-zero exit would abort the invocation.

allowed-tools

This is the most misunderstood field. allowed-tools "grants permission for the listed tools during the turn that invokes the skill, so Claude can use them without prompting you for approval. The grant clears when you send your next message." And: "It does not restrict which tools are available: every tool remains callable." Read it as pre-approval, not a sandbox. To remove tools, use disallowed-tools, which also clears on your next message. To restrict across all skills, use deny rules (skills: pre-approve tools).

Precedence. "Deny and ask rules still override allowed-tools." For a session-long pre-approval, add allow rules to settings instead. The value accepts a space- or comma-separated string, or a YAML list, using permission-rule syntax: Bash(git add *), Read, mcp__github__get_*.

One skill, one permission setup, one tool call. The decision follows the documented order: removed by disallowed-tools → deny rule → ask rule → the skill's grant (invoking turn only, ignored under allowManagedPermissionRulesOnly) → settings allow → built-in read-only command → prompt. Simplified to Manual mode. The checks are bands down the drawing and the turns run across it: the call drops through at its turn and stops at the first band that decides, and the shaded window is the skill's grant.
Security pitfall: not gated by workspace trust"Workspace trust doesn't gate this field. Claude Code applies a project skill's allowed-tools even in a -p run in a folder you've never trusted. A skill can grant itself broad tool access, so review the allowed-tools of skills checked into a repository before you run Claude Code there." An organization can neutralize it with managed allowManagedPermissionRulesOnly (v2.1.282+). Affected skills then go through managed rules and normal prompts, and /status lists which grants were ignored.

Gating skills themselves. Use permission rules on the Skill tool. Skill in deny disables all skills. Skill(commit) matches exactly, and Skill(review-pr *) matches by prefix with arguments. A deny on an unqualified name also blocks nested variants (apps/web:deploy), and a deny on an alias such as Skill(review) blocks /code-review. user-invocable: false hides a skill from you but Claude can still invoke it. Only disable-model-invocation: true keeps Claude away.

Testing Skills

"Seeing a skill trigger tells you Claude found it, not that it did what you intended." A skill test measures two separate things: triggering (does Claude invoke it on the prompts it should, and not on others?) and outcome (is the result better than without it?). Both need a baseline. Run a few realistic prompts each in a fresh session, once with the skill and once without, and compare. "A fresh session matters because leftover context from authoring the skill will mask gaps in the written instructions." (skills: evaluate and iterate)

  • Turning it off for the baseline: for personal or project skills, set "skillOverrides": {"release-notes": "off"}. That has no effect on plugin skills; use claude plugin eval, which runs a no-plugin arm automatically.
  • Static checks first: claude plugin validate .claude/skills (v2.1.233+) finds SKILL.md files whose frontmatter doesn't parse. claude --debug shows parse errors and listing-budget warnings. Ask "What skills are available?" to confirm listing.
  • Headless trigger check: run each prompt through claude -p --output-format stream-json --verbose and look for a tool_use of the Skill tool naming your skill.

The eval and trigger examples below assume a model-invocable variant of release-notes, without the disable-model-invocation: true used in the authoring example. With that flag set, Claude can't invoke the skill on its own, so a tool_used: Skill grader could never pass.

claude plugin eval (v2.1.269+) is the built-in harness for skills shipped in a plugin. Each case is a directory, and graders are Markdown with frontmatter. tool_used, tool_order, regex and file_exists cost nothing; llm and baseline call a judge model. There are no custom-code graders (plugin evals).

claude plugin eval init --bare first-case     # writes evals/first-case/{prompt.md,graders/criteria.md}
claude plugin eval .                          # runs with-plugin and without-plugin arms, reports Δ
claude plugin eval . --runs 5 --judge-model sonnet --max-cost-usd 3 --json results.json
---
max_turns: 10
allowed_tools: [Read, Glob, Grep, Skill]
---

Write me release notes for 2.4.0. The merged PRs are: #812 "Add SSO login",
#815 "Fix crash on empty cart", #820 "Bump lodash to patch CVE".
---
type: tool_used
tool: Skill
input_match: '"skill"\s*:\s*"(?:[\w-]+:)?release-notes"'
---
---
type: llm
---

PASS if the notes group #812 under Added, #815 under Fixed and #820 under Security, and cite each PR number.
FAIL if any PR is missing, misgrouped, or a PR number is invented.

A tool_used: Skill grader can never pass without the plugin, so in two-arm runs Claude Code reports it but excludes it from the score in both arms (scored: false). That keeps Δ honest. For iterating on a single skill inside a conversation, the skill-creator plugin (/plugin install skill-creator@claude-plugins-official) runs a similar loop. It stores cases in its own evals/evals.json, runs blind A/B comparisons between versions, and tunes descriptions with should-trigger and should-not-trigger prompts. The two formats aren't interchangeable.

What you build: a linter for SKILL.md and command files against the documented rules: frontmatter on line 1, YAML that parses, misspelled (silently ignored) fields, the 1,536-character cap and the 1%-of-window listing budget, invocation control, ! commands without a matching allow rule, and broad allowed-tools. Run:

cd labs && python3 agents-3/skill_lint.py     # good samples must be clean; bad ones match EXPECTED.json
python3 agents-3/skill_lint.py ~/your-repo/.claude/skills --portable --strict

Observe: the late-frontmatter, broken-YAML, typo-field, dead-end (nobody can invoke it) and greedy samples. Note how many listing characters the model-invocable descriptions put in context.

Open the lab walkthrough

Exercise: a trigger matrix for one skill

For one of your skills, write five prompts that should trigger it (phrased as users phrase things, never naming the skill) and five near-misses that shouldn't. Run all ten headless in fresh sessions and record whether the Skill tool fired. Rewrite the description until you get at least 9/10, then run the five positives again with the skill "off" and compare outputs.

Show a reference solution
while IFS= read -r p; do
  hit=$(claude -p "$p" --permission-mode plan --max-turns 3 --output-format stream-json --verbose \
        | jq -r 'select(.type=="assistant") | .message.content[]? | select(.type=="tool_use" and .name=="Skill") | .input.skill' \
        | grep -c 'release-notes' || true)
  printf '%s\t%s\n' "$hit" "$p"
done < prompts.txt

Typical fixes: add the user's vocabulary ("changelog", "what changed since") to the first sentence. Narrow an over-broad description that also fires on "write a blog post about the release". Move edge-case triggers into when_to_use. If outcomes don't beat the baseline, the problem is the body, not the description. Plan mode and a turn cap keep the runs read-only and cheap. They still cost money, so check total_cost_usd in the result events.

Key takeaways

  • The description is the router: action, input, output and trigger phrases, key use case first, under 1,536 characters together with when_to_use.
  • Frontmatter typos fail silently, and malformed YAML loads a skill with no fields. Validate with claude plugin validate and --debug.
  • Layers: listing (every turn, 1%-of-window budget) → body (once, persists) → references (on read) → scripts (output only).
  • allowed-tools pre-approves for the invoking turn and restricts nothing; deny and ask rules win, and it isn't trust-gated.
  • Test triggering and outcome separately, against a fresh-session baseline with the skill off.

Plugins

A plugin is the packaging layer: "a directory of skills, agents, hooks, MCP servers, or other components that Claude Code installs and loads as one unit." Reach for it when a second repository or a second person needs your setup. This topic covers the directory contract, how marketplaces distribute plugins, the install lifecycle, mods (plugins that run JavaScript inside Claude Code), and how versions and dependencies resolve. The plugin docs now live under /docs/en/plugins/*; the legacy URLs still serve the same content.

Plugin Anatomy

A plugin is a directory with an optional manifest and any number of component folders. With no manifest, a --plugin-dir plugin is named after its directory. The rule people break most: "Only plugin.json goes inside .claude-plugin/. Components saved there don't load." (create, components)

Click a file to see its role, the name users see, when it loads, what it costs in context and how it runs. Then switch on common mistakes and watch the validation verdict change. The verdicts are illustrative; run claude plugin validate ./release-kit --strict for the real ones. The plugin is drawn as a toolbox: the lid (.claude-plugin/) holds only the manifest, and each tray is a component folder.

The manifest. plugin.json needs only name: kebab-case, no spaces, and it prefixes every component. Names starting with claude-, anthropic-, anthropics- or cc-plugin-, or exactly claude, claude-code and similar, are reserved. Optional fields include displayName, version, description, author, homepage (must parse as a URL or the plugin fails to load), license, keywords, defaultEnabled (true), dependencies, userConfig, channels, and the component keys. "Every component path in a manifest is relative to the plugin root and must start with ./." Unknown top-level keys are stripped with a validator warning. An unknown key inside a userConfig option, channel, LSP config or monitor is an error, and the plugin doesn't load (manifest reference).

{
  "name": "release-kit",
  "displayName": "Release Kit",
  "version": "1.4.0",
  "description": "Release notes skill, changelog reviewer agent, format hook and a tags MCP server",
  "author": { "name": "Platform Team", "email": "platform@example.com" },
  "license": "MIT",
  "keywords": ["release", "changelog"],
  "mcpServers": {
    "tags": { "command": "${CLAUDE_PLUGIN_ROOT}/bin/tags-mcp", "args": [] }
  },
  "userConfig": {
    "gh_token": { "type": "string", "title": "GitHub token", "description": "Read-only token for PR lookups", "sensitive": true }
  }
}

How component keys combine with default folders. skills adds to the default skills/ scan. commands, agents and outputStyles replace their default folder, and the validator warns Default <folder>/ folder is ignored because the manifest sets "<key>". hooks and mcpServers merge with hooks/hooks.json and .mcp.json.

Behaviors that differ from the same component outside a plugin:

  • Namespacing. Skills become /release-kit:release-notes, agents release-kit:changelog-reviewer, and MCP tools mcp__plugin_release-kit_tags__list_tags.
  • Hooks are not namespaced. A hook in both your settings and hooks/hooks.json "runs twice". Plugin hooks fire from session load, not when a skill is used.
  • Plugin subagents ignore permissionMode, hooks, mcpServers and initialPrompt "for security reasons". Copy the agent into .claude/agents/ if you need them.
  • Root files. A settings.json at the plugin root applies only agent and subagentStatusLine. A root CLAUDE.md isn't loaded as context.
  • Path variables. ${CLAUDE_PLUGIN_ROOT} changes with every version, so "Don't write state there". Use ${CLAUDE_PLUGIN_DATA}, which survives updates. Neither variable is in the Bash tool's environment.
  • Executables. Files in bin/ are on the Bash tool's PATH while the plugin is enabled. claude.ai and Cowork refuse plugins with a top-level bin/.

The dev loop: claude --plugin-dir ./release-kit (repeatable; a directory or .zip) loads it for one session as release-kit@inline. /reload-plugins applies edits. claude plugin validate ./release-kit --strict fails on warnings too. claude plugin init my-tool scaffolds a plugin under ~/.claude/skills/ that loads as my-tool@skills-dir. To convert an existing .claude/ setup, copy its skills/, agents/ and commands/ folders into the plugin, and move the hooks object into hooks/hooks.json under a top-level "hooks" key.

Marketplaces

"A plugin marketplace is a directory or repository with a .claude-plugin/marketplace.json file that lists your plugins and where to fetch each one". "It's a catalog, not a hosted store." Three fields are required: name, owner (with name) and plugins. Each entry needs its own name and source (create a marketplace).

{
  "name": "acme-tools",
  "owner": { "name": "Acme Platform", "email": "platform@acme.example" },
  "description": "Acme's internal Claude Code plugins",
  "plugins": [
    { "name": "release-kit", "source": "./plugins/release-kit", "description": "Release notes and changelog review" },
    { "name": "db-tools", "source": { "source": "github", "repo": "acme/db-tools", "ref": "v2" } },
    { "name": "sec-review", "source": { "source": "git-subdir", "url": "acme/monorepo", "path": "tools/sec-review" } }
  ]
}
The marketplace root is the directory that contains .claude-plugin/, and relative sources resolve from it. A relative path only works when Claude Code has the marketplace's files, so it fails for a hosted url marketplace. Switch where the catalog was added from and hover a pot for how its source is fetched. Plugin names and versions are illustrative.

Plugin sources: a relative path (must start with ./), github (repo, ref, sha), url (any git host), git-subdir (sparse checkout of a monorepo path), npm (install scripts never run), archive (HTTPS zip with sha256, v2.1.224+) and command (a command that prints a directory, v2.1.229+). When both ref and sha are set, Claude Code checks out the 40-character sha. strict (default true) makes the plugin's own plugin.json authoritative, and the entry's component fields are appended. With strict: false, an entry that also declares components conflicts with a manifest that does: has conflicting manifests.

The two failure causes the docs name: "a relative path written from the wrong directory, or … an entry name that differs from the name in the plugin's plugin.json". The entry name is the install ID and the enabledPlugins key; the manifest name prefixes the components. "Keep the entry name and the manifest name the same." The validator also ignores typos quietly: "Claude Code ignores an unknown top-level key or plugin-entry key rather than rejecting it, so a typo loads silently."

Trust tiers by name. Anthropic's official names (claude-plugins-official, claude-code-plugins, …) and community names (claude-community, …) are accepted only from github.com/anthropics/. Anywhere else you get Marketplace is registered from an untrusted source. claude-plugins-official is added automatically on your first interactive terminal session. But "A marketplace's name tells you who publishes the catalog, not what each plugin in it does." Organizations control the list with managed strictKnownMarketplaces (an allowlist; [] "locks every marketplace source out, including the official marketplace"), blockedMarketplaces ("checked first") and extraKnownMarketplaces, covered in Autonomy 2.

Installing and Managing

# In a session: opens the details pane (Will install, Last updated, Context cost) instead of installing at once
/plugin install commit-commands@claude-plugins-official
/plugin marketplace add acme/claude-plugins#v3     # GitHub owner/repo[#ref], git URL, ./local/path, or https://…/marketplace.json
/plugin install release-kit --marketplace acme/claude-plugins   # add + install in one step (v2.1.275+); plugin name without @marketplace

# From the shell (scriptable; default scope is user)
claude plugin marketplace add ./my-marketplace
claude plugin install release-kit@acme-tools --scope project   # writes enabledPlugins to .claude/settings.json
#   one-step shell form (v2.1.292+): claude plugin install release-kit --marketplace acme/claude-plugins
claude plugin list                      # Installed / Session-only / Skills-directory / Synced sections
claude plugin details release-kit       # Component inventory, Projected token cost, Always-on line
claude plugin disable release-kit@acme-tools
claude plugin update release-kit@acme-tools
claude plugin uninstall release-kit@acme-tools --scope project [--keep-data]

Scopes write enabledPlugins. User scope writes it to ~/.claude/settings.json, project to .claude/settings.json, and local to .claude/settings.local.json. "The local setting overrides the project setting, and the project setting overrides the user setting." Committing a project entry "turns the plugin on for your collaborators but doesn't download it to their machines". For a plugin with an external source, the /plugin Errors tab shows Plugin "<name>" is enabled in project settings but isn't installed here until each person installs it. A relative-path plugin from the marketplace (or one in a seed directory) is the exception (plugin loading). A project-scope plugin also loads only after workspace trust, its MCP servers get the per-server approval prompt, and its monitors don't load. To opt out on your machine, set the ID to false in .claude/settings.local.json. A managed enabledPlugins of false "blocks at every scope and hides the plugin".

A plugin must reach three layers before you can use it: settings declare it, disk holds it (~/.claude/plugins/), and the session loads it. Step through an install, a teammate's clone, an update and an uninstall to see which layer each command changes. The slip, the box and the lamp are the three layers; the highlighted one is what the step changed.

Every enabled plugin costs every session. "An enabled plugin is part of every session, not only the sessions where you use it." The name and description of each skill, agent and command sit in context every turn. claude plugin details shows the Always-on tokens, and the install pane shows Context cost (Every turn / When invoked) for official-marketplace plugins. Disable what you don't use: the /plugin Installed tab groups plugins Not used recently, and /skill-doctor reports plugins you haven't used.

Updating. Auto-update is on by default for claude-plugins-official, the other official names except knowledge-work-plugins and first-party-plugins, and claude.ai marketplaces. It's off for community, third-party and local marketplaces. "There's no command that updates every plugin at once." Background updates end with Run /reload-plugins to apply. /reload-plugins --force applies a reload that changes MCP tools, at the cost of one uncached request.

Headless and CI. "/plugin doesn't run" in claude -p, but installed plugins load. Install with the shell commands, set CLAUDE_CODE_SYNC_PLUGIN_INSTALL=1 so a -p run waits for installs, and confirm with the plugins field of the stream-json system/init event. The Agent SDK uses its plugins option. Cloud sessions don't load the plugins in your local settings.

Who wins: enabledPlugins sources, name conflicts and session-only plugins

enabledPlugins can be set in six sources, merged key by key. From lowest to highest precedence: --add-dir directories (only true counts) → user → project → local → the --settings flag → managed. Managed true force-enables and false blocks, and nothing overrides either. When your user false loses, claude plugin list says so explicitly: Disabled in ~/.claude/settings.json but still loads — project settings enable it, which overrides your user setting. The fix is a false in .claude/settings.local.json (plugin loading).

Names. A marketplace plugin has two names. The entry name is the install key, the cache directory and the enabledPlugins key. The manifest name is the component namespace and what name conflicts compare. A session-only plugin (--plugin-dir/--plugin-url, shown as <name>@inline) wins over an installed plugin with the same name, unless you disable it as <name>@inline or managed settings lock the name. That's convenient for testing a fix against your installed copy, and a hazard if a script passes --plugin-dir to an untrusted path. Admins close that hole with disableSideloadFlags. When two enabled plugins share a manifest name, only one registers its hooks/hooks.json hooks.

Fetching rules. Plugins load at session start from installed_plugins.json and the cache, without the network. Background work then reconciles: it clones newly declared marketplaces, re-fetches ones whose source changed (Plugins changed. Run /reload-plugins to activate.), and runs auto-updates. A reload that would change MCP tools mid-conversation is held until /reload-plugins --force, because it would invalidate the prompt cache.

Security pitfall: review before install, and after updates"A Claude Code plugin you install can execute arbitrary code on your machine with your user privileges." The Will install section "shows that a hook exists but not what it runs". Before trusting a plugin, read hooks/hooks.json, .mcp.json and bin/, and run claude --plugin-dir <dir> plugin details <name>. Auto-update means "the files you reviewed can change on disk". Removing a marketplace "uninstalls every plugin you installed from it" (plugin security).

Mods

"A mod is a plugin that changes how Claude Code looks and behaves." It's made of JavaScript or TypeScript event handlers that Claude Code calls in its own process when an event happens: a tool call, a submitted prompt, part of the interface being drawn. A handler can observe the event, rewrite it, or answer it so the usual behavior doesn't run. Mods need terminal v2.1.287+ (Desktop v2.1.286+) and are on by default. Several of Claude Code's own features are mods: /diff, AGENTS.md support, the sec-default guard and "You should know" (mods overview, getting-started post).

first-mod/
├── .claude-plugin/plugin.json
└── hooks/
    ├── hooks.json        # { "modules": ["./register.js"] }   (may also hold settings hooks under "hooks")
    └── register.js       # the hooks module: export function register(on, options)
// hooks/register.js — the docs' complete example: count tool calls, show the count by the spinner
let calls = 0

export function register(on) {
  on('tool.call', async ($, e, next) => {
    calls += 1
    $.ui.invalidate('ui.render')          // ask Claude Code to redraw so the count shows
    return next(e)                         // let the tool run as usual
  })

  on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
    return next({ ...e, props: { ...e.props, suffix: ' · tool calls: ' + calls + '…' } })
  })
}

The model is middleware. on(event, [matcher], handler) receives $ (the mods API), e (deeply frozen event data; pass a modified copy to next) and next (the rest of the chain, then Claude Code's own behavior). To refuse a call, return { deny: 'reason Claude can act on' } without calling next. To answer it yourself, return { result }. To act after the tool runs, await next(e). The $ API covers $.ui (panes, toasts, the band above the prompt), $.command and $.tool (add commands and tools), $.model (call a model on your plan), $.fs, $.http, $.process, $.store and $.session. Because every side effect goes through $, claude plugin validate can list a mod's hooks: and calls: before you install it (mods reference).

One tool.call event travels outward-in through the documented order: managed PreToolUse hooks, then organization and prepend mods (incl. sec-default where it loads), then mods you install, then append mods, then built-in mods, then Claude Code's own behavior (other settings PreToolUse hooks, the permission check, the tool). Results travel back out. The event descends the left side of the stack and the result climbs the right; a deny turns back at the layer that refuses.
ModSettings hookSkillMCP server
What it isFunctions in a plugin that Claude Code calls in its own processShell command, HTTP request or prompt run on a lifecycle eventInstructions Claude readsExternal process or service giving Claude tools
Can changeTool calls, prompts, commands, turns, what the UI drawsGo/no-go, tool args and results, added contextWhat Claude knows and doesWhich tools Claude has
Draws UIYesNoNoNo
Pick it whenYou want a pane, a band, a custom command, or to rewrite an eventYou want to block, allow or log with a script you haveYou keep pasting the same instructionsClaude needs an external system
Trust: a mod is you, inside Claude CodeOnce loaded, a mod can read and write your files, read secrets in env and settings, see every prompt and tool call, rewrite them, "approve a tool call before you're asked", and spend your usage. "Mods aren't sandboxed." With managed settings or a Team/Enterprise /login as the session's credential, a mod's tool.check approval doesn't get a call past your deny rules, ask rules or PreToolUse hooks by default (for deny rules, "your organization can change that"). Without either, and API-key or CLAUDE_CODE_OAUTH_TOKEN sessions count as this setup, "the mod can approve a call that a deny rule refuses or a PreToolUse hook blocked" (permissions: precedence among rules, hooks, and mods). A mod can't restyle the permission prompt. Turn mods off with --safe-mode (one session) or "disableAllHooks": true (also stops your settings hooks). Inspect before installing with claude plugin validate ./some-mod.

Building one. /plugin-authoring (v2.1.287+) loads the mod-writing reference as a skill, so you can describe the mod and have Claude write it. claude --plugin-dir ./first-mod reloads the hooks module on save. claude plugin test runs the mod's *.test.ts files with no session or network. Limits to design for: a hook's own execution gets 10 seconds (50 ms for prompt.edit), $.fs reads up to 4 MiB, and redraws are throttled. Hooks run in claude -p and the SDK, but nothing draws there. Anthropic's samples (token-weather, blast-radius, replay-theater) live in claude-code-playground.

Versioning

Claude Code computes a version for every installed plugin. That version names the cache directory (~/.claude/plugins/cache/<marketplace>/<plugin>/<version>/) and decides whether an update changes anything. Resolution for every source except command: the version field in the plugin's manifest comes first, then the version field in its marketplace entry. When neither is set, the source decides: a 12-character commit SHA for github, url and git-subdir, a 12-character SHA-256 for archive, or unknown for npm and for a local non-git directory (plugin loading).

That rule creates the classic trap. Set "version": "1.0.0", push fixes without bumping it, and claude plugin update prints <name> is already at the latest version (1.0.0). Users keep the old copy. Pick one policy per plugin. Either bump version on every release (and run claude plugin validate --strict in CI, which fails on a missing version), or omit it in a git-hosted marketplace so the commit SHA is the version (publish). One exception: a plugin loaded in place from a local-path marketplace loads its current files at every session start, whatever the version says.

Dependencies. dependencies in plugin.json lists other plugins as a bare name, "name@marketplace", or { "name", "version" } with a semver range (~2.1.0, ^2.0, >=1.4, =2.1.0). Ranges resolve against git tags named <plugin-name>--v<version>. Create them with claude plugin tag --push, which also checks that plugin.json and the marketplace entry agree. When several installed plugins constrain one dependency, it resolves to the highest tag satisfying all their ranges. Disjoint ranges fail with has conflicting version requirements. Pre-releases match only with an opt-in suffix such as ^2.0.0-0 (dependencies).

{
  "name": "deploy-kit",
  "version": "3.1.0",
  "dependencies": [
    "audit-logger",
    { "name": "secrets-vault", "version": "~2.1.0" }
  ]
}
Left: how Claude Code computes a plugin's version and whether an update is detected after unbumped commits. Right: which secrets-vault tag two plugins' ranges resolve to, using the documented highest-satisfying-tag rule. The chip shows which version source won; the lattice puts tags in rows by major version, hatches each plugin's range, and outlines the answer.
Release checklist that avoids most support tickets
  1. Bump version, or deliberately omit it.
  2. Run claude plugin validate . --strict.
  3. Run claude plugin eval and gate on its exit code.
  4. Run claude plugin tag --push if anything depends on you.
  5. Install from the marketplace in a clean profile (not --plugin-dir) to catch relative-path and name mismatches.
  6. Check claude plugin details for always-on token cost.
One manifest field blocks older clients outright: declaring userConfig options means "users on Claude Code versions before v2.1.271 can't load the plugin".

What you build: lab-review, a plugin with one of each component: the skill /lab-review:review, the subagent lab-review:test-auditor, and a PostToolUse hook on Edit|Write. Seeded broken copies (bad/reserved, bad/paths, bad/ignored-fields) cover the rules on this page. plugin_validate.py checks the manifest and components offline, lints the skills with skill_lint.py, and runs the hook against three documented PostToolUse payloads, one of them with cwd in a subfolder. Run:

cd labs && python3 agents-3/plugin_validate.py   # the kit must pass; bad/ plugins match EXPECTED.json
python3 agents-3/plugin_validate.py PATH --strict                    # any plugin root; warnings fail too
python3 agents-3/plugin_validate.py --with-claude                    # also runs claude plugin validate (no model call)
claude --plugin-dir agents-3/plugin_kit/kit/lab-review               # one session, nothing installed

Observe: the kit has 0 errors. Its hook adds additionalContext naming tests/test_pricing.py after a Write to tinyapp/pricing.py, and stays silent for README.md. It finds tests/ under the git root above the payload's cwd, so it also works when cwd is tinyapp/. bad/reserved shows a reserved name, a skill inside .claude-plugin/, a path without ./ and a hooks file without its "hooks" wrapper. bad/paths shows .. traversal and agents pointing at a directory. bad/ignored-fields shows agent fields that plugins silently ignore. Compare with --with-claude: the official validator catches the path, type and URL errors, and the reserved name once the schema errors are fixed, but says nothing about a component inside .claude-plugin/ or ignored agent fields. Read hooks/hooks.json and scripts/ before enabling the kit, because the hook runs as you in every session.

Open the lab walkthrough

Exercise: ship your setup as a plugin through a local marketplace

Take one skill and one hook from a repo's .claude/ and package them as team-kit. Create a sibling my-marketplace/ with a marketplace.json entry for it, validate both, add the marketplace, install the plugin at project scope, and confirm the skill appears as /team-kit:<skill>. Then make a change, run claude plugin update with and without bumping version, and explain the output.

Show a reference solution
mkdir -p team-kit/.claude-plugin team-kit/skills team-kit/hooks my-marketplace/.claude-plugin
cp -r .claude/skills/release-notes team-kit/skills/
printf '{ "name": "team-kit", "version": "0.1.0", "description": "Team skills and hooks" }\n' > team-kit/.claude-plugin/plugin.json
# move the hooks object from .claude/settings.json into team-kit/hooks/hooks.json as { "hooks": { … } }
mv team-kit my-marketplace/
cat > my-marketplace/.claude-plugin/marketplace.json <<'EOF'
{ "name": "my-marketplace", "owner": { "name": "Me" },
  "plugins": [ { "name": "team-kit", "source": "./team-kit", "description": "Team skills and hooks" } ] }
EOF
claude plugin validate ./my-marketplace            # the catalog
claude plugin validate ./my-marketplace/team-kit   # the plugin (a marketplace run doesn't open its component files)
claude plugin marketplace add ./my-marketplace
claude plugin install team-kit@my-marketplace --scope project

Remove the hook from .claude/settings.json after moving it, or it "runs twice". A local relative-path marketplace is read in place, so your edits show up at the next session start or /reload-plugins whatever the version. That's why the bump/no-bump experiment only shows the "already at the latest version" message once you host the marketplace in git and install from there.

Key takeaways

  • Only plugin.json goes in .claude-plugin/. Components live at the root, and every manifest path starts with ./.
  • Plugin skills and agents are namespaced; hooks aren't, so duplicates run twice. Plugin agents ignore permissionMode, hooks and mcpServers.
  • Marketplaces are catalogs. Keep entry name = manifest name, and know that removing a marketplace uninstalls its plugins.
  • Scopes write enabledPlugins (local over project over user). A committed entry enables but doesn't download.
  • Mods are in-process JS middleware with your full privileges. Inspect with claude plugin validate, disable with --safe-mode.
  • Version = manifest, then entry, then commit SHA. A pinned, unbumped version means users never get your fix.

Context Management

Every extension in this session feeds the same context window. MCP results, script output, fetched pages and skill bodies all compete with the code Claude is working on. Claude Code already caps and offloads large results. The expert move is to design extensions so that bulk never needs to enter the window, and to be clear about which content and code crosses a trust boundary on the way in. For session-level habits like /context, /clear and compaction, see Core 2.

Tool Output Limits

Every built-in tool, and every MCP tool, has a ceiling on what it returns inline. Past that ceiling Claude Code doesn't silently truncate: it either saves the full output to a file and gives Claude the path plus a preview, or (for failures) keeps a head-and-tail excerpt. Knowing which tool does which tells you whether Claude saw the error line or only a pointer to it (tools reference, mcp).

ToolInline ceiling (default)Past the ceilingKnobs
Bash, valid result~30,000 charactersPath of a file in the session directory plus a preview of up to 2,000 charactersbashOutputMaxChars (≤128,000, v2.1.261+) sets inline + read-back
Bash, failure~10,000 charactersHead-and-tail excerpt cut from the read-back window, no file pathBASH_MAX_OUTPUT_LENGTH (read-back window, default 30,000, max 150,000)
MCP tool, successWarn >10,000 tokens; limit 25,000 tokens; text >50,000 charactersSaved to the session's tool-results directory and replaced by a message naming the fileMAX_MCP_OUTPUT_TOKENS; server _meta["anthropic/maxResultSizeChars"] (≤500,000)
MCP tool, isError~11,000 charactersFirst 5,000 + last 5,000 with a removed-count markernone
Read25,000 tokens per call; whole file over 256 KB refusedClaude pages with offset/limit, or allow_large: true (v2.1.296+) sized to the room leftCLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS
WebFetch100,000 characters of page content per callFor most fetches, a separate model call answers over the page and Claude gets that answer; longer pages report the unread remainder (v2.1.290+)—
Glob100 files, sorted by modification timeTruncation flag, so Claude narrows the pattern. Note: Glob and Grep are "absent by default on macOS, Linux, and WSL", where search runs through Bash and the Bash limits apply—
Pick a tool, an outcome and an output size, and adjust the knobs. The router applies the documented thresholds and shows what lands in context. Token estimates use about 2.5 characters per token (the models overview's rough figure), so they're approximate. The output drops into the hopper and leaves by the chute the thresholds pick; the short mark is the line that matters.
Pitfall: the failing build whose error is past the windowA failing command gets a 10,000-character head-and-tail excerpt cut from the read-back window, which is 30,000 characters by default. If your build prints 200,000 characters and the real error is near the end, the excerpt's "tail" is the tail of the first 30,000, and Claude never sees the error. Fix it at the source: filter output (next concept). Or raise BASH_MAX_OUTPUT_LENGTH for verbose builds, accepting more context per failure. Exit code 1 also counts as a failure for most commands. Only grep, rg, find, diff, test, git diff, git grep and a few others treat it as a valid result.

For server authors: treat these limits as a design spec, not a backstop. A tool that regularly hits 50,000 characters forces an extra Read round-trip every time. Return a summary plus an ID, paginate, or offer a detail parameter. Use maxResultSizeChars only for outputs that are inherently large and needed whole, such as a schema. HTTP/SSE responses over 16 MiB fail outright.

Code Execution Patterns

Anthropic's engineering post Code execution with MCP names two costs of naive tool use: "Tool definitions overload the context window" and "Intermediate tool results consume additional tokens." Claude Code's tool search already solves the first. The second is yours to solve, with the code execution pattern: let Claude write code that calls the API or CLI, filters and joins in the program, and prints only what matters. In the post's example, presenting MCP servers as code APIs cut usage "from 150,000 tokens to 2,000 tokens", a 98.7% saving. Their own caveat applies: "Running agent-generated code requires a secure execution environment with appropriate sandboxing."

Left: each tool result passes through the context window before Claude can use it in the next call. Right: Claude writes one script, the shell runs it (sandboxed if you've turned the sandbox on), and only the summary returns. Hover either side; the record counts are illustrative.

The pattern in Claude Code, five ways:

  1. Prefer CLIs and pipes. gh pr list --json number,title --jq '.[] | select(.title|test("auth"))' returns ten lines where an MCP list call might return a thousand objects. The costs docs call CLIs "still more context-efficient than MCP servers".
  2. Scripts in skills and plugins. Put the join, filter or validation logic in scripts/ (skills) or bin/ (plugins). Claude runs it, and only stdout enters context.
  3. Filter in a hook. The costs docs' own example is a PreToolUse hook on Bash that rewrites test commands to keep only failures, using updatedInput:
#!/bin/bash
# ~/.claude/hooks/filter-test-output.sh  (from the costs docs; registered as a PreToolUse hook with matcher "Bash")
input=$(cat)
cmd=$(echo "$input" | jq -r '.tool_input.command')
pattern='^(npm test|pytest|go test)( [^;&|<>`$#\\[:cntrl:]]*)?$'
if [[ "$cmd" =~ $pattern ]]; then
  filtered_cmd="$cmd 2>&1 | grep -A 5 -E '(FAIL|ERROR|error:)' | head -100"
  echo "$input" | jq --arg filtered "$filtered_cmd" \
    '{hookSpecificOutput: {hookEventName: "PreToolUse", updatedInput: (.tool_input + {command: $filtered})}}'
else
  echo "{}"
fi
Security note on this recipeTwo details keep it safe. The pattern matches only a bare test command with plain arguments, so a command with ;, &, |, <, >, a backtick, $, #, a backslash or a control character in it (npm test && curl … | sh, say) passes through unchanged. And the hook returns no permissionDecision, so the rewritten command still goes through your permission rules and mode: Claude Code "evaluates permission rules … against the input your hook returns, not the input Claude sent" (hooks). Adding "allow" would auto-approve every command the pattern lets through, so if you add it, keep the pattern this strict.
  1. Delegate verbose work to a subagent. The noise stays in its window and a summary comes back (Agents 4). It costs more tokens in total, but your main context stays clean.
  2. Design MCP tools for code. Give tools filter and projection parameters (fields, where, limit) so even direct calls return small results.
Toy model with illustrative numbers. A task needs records from a system, filtered down to a handful. Compare the tokens that pass through the main context window under four strategies, including Claude Code's automatic offload followed by a grep, and the total tokens processed. Each row is a dumbbell on a log scale: the filled dot is the main window, the ring is everything processed. Hover a row.
The API-side version: programmatic tool calling

If you build agents on the Claude API rather than in Claude Code, the same idea ships as programmatic tool calling. You mark tools with allowed_callers so the server-side code execution tool can call them from a script, and intermediate results stay inside the code environment (cookbook: Programmatic tool calling; it uses the Client SDK and needs an API key, not the Agent SDK). Inside Claude Code, the Bash tool plus a sandbox (/sandbox; off by default) is your code execution environment. With the sandbox on, scripts Claude writes are filesystem- and network-isolated, which is what makes letting Claude write and run the glue code safe enough to do routinely. MCP servers themselves run outside it.

Offloading to Files

Offloading means keeping bulk on disk and only a pointer plus a preview in context. Claude can then grep, head or Read with an offset when it needs a specific part. Claude Code does this automatically. Bash output over the inline ceiling becomes a file path plus a 2,000-character preview. MCP results over the limit go to the session's tool-results directory under ~/.claude/projects/. MCP image results are saved there at full resolution too (v2.1.283+), while Claude sees a scaled inline copy. Those files are cleaned up with session data after cleanupPeriodDays (30 days by default).

The context window holds a path and a small preview. The full result stays on disk, and Claude pulls slices with targeted reads. Compare a 120,000-character log inline (about 48,000 tokens at roughly 2.5 characters per token, illustrative) with a pointer and preview (about 850 tokens).

Deliberate offloading patterns you can put in skills, CLAUDE.md or briefs:

  • Write, then search. "Write the full output to .scratch/build.log and grep it for error" beats running the build inline. It survives a long session, too.
  • State in files. For long runs, keep a progress file or TASKS.md, plus a JSON feature list Claude updates. The long-running harness post found that "the model is less likely to inappropriately change or overwrite JSON files compared to Markdown files." After compaction Claude re-reads up to five recently modified files, and a file over 5,000 tokens comes back only as a path, so keep the state file small.
  • Subagents return paths, not dumps. Ask research subagents to write findings to a file and return a 10-line summary with the path.
  • Background work writes to files. A backgrounded Bash command (Ctrl+B, or one that hits its timeout) keeps writing to an output file that Claude reads with Read. A long MCP call that auto-backgrounds after 2 minutes reports through a task notification. Append a marker such as ; echo DONE so the end of a file is detectable. The docs suggest exactly this for backgroundOutputPath when you serve Claude Code over MCP (v2.1.295+).
Practical tipAdd a "Compact Instructions" section to CLAUDE.md that says which files hold state ("Progress lives in TASKS.md; re-read it after compaction"). Or use a SessionStart hook with the compact source to re-inject a short state summary. Hooks that match compact run again after compaction and add their output to the compacted context.

Exercise: measure an offload

In a scratch repo, have Claude run a command that prints about 100,000 characters (for example seq 1 20000). Run /context before and after, and note what the transcript shows for the result (Ctrl+O). Then ask Claude to run the same command redirected to .scratch/out.txt and report the line count and last line. Compare the two context deltas.

Show a reference solution

The first run returns a file path and a preview of up to 2,000 characters, not 100,000 characters inline. The context grows by roughly the preview plus the tool-call overhead, and Claude may then Read the file if you ask for more. The redirected run costs only the command and a short answer. The lesson: offloading is automatic but not free, because every follow-up Read of the saved file costs again. Designing commands to print small answers beats relying on the safety net. Neither run should write outside your scratch repo; check with git status.

Trust Boundaries

Two questions decide whether an extension is safe: what runs as you without being checked, and what enters Claude's context that someone else wrote. Claude Code's permission rules and sandbox cover "the tool calls Claude makes, not the code a plugin runs by itself" (plugin security). Hooks, monitors, MCP and LSP servers, and the processes a mod starts run outside the sandbox with your full user permissions. The sandbox, when you turn it on, isolates Bash commands. Claude's file tools are governed by permission rules, not the sandbox (sandboxing). That's the trust boundary.

The second question is prompt injection. Content that crosses into context is data that can carry instructions: MCP results, fetched pages, issue and PR text, files in a cloned repo, and skill and plugin bodies. Claude Code's built-in mitigations include approval for network commands (curl and wget aren't auto-approved), WebFetch's separate summarizing model call, the workspace trust dialog, the .mcp.json approval prompt, command-injection detection and fail-closed matching in Manual mode (security). None of them makes a hostile instruction harmless if the agent also holds a dangerous capability. Defense means removing that combination.

Choose how Claude Code is started in a repository you didn't write. Each row is something the repository can supply, taken from the permissions docs' "What runs before you trust a folder" table plus --bare. Click a row's why for the boundary that governs it. Every session type is a column, so you can compare them at a glance; the menu or a column heading highlights one.

A defensive checklist for extensions:

  1. Untrusted repo, headless. Use --bare (no project hooks, skills, plugins or .mcp.json), or --setting-sources user. Add --settings '{"disableAllHooks": true}' if you need settings but not hooks: putting disableAllHooks in your user settings alone isn't enough, because project settings take precedence. Note that --bare still applies the project's env block.
  2. Skills from repos. Read their allowed-tools and ! commands before running Claude Code there, because neither is trust-gated. Organizations set allowManagedPermissionRulesOnly and disableSkillShellExecution.
  3. Plugins. Read hooks/hooks.json, .mcp.json and bin/, and use claude plugin validate for mods. Prefer pinned sources (sha, archive with sha256). Remember that auto-update can change reviewed files.
  4. MCP. Grant the least privilege per tool. Use read-only accounts, pinned OAuth scopes, and requiresUserInteraction for consent steps. Never combine a server that reads untrusted content with unprompted write tools in the same session.
  5. The real boundary. Deny rules (for example Read(~/.ssh/**)), the sandbox with a narrow network allowlist, and a container for anything autonomous. Hooks are defense in depth, not the boundary (Agents 5). Deny rules are mod-proof only under managed settings or a Team/Enterprise /login. Without either (an API key or CLAUDE_CODE_OAUTH_TOKEN doesn't count), a mod you install "can approve a call that a deny rule refuses or a PreToolUse hook blocked". Treat installing a mod as extending your trust boundary to its author. Also remember that, in Bash, Read/Edit deny rules cover the file commands Claude Code recognizes (cat, head, grep, find, redirections) when the denied path appears as an argument. They don't cover a grep -r or find over a directory that contains denied files, or "subprocesses that open files themselves" (large codebases). The sandbox is the OS-level boundary.
The lethal combination, and where each extension sits in it

A practical way to reason about injection risk, popularized by Simon Willison as the "lethal trifecta" (community post), is to ask whether one session combines three things: (a) exposure to content an attacker can write, (b) access to something valuable (secrets, private code, production), and (c) a way to act or exfiltrate without a human in the loop (write tools, network egress, a pushing git remote). Each extension type moves you along these axes:

  • (a) exposure: MCP servers that read tickets, mail or the web; WebFetch; cloned repos.
  • (b) access: MCP servers with broad tokens; anything outside the sandbox; plugin and mod code (which runs as you).
  • (c) action: allowed-tools grants, allow rules, auto mode, and mods that approve calls.

Claude Code gives you a control on each axis. For exposure: disabledMcpjsonServers, denying WebFetch, --bare. For access: deny rules, the sandbox's filesystem.denyRead, scoped credentials. For action: ask rules, requiresUserInteraction, dontAsk with an exact allowlist in CI, and managed policy. Remove one axis per session and the attack chain breaks. Auto mode's classifier is a further layer, but Anthropic's own measurement put its false-negative rate on real overeager actions at 17% (auto mode post). Treat it as a layer, not a boundary. Anthropic's containment post describes the same thinking for their own infrastructure.

Key takeaways

  • Over the ceiling, Claude Code offloads (path plus preview) rather than truncating. Failures get head-and-tail excerpts from a 30,000-character read-back window.
  • Code execution beats chained tool calls for bulk data: scripts, CLIs, hook filters, filterable MCP tools.
  • Offload deliberately. Small state files survive compaction, and subagents should return paths and summaries.
  • Permission rules and the sandbox govern Claude's tool calls. Hooks, MCP/LSP servers, monitors and mods run as you outside them.
  • In untrusted repos, start headless runs with --bare or --setting-sources user. .mcp.json servers and skill allowed-tools apply in -p without any prompt.

Session wrap-up

You now have the builder's model of every Claude Code extension. Instruction files concatenate by scope and are advisory. MCP servers are scoped, approved, authenticated and deferred behind tool search. Skills load in layers, and their allowed-tools grants without restricting. Plugins package all of it with a manifest, a marketplace, computed versions and, for mods, in-process JavaScript. Context management is about keeping bulk out of the window and knowing what crosses the trust boundary. The thread through every topic: put each need in the cheapest mechanism that guarantees it, and measure the cost in /context rather than guessing.

Where this connects
Labs for this session
  • mcp_server/: the stdlib lab-docs stdio server, its JSON-RPC test client and install block. python3 agents-3/mcp_server/test_client.py
  • skill_lint.py: frontmatter, listing budget, injection and grant linter with good and bad samples. python3 agents-3/skill_lint.py
  • plugin_kit/: the lab-review plugin (skill, agent, hook), seeded broken copies, and plugin_validate.py. python3 agents-3/plugin_validate.py

Run from labs/. All three run offline by default; see each folder's README for the optional real-mode steps.

What to do next

  1. Run /context all in your main repo and list every always-on extension cost: instruction files, the skill listing, MCP names, plugins.
  2. Pick the biggest item and move it one rung: CLAUDE.md to a rule or skill, an MCP server to a CLI, a plugin to disabled.
  3. Package one skill and one hook as a plugin through a local marketplace, then add a claude plugin eval case for the skill.
  4. Audit one repo you didn't write with the trust map. Would claude -p run anything there you haven't read?
  5. Continue to Agents 4: Multi-Agent Work, where subagents preload these skills and scope these MCP servers.