C Claude Code Internals
| EN | ES

Custom Agents

自定义代理是定义为带 YAML frontmatter 的 markdown 文件的专用 AI 人格。每个代理都有自己的系统提示词、工具白名单、模型、权限模式、MCP 服务器、hooks、持久化内存和颜色标识。

4 代理定义类型 6 优先级级别 3 内存作用域 8 可用颜色
i 一个文件,一个代理
.claude/agents/ 中放入一个 .md 文件, 它就会立即可用。YAML frontmatter 配置所有内容 — 工具、模型、内存、hooks、MCP — markdown 正文是系统提示词。无需代码。

代理定义类型和优先级

4 种定义类型

类型 来源 提示词
内置 builtInAgents.ts 动态(函数)
自定义 .claude/agents/*.md 静态(markdown 正文)
插件 plugin/agents/*.md 静态 + 变量替换
标志 --agents CLI 标志 JSON(静态)

发现优先级(高者优先)

1(最低) Built-in 代码 所有项目
2 Plugin agents/ Plugin 作用域
3 ~/.claude/agents/ 个人,所有项目
4 <cwd>/.claude/agents/ 项目,与团队共享
5 --agents CLI 标志 仅会话
6(最高) <managed>/.claude/agents/ 企业范围

与内置代理同名的项目代理会覆盖它。CLAUDE_CODE_SIMPLE=true 跳过所有自定义代理。

Agent File Format

File location: .claude/agents/my-agent.md

---
name: my-agent
description: Use this agent for code reviews.
  Checks security, performance, and best practices.
tools:
  - Read
  - Grep
  - Glob
  - Bash
disallowedTools:
  - Write
  - Edit
model: opus
color: red
memory: project
maxTurns: 20
---

You are a specialized code reviewer. Your job is
to review code changes for security vulnerabilities,
performance issues, and best practices.

## Guidelines

1. Always check for OWASP top 10
2. Look for N+1 query patterns
3. Check for proper error handling

System prompt construction

1. Markdown body (everything after ---) is trimmed
2. If memory enabled → append MEMORY.md + scope guidelines
3. For plugins → substitute ${CLAUDE_PLUGIN_ROOT} and ${user_config.X}
4. At spawn → wrap with enhanceSystemPromptWithEnvDetails() (OS, shell, CWD, model, date, agent notes)
5. User context added: CLAUDE.md hierarchy (unless omitClaudeMd)
6. System context added: git status

Default prompt fallback

If no body is provided, the agent uses DEFAULT_AGENT_PROMPT: a general-purpose task-completion prompt that instructs the agent to use available tools, complete the task fully, and return a concise report.

Complete Frontmatter Schema

Required fields

Field Description
name 唯一标识符 → agentType。用于 subagent_type 选择。
description 显示给模型的 whenToUse 文本。支持 \n 换行。

Optional fields

Field Default Values / Notes
tools 所有工具 字符串或数组。[]=无,*=全部
disallowedTools 应用于允许列表之上的拒绝列表
model 继承 sonnetopushaikuinherit 或完整模型 ID
effort 继承 lowmediumhighmax
permissionMode 继承 defaultacceptEditsbypassPermissionsdontAskplanauto
color red、blue、green、yellow、purple、orange、pink、cyan
maxTurns 无限制 正整数
background false 始终作为后台任务运行
initialPrompt 前置到第一个用户轮次(主线程使用)
memory userprojectlocal
isolation 相同 CWD worktree — 隔离的 git worktree,自动清理
hooks 会话作用域,支持所有 27 个事件
mcpServers 字符串引用或内联服务器定义
skills 要预加载的技能名称(内容在第一轮之前注入)

Tool configuration

Resolution flow

1. tools undefined → all tools (full toolset)
2. tools: [] → no tools
3. tools: ["*"] → all tools
4. explicit list → only those tools
5. disallowedTools applied as denylist on top
6. memory + explicit list → auto-inject Read, Write, Edit
7. agent MCP tools merged additively
8. async agents → UserInput-type tools removed
# Read-only agent
tools:
  - Read
  - Grep
  - Glob
disallowedTools:
  - Agent
  - Write
  - Edit
  - Bash

# MCP tools (full name required)
tools:
  - Bash
  - Read
  - mcp__github__create_issue
  - mcp__slack__search_public

MCP Servers & Memory

MCP server configuration

Reference existing servers

mcpServers:
  - slack    # Uses "slack" from user/project config
  - github   # Shares connection, NOT cleaned up on finish

Inline definition

mcpServers:
  - my-api:
      type: http
      url: https://api.example.com/mcp
      headers:
        Authorization: Bearer `${API_TOKEN}`
# Newly created for agent, cleaned up when finished

Mixed

mcpServers:
  - slack                    # reference
  - custom:                  # inline
      command: node
      args: ["`${plugin_root}`/server.js"]

3 memory scopes

Scope Directory VCS
user ~/.claude/agent-memory/<name>/
project <cwd>/.claude/agent-memory/<name>/
local <cwd>/.claude/agent-memory-local/<name>/

How memory works

1. Memory directory created if it doesn't exist
2. loadAgentMemoryPrompt() loads MEMORY.md index → appended to system prompt
3. Scope-specific guidelines added ("keep learnings general" for user)
4. If explicit tools list → auto-inject Read, Write, Edit so agent can manage memory

Memory snapshots (VCS distribution)

Stored at <cwd>/.claude/agent-memory-snapshots/<agentType>/. On load: if no local memory but snapshot exists, copies snapshot to local. Teams can commit snapshots to share baseline agent knowledge.

Hooks Per-Agent

Frontmatter hooks example

---
name: formatter
hooks:
  PostToolUse:
    - matcher: "Write|Edit"
      hooks:
        - type: command
          command: "prettier --write \"$(cat | jq -r '.tool_input.file_path')\""
          timeout: 10
          statusMessage: "Formatting..."
  Stop:
    - hooks:
        - type: command
          command: "npm test"
---

Behavior

Registered as session hooks when the agent starts
Cleaned up automatically when the agent finishes
Agent Stop hooks auto-converted to SubagentStop
Hooks scoped to the agent's ID (no cross-agent leakage)
Under strictPluginOnlyCustomization, only admin-trusted sources can register hooks

All 27 hook events are supported in agent frontmatter.

Agent Invocation

AgentTool input schema

{
  description: string        // 3-5 words (REQUIRED)
  prompt: string             // Full task prompt (REQUIRED)
  subagent_type?: string     // Agent name (default: general-purpose)
  model?: 'sonnet'|'opus'|'haiku'
  run_in_background?: boolean
  name?: string              // For multi-agent teams
  team_name?: string
  mode?: PermissionMode      // Override for teammate
  isolation?: 'worktree'
  cwd?: string               // Working dir (KAIROS only)
}

Execution flow (10 steps)

1. Resolve agent definition from subagent_type
2. Initialize agent-specific MCP servers
3. Build system prompt (markdown + memory + env details)
4. Load user/system context (optionally omit CLAUDE.md)
5. Set up permission mode override (if defined)
6. Register agent hooks (scoped to agent lifecycle)
7. Preload skills (inject as user messages)
8. Call query() with agent context and tools
9. Stream messages as they arrive
10. On completion: clean up MCP servers, hooks

Fork vs Fresh agent

Aspect Fork (no subagent_type) Fresh (with subagent_type)
历史 继承父上下文 从空开始
工具 确切的父池 代理定义
系统提示词 父提示词 代理的 markdown
上下文窗口 与父共享 全新
目的 后台工作而不淹没父 专门执行

Isolation modes

isolation: worktree — creates a temporary git worktree for the agent. If no changes are made, the worktree is auto-cleaned. If changes are made, the worktree path and branch are returned.
isolation: remote — runs on Anthropic's Cloud Code Runner (ANT-only).

Plugin Agent Restrictions & Built-in Agents

Plugin agent security restrictions

Field Status
permissionMode 忽略 — 不能超过安装时信任级别
hooks 忽略 — 不能注册自定义 hooks
mcpServers 忽略 — 不能定义 MCP 服务器
所有其他字段 允许(name、tools、model、color 等)

Plugin agent names are namespaced: pluginName:agentName (e.g., my-plugin:test-runner).

JSON agent definitions (--agents flag)

All frontmatter fields available as JSON object keys. Multiple agents per JSON object.

Agents CANNOT be defined in settings.json — there is no agents key in the settings schema.

Built-in agents (6)

Agent Model Key features
general-purpose 继承 所有工具,研究和多步任务
Explore Haiku 只读,快速代码库搜索,省略 CLAUDE.md
Plan 继承 只读,架构规划,省略 CLAUDE.md
claude-code-guide Haiku 文档查找,dontAsk 权限模式
statusline-setup Sonnet 仅 Read + Edit 工具,橙色
verification 继承 后台,VERDICT 输出,功能标志控制,红色

CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS=true disables all built-in agents (non-interactive only).

Practical Examples

Security reviewer (read-only, opus)

---
name: security-review
description: Use for security reviews of code.
  Checks OWASP top 10, injection, auth, data exposure.
tools: [Read, Grep, Glob, Bash]
disallowedTools: [Write, Edit, Agent]
color: red
model: opus
---

You are a security code reviewer...

Deploy agent (MCP + maxTurns)

---
name: deployer
description: Use to deploy code to staging or prod.
  Requires deploy-server MCP to be connected.
tools: [Bash, Read, Grep]
mcpServers:
  - deploy-server
color: orange
permissionMode: default
maxTurns: 20
---

You are a deployment specialist...

Learning agent (user memory)

---
name: tutor
description: Use to learn about the codebase.
  Remembers what the user has learned.
tools: [Read, Grep, Glob]
memory: user
color: green
effort: high
---

You are a patient coding tutor...

Auto-formatter (per-agent hooks)

---
name: formatter
description: Use when writing code that needs
  auto-formatting after every file edit.
hooks:
  PostToolUse:
    - matcher: "Write|Edit"
      hooks:
        - type: command
          command: "prettier --write \"$(cat | jq -r '.tool_input.file_path')\""
          timeout: 10
---

You write clean code. Prettier formats automatically.

/agents Command

Interactive management UI

List all agents grouped by source (built-in, user, project, plugin)
View agent details (prompt, tools, configuration)
Create new agents via step-by-step wizard
Edit existing user/project agents
Delete user/project agents

Built-in and plugin agents are shown but marked non-editable.

Agent creation wizard (7 steps)

1. Name selection
2. Description (whenToUse)
3. System prompt editing
4. Tool configuration
5. Model selection
6. Color selection (ColorPicker component)
7. Save location: user (~/.claude/agents/) or project (.claude/agents/)
i Agent description is critical for selection
The description field is the only signal the model uses to decide which agent to pick. Write it as "Use this agent when..." followed by specific, concrete scenarios. Vague descriptions lead to poor agent selection. Supports \n for multi-line formatting in the agent list shown to the model.