Skip to content

工具与 Hooks 集成

自定义 Skill 可以访问 Claude Code 的工具集,并与 Hooks 系统集成。

工具列表

Skill 可用的标准工具:

工具类型说明
Read只读读取文件
Write写入创建/覆盖文件
Edit写入精确字符串替换
Bash执行运行 Shell 命令
Glob只读文件模式匹配
Grep只读文本搜索
WebFetch网络获取网页内容
WebSearch网络搜索互联网

配置工具权限

yaml
allowed-tools:
  - Read
  - Write
  - Edit

原则:只授予 Skill 真正需要的工具。

只读分析 Skill

yaml
allowed-tools:
  - Read
  - Bash    # 只用于 git log、npm ls 等查询命令

代码生成 Skill

yaml
allowed-tools:
  - Read
  - Write
  - Edit
  - Bash    # 运行测试验证

Hooks 集成

Hooks 允许在特定事件时自动执行操作。

可用的事件钩子

json
{
  "hooks": {
    "PreToolUse": {
      "bash": "echo 'About to run: $TOOL_NAME'"
    },
    "PostToolUse": {
      "bash": "npm run lint"
    }
  }
}

Skill + Hook 组合示例

场景:创建一个代码生成 Skill,每次写文件后自动格式化。

SKILL.md:

yaml
---
name: component-generator
description: Generate React components with tests and stories
allowed-tools: [Read, Write, Edit, Bash]
---

settings.json:

json
{
  "hooks": {
    "PostToolUse": [
      {
        "tool": "Write",
        "command": "npx prettier --write $FILE_PATH"
      }
    ]
  }
}

MCP 工具

如果配置了 MCP 服务器(如 CodeGraph),Skill 也可以调用 MCP 工具。

yaml
# 使用 codegraph 的 Skill
name: code-explorer
description: Explore codebase structure using CodeGraph
allowed-tools:
  - Read
  - mcp__codegraph__codegraph_search
  - mcp__codegraph__codegraph_context

安全最佳实践

  1. 永远不要allowed-tools 中放通配符
  2. Bash 工具限制具体命令(通过 settings.json 的 permissions)
  3. 敏感操作(deploy、publish)不应该放在 allowlist 中
  4. Hooks 命令在 Claude Code 进程外部执行,注意脚本安全性

下一步