10  MCP与Hooks

本章介绍 Claude Code 的两项高级自动化功能:MCP 服务器(扩展工具能力)和 Hooks(触发事件响应)。这些功能面向有一定使用经验的用户,初学者可先跳过。

10.1 MCP 服务器配置

MCP(Model Context Protocol)是扩展 Claude Code 能力的插件协议。通过配置 MCP 服务器,Claude Code 可以获得额外的工具能力。

10.1.1 配置文件位置

MCP 服务器在 ~/.claude/settings.json 中配置:

{
  "mcpServers": {
    "fetch": {
      "command": "npx",
      "args": ["-y", "@anthropic-ai/mcp-fetch"]
    }
  }
}

10.1.2 常用 MCP 服务器

服务器 用途 安装命令
fetch 抓取网页内容 npx @anthropic-ai/mcp-fetch
filesystem 增强文件操作 npx @anthropic-ai/mcp-filesystem
memory 持久化记忆 npx @anthropic-ai/mcp-memory

10.1.3 社科研究者推荐配置

  • fetch:让 Claude Code 能够访问在线数据源、API 文档
  • filesystem:增强对大型数据目录的浏览能力

10.2 Hooks 自动化

Hooks 允许你在 Claude Code 的特定事件(如工具调用前后)自动执行 shell 命令。

10.2.1 配置位置

~/.claude/settings.json 中的 hooks 字段:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "command": "echo '文件已修改: $TOOL_INPUT'"
      }
    ]
  }
}

10.2.2 实用 Hook 示例

注释

以下 R 相关 Hook 示例依赖 stylerlintr 包。如尚未安装,在 Claude Code 聊天框中输入:

帮我安装 R 包:install.packages(c("styler", "lintr"))

10.2.2.1 自动格式化 R 代码

每次 Claude Code 编辑 .R 文件后,自动运行 styler 格式化:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "command": "if echo $TOOL_INPUT | grep -q '\\.R$'; then Rscript -e 'styler::style_file(\"$FILE_PATH\")'; fi"
      }
    ]
  }
}

10.2.2.2 提交前检查

在 Git 提交前自动运行 R 脚本的语法检查:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "command": "if echo $TOOL_INPUT | grep -q 'git commit'; then Rscript -e 'lintr::lint_dir(\"scripts/\")'; fi"
      }
    ]
  }
}
提示

Hooks 是高级功能,建议在熟悉 Claude Code 基本使用后再配置。从简单的通知类 Hook 开始,逐步添加自动化逻辑。