Claude Code的配置体系是一个五层优先级的精密系统,决定了AI助手"能做什么"和"怎么做"。本教程从settings.json的完整字段解析出发,深入权限系统的allow/ask/deny三层规则引擎、沙箱隔离机制、Hooks生命周期钩子,直到企业级部署的MDM推送策略。适合已安装Claude Code但希望系统掌握配置治理的开发者和团队负责人。
npm install -g @anthropic-ai/claude-code)Claude Code的配置不是单一文件,而是五层堆叠的优先级体系。理解这五层,是掌控Claude Code行为的基石。
graph TB
subgraph "配置优先级(从高到低)"
A["🔒 Managed<br/>企业托管配置<br/>无法被任何层级覆盖"]
B["⌨️ CLI Arguments<br/>命令行参数<br/>临时会话覆盖"]
C["🏠 Local<br/>~/.claude/settings.local.json<br/>项目级个人覆盖"]
D["📂 Project<br/>项目级共享配置<br/>团队统一规范"]
E["👤 User<br/>用户级全局配置<br/>跨项目个人偏好"]
end
A --> B --> C --> D --> E
style A fill:#ff6b6b,color:#fff
style B fill:#ffd93d,color:#333
style C fill:#6bcb77,color:#fff
style D fill:#4d96ff,color:#fff
style E fill:#9b59b6,color:#fff
每一层的存储位置与作用域如下表:
| 层级 | 文件位置 | 影响范围 | 是否共享 |
|---|---|---|---|
| Managed | 系统级(macOS: plist,Windows: registry)或 managed-settings.json |
本机所有用户 | IT部署 |
| CLI Arguments | --permission-mode、--settings 等 |
当前会话 | 否 |
| Local | 项目根目录 .claude/settings.local.json |
当前项目、仅自己 | 否(gitignored) |
| Project | 项目根目录 .claude/settings.json |
当前项目、所有协作者 | 是(提交到git) |
| User | ~/.claude/settings.json |
所有项目、仅自己 | 否 |
常规设置采用覆盖策略——高优先级的值直接替换低优先级的值。例如User层设置 spinnerTipsEnabled: true,Project层设置 spinnerTipsEnabled: false,最终结果为 false。
权限规则采用合并策略——所有层级的 allow、ask、deny 规则会被合并在一起,但按 deny → ask → allow 的顺序评估,第一条匹配的规则胜出。这意味着Managed层的deny规则在任何情况下都无法被低层级的allow规则绕过。
在Claude Code交互会话中运行:
# 查看当前所有权限规则及其来源
/permissions
# 在终端中直接检查配置
cat ~/.claude/settings.json # 用户级
cat .claude/settings.json # 项目级
cat .claude/settings.local.json # 本地覆盖
常见问题:修改了settings.json但行为没变?检查是否有更高优先级的层级在覆盖。
settings.json 是一个JSON文件,包含以下主要字段:
{
"permissions": {
"allow": [],
"deny": [],
"ask": [],
"defaultMode": "default"
},
"hooks": {},
"env": {},
"model": "claude-sonnet-4-6",
"sandbox": {
"enabled": false
},
"outputStyle": "default",
"spinnerTipsEnabled": true,
"additionalDirectories": [],
"enabledPlugins": [],
"strictKnownMarketplaces": [],
"allowManagedPermissionRulesOnly": false,
"allowManagedHooksOnly": false
}
{
"permissions": {
"defaultMode": "default",
"allow": [
"Bash(npm test *)",
"Bash(git status)",
"Read",
"Grep",
"Glob"
],
"deny": [
"Bash(rm -rf *)",
"WebSearch"
],
"ask": [
"Bash(*)"
],
"disableBypassPermissionsMode": "disable",
"disableAutoMode": "disable"
}
}
字段说明:
| 字段 | 作用 | 示例 |
|---|---|---|
defaultMode |
默认权限模式 | default / acceptEdits / plan / auto / bypassPermissions |
allow |
无需确认直接执行 | "Bash(npm test *)" 允许所有npm test命令 |
deny |
完全禁止 | "Bash(rm -rf *)" 阻止危险删除 |
ask |
每次需要确认 | "Bash(*)" 所有Bash命令需确认 |
disableBypassPermissionsMode |
禁用bypass模式 | "disable" 阻止使用 --dangerously-skip-permissions |
disableAutoMode |
禁用auto模式 | "disable" 阻止自动批准模式 |
七种权限模式详解:
graph LR
subgraph "权限模式光谱"
A["plan<br/>只读探索<br/>最安全"] --> B["default<br/>标准确认"]
B --> C["acceptEdits<br/>自动编辑"]
C --> D["auto<br/>后台安全检查"]
D --> E["dontAsk<br/>拒绝未预批准"]
E --> F["bypassPermissions<br/>跳过所有提示<br/>最危险"]
end
style A fill:#27ae60,color:#fff
style F fill:#e74c3c,color:#fff
| 模式 | 行为 | 适用场景 |
|---|---|---|
plan |
只读探索,不可编辑文件 | 代码审查、架构分析 |
default |
首次使用工具需确认 | 日常开发 |
acceptEdits |
自动接受文件编辑和常见文件操作 | 频繁修改场景 |
auto |
后台安全检查后自动批准 | 高信任环境(研究预览) |
dontAsk |
拒绝未预批准的工具调用 | CI/CD流水线 |
bypassPermissions |
跳过所有权限提示 | 隔离容器/VM |
{
"env": {
"ANTHROPIC_API_KEY": "",
"NODE_ENV": "development",
"CUSTOM_CONFIG_PATH": "/path/to/config"
}
}
通过env字段注入的环境变量会在Claude Code启动时加载,优先级低于系统环境变量。API Key等敏感信息建议通过系统环境变量设置,而非硬编码到settings.json。
{
"model": "claude-sonnet-4-6"
}
可选值包括:
- claude-opus-4-6 — 最强推理能力
- claude-sonnet-4-6 — 性能与成本平衡(默认)
- claude-haiku-4-5 — 最快响应速度
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "npx prettier --write $CLAUDE_FILE_PATH"
}
]
}
]
}
}
Hooks将在第四章详细讲解。
{
"sandbox": {
"enabled": true,
"autoAllowBashIfSandboxed": true,
"allowUnsandboxedCommands": false,
"excludedCommands": ["git"],
"network": {
"allowLocalBinding": false,
"allowedDomains": ["registry.npmjs.org", "github.com"],
"allowAllUnixSockets": false,
"allowUnixSockets": []
},
"enableWeakerNestedSandbox": false
}
}
沙箱配置将在第三章详细讲解。
以下是一个适合中型团队的项目级settings.json模板:
{
"permissions": {
"defaultMode": "acceptEdits",
"allow": [
"Bash(npm run *)",
"Bash(npx *)",
"Bash(git *)",
"Bash(node *)",
"Bash(cat *)",
"Bash(ls *)",
"Bash(pwd)",
"Read",
"Grep",
"Glob",
"WebFetch"
],
"deny": [
"Bash(rm -rf /)",
"Bash(rm -rf ~)",
"Bash(sudo *)",
"Bash(chmod 777 *)"
],
"ask": [
"Bash(*)"
]
},
"env": {
"NODE_ENV": "development"
},
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "npx prettier --write $CLAUDE_FILE_PATH 2>/dev/null || true"
}
]
}
],
"Stop": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "npm test 2>&1 | tail -20"
}
]
}
]
},
"additionalDirectories": ["../shared-lib"],
"spinnerTipsEnabled": false
}
常见问题:settings.json格式错误导致Claude Code无法启动?用 cat settings.json | python3 -m json.tool 验证JSON格式。
权限规则的核心是工具名 + 模式匹配的语法:
ToolName(pattern)
基础语法规则:
| 规则 | 含义 |
|---|---|
"Read" |
允许/禁止所有文件读取 |
"Bash" |
允许/禁止所有Bash命令 |
"Bash(npm test *)" |
匹配以npm test开头的命令 |
"Bash(git *)" |
匹配所有git命令 |
"Edit" |
允许/禁止所有文件编辑 |
"MCP" |
允许/禁止所有MCP工具调用 |
通配符规则:
- * 匹配任意字符序列
- 多个模式用 | 分隔:"Edit|Write" 同时匹配两种工具
- 模式区分大小写
评估顺序:deny → ask → allow。第一条匹配的规则生效。
flowchart TD
A["工具调用请求"] --> B{"匹配deny规则?"}
B -->|是| C["❌ 拒绝执行"]
B -->|否| D{"匹配ask规则?"}
D -->|是| E["🔔 弹出确认对话框"]
D -->|否| F{"匹配allow规则?"}
F -->|是| G["✅ 自动执行"]
F -->|否| H{"权限模式?"}
H -->|default| E
H -->|bypassPermissions| G
H -->|plan| I["❌ 拒绝(plan模式不可写入)"]
style C fill:#e74c3c,color:#fff
style G fill:#27ae60,color:#fff
style E fill:#f39c12,color:#fff
不同的工具有不同的权限语法:
{
"allow": [
"Bash(npm run lint)",
"Bash(npm test *)",
"Bash(git status)",
"Bash(git diff *)",
"Bash(git log *)",
"Bash(python3 *)"
],
"deny": [
"Bash(rm -rf *)",
"Bash(sudo *)",
"Bash(curl * | bash)",
"Bash(wget * -O * | bash)"
]
}
进阶技巧:Bash规则支持复合命令检测。Bash(git *) 会匹配 git status && git diff,因为命令以 git 开头。
{
"allow": [
"Read",
"Glob",
"Grep"
],
"deny": [
"Write(.env*)",
"Edit(.env*)",
"Write(*credentials*)",
"Write(*secret*)"
]
}
{
"allow": [
"mcp__github__*",
"mcp__database__query"
],
"deny": [
"mcp__database__drop*"
]
}
沙箱是Claude Code最强大的安全防线。启用后,所有Bash命令在受限环境中执行:
Docker沙箱(推荐用于生产环境):
{
"sandbox": {
"enabled": true,
"autoAllowBashIfSandboxed": true,
"network": {
"allowedDomains": [
"registry.npmjs.org",
"github.com",
"api.github.com"
],
"allowLocalBinding": false
}
}
}
沙箱配置字段详解:
| 字段 | 类型 | 默认值 | 说明 |
|---|---|---|---|
enabled |
boolean | false | 是否启用沙箱 |
autoAllowBashIfSandboxed |
boolean | false | 沙箱内Bash命令自动批准 |
allowUnsandboxedCommands |
boolean | false | 允许部分命令在沙箱外运行 |
excludedCommands |
array | [] | 不受沙箱限制的命令列表 |
network.allowedDomains |
array | [] | 允许访问的域名白名单 |
network.allowLocalBinding |
boolean | false | 允许本地端口绑定 |
network.allowUnixSockets |
array | [] | 允许的Unix socket路径 |
network.allowAllUnixSockets |
boolean | false | 允许所有Unix socket |
network.httpProxyPort |
number | null | HTTP代理端口 |
network.socksProxyPort |
number | null | SOCKS代理端口 |
enableWeakerNestedSandbox |
boolean | false | 允许在已有沙箱内使用更弱的沙箱 |
三种安全级别配置对比:
graph TB
subgraph "Lax - 宽松模式"
L1["✅ Bash命令自由执行"]
L2["✅ 无沙箱限制"]
L3["✅ 仅禁止bypass模式"]
end
subgraph "Strict - 严格模式"
S1["🔔 所有Bash需确认"]
S2["❌ 禁止WebSearch/WebFetch"]
S3["❌ 禁止用户自定义hooks"]
S4["❌ 禁止用户自定义权限规则"]
end
subgraph "Sandbox - 沙箱模式"
X1["🔒 Bash在沙箱内执行"]
X2["🔒 网络白名单限制"]
X3["❌ 禁止用户自定义权限规则"]
end
L1 --- L2 --- L3
S1 --- S2 --- S3 --- S4
X1 --- X2 --- X3
Anthropic官方提供的三种预设配置:
宽松配置 (settings-lax.json):
{
"permissions": {
"disableBypassPermissionsMode": "disable"
},
"strictKnownMarketplaces": []
}
严格配置 (settings-strict.json):
{
"permissions": {
"disableBypassPermissionsMode": "disable",
"ask": ["Bash"],
"deny": ["WebSearch", "WebFetch"]
},
"allowManagedPermissionRulesOnly": true,
"allowManagedHooksOnly": true,
"strictKnownMarketplaces": []
}
沙箱配置 (settings-bash-sandbox.json):
{
"allowManagedPermissionRulesOnly": true,
"sandbox": {
"enabled": true,
"autoAllowBashIfSandboxed": false,
"allowUnsandboxedCommands": false,
"network": {
"allowLocalBinding": false,
"allowedDomains": []
}
}
}
在Claude Code交互会话中,/permissions 命令提供了一个可视化界面来管理权限:
> /permissions
Permission Rules (from settings.json)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ ALLOW Bash(npm test *) — project settings
✅ ALLOW Bash(git *) — project settings
✅ ALLOW Read — user settings
🔔 ASK Bash(*) — project settings
❌ DENY Bash(rm -rf *) — project settings
❌ DENY Bash(sudo *) — managed settings
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
每条规则右侧标注了来源层级,方便排查冲突。
Hooks是Claude Code的自动化核心,支持在30+个生命周期节点触发自定义逻辑:
flowchart LR
subgraph "会话生命周期"
A["SessionStart"] --> B["InstructionsLoaded"]
B --> C["UserPromptSubmit"]
C --> D["PreToolUse"]
D --> E["PostToolUse"]
E --> F["PostToolBatch"]
F --> G["Stop"]
G --> C
end
subgraph "特殊事件"
H["PermissionRequest"]
I["PermissionDenied"]
J["Notification"]
K["SubagentStart"]
L["SubagentStop"]
M["SessionEnd"]
end
style A fill:#3498db,color:#fff
style G fill:#e74c3c,color:#fff
style M fill:#2c3e50,color:#fff
最常用的六大Hook事件:
| 事件 | 触发时机 | 典型用途 |
|---|---|---|
SessionStart |
会话开始 | 环境变量设置、依赖检查 |
PreToolUse |
工具调用前 | 拦截危险操作、注入上下文 |
PostToolUse |
工具调用后 | 自动格式化、代码检查 |
PostToolBatch |
批量工具调用完成 | 批量验证 |
Stop |
Claude完成响应 | 运行测试套件 |
Notification |
发送通知时 | 集成Slack/Discord |
{
"hooks": {
"<EventName>": [
{
"matcher": "<ToolPattern>",
"hooks": [
{
"type": "command",
"command": "your-shell-command"
}
]
}
]
}
}
command(Shell命令)、http(HTTP请求)、prompt(LLM提示)文件被编辑后自动运行Prettier:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "npx prettier --write \"$CLAUDE_FILE_PATH\" 2>/dev/null || true"
}
]
}
]
}
}
预期行为:Claude每次编辑文件后,Prettier自动格式化该文件。$CLAUDE_FILE_PATH 是Claude Code注入的环境变量,指向被操作的文件。
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "npx eslint \"$CLAUDE_FILE_PATH\" --fix 2>&1 | head -30"
}
]
}
]
}
}
{
"hooks": {
"Stop": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "cd $PROJECT_DIR && npm test 2>&1 | tail -30"
}
]
}
]
}
}
注意:Stop hook在每次Claude完成响应时触发。如果你的测试套件很慢,考虑只在关键修改后手动运行测试。
阻止Claude写入敏感文件:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "FILE=\"$CLAUDE_FILE_PATH\"; if echo \"$FILE\" | grep -qE '\\.(env|key|pem|p12)$|credentials|secret'; then echo 'BLOCK: Sensitive file detected' >&2; exit 2; fi"
}
]
}
]
}
}
关键机制:Hook返回exit code 2会阻止工具调用执行,并向Claude传递拒绝原因。exit code 0允许执行,exit code 1允许执行但输出会作为上下文传给Claude。
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "git add \"$CLAUDE_FILE_PATH\" 2>/dev/null || true"
}
]
}
]
}
}
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "curl -s -X POST \"$SLACK_WEBHOOK_URL\" -H 'Content-type: application/json' --data '{\"text\":\"Claude Code: $CLAUDE_NOTIFICATION\"}'"
}
]
}
]
}
}
除了Shell命令,Hook还支持HTTP请求:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "http",
"url": "http://localhost:8080/validate",
"headers": {
"Authorization": "Bearer $VALIDATION_TOKEN"
}
}
]
}
]
}
}
长时间运行的任务可以配置为异步执行:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "npm run build 2>&1 | tail -10",
"async": true
}
]
}
]
}
}
异步Hook不会阻塞Claude的响应,结果会在后台收集。
常见问题:Hook中引用的环境变量 $CLAUDE_FILE_PATH 为空?确保你的匹配器正确——只有在工具确实操作了文件时才会注入此变量。
project-root/
├── .claude/
│ ├── settings.json # 项目级共享配置
│ ├── settings.local.json # 项目级个人覆盖(gitignored)
│ ├── CLAUDE.md # 项目级指令(备选位置)
│ ├── rules/ # 条件加载的规则文件
│ │ ├── typescript.md # TypeScript相关规则
│ │ ├── react.md # React相关规则
│ │ └── database.md # 数据库相关规则
│ ├── agents/ # 自定义子Agent
│ │ ├── reviewer.md # 代码审查Agent
│ │ └── architect.md # 架构设计Agent
│ ├── skills/ # 自定义Skills
│ │ └── deploy/
│ │ └── SKILL.md
│ ├── commands/ # 自定义斜杠命令
│ │ └── check.md
│ ├── output-styles/ # 自定义输出样式
│ │ └── concise.md
│ └── auto.md # 自动记忆存储
├── CLAUDE.md # 项目指令(主位置)
├── CLAUDE.local.md # 个人项目指令(gitignored)
└── .mcp.json # MCP服务器配置
CLAUDE.md同样遵循多层加载:
| 文件 | 位置 | 作用域 | Git |
|---|---|---|---|
~/.claude/CLAUDE.md |
用户主目录 | 所有项目 | 否 |
CLAUDE.md |
项目根目录 | 当前项目 | 是 |
.claude/CLAUDE.md |
.claude目录 | 当前项目 | 是 |
CLAUDE.local.md |
项目根目录 | 当前项目、仅自己 | 否 |
所有层级的CLAUDE.md都会被加载(不是覆盖),内容会合并到Claude的系统提示中。
.claude/rules/ 中的文件可以按条件加载——只有当操作涉及特定路径时才激活:
<!-- .claude/rules/typescript.md -->
---
description: TypeScript项目规则
globs: ["**/*.ts", "**/*.tsx"]
---
# TypeScript 规范
- 使用严格模式
- 优先使用 interface 而非 type
- 禁止使用 any
- 导出函数必须有JSDoc注释
globs 字段定义了触发条件,只有Claude操作匹配这些glob模式的文件时,规则才会被注入到上下文。
MCP服务器通过 .mcp.json 配置(项目级)或 ~/.claude.json(用户级):
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
},
"database": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"DATABASE_URL": "${DATABASE_URL}"
}
}
}
}
假设你是一个5人前端团队的负责人,项目是一个Next.js + TypeScript的应用。需要配置Claude Code使得:
# 项目:Next.js电商平台
## 技术栈
- Next.js 15 (App Router)
- TypeScript 5.x
- Tailwind CSS 4
- Prisma ORM
- PostgreSQL
## 代码规范
- 使用函数组件和hooks
- 文件命名:kebab-case
- 组件目录:src/components/
- API路由:src/app/api/
- 数据库操作:src/lib/db.ts
- 禁止直接使用fetch,使用 src/lib/api-client.ts
## 测试
- 测试框架:Vitest + Testing Library
- 运行命令:npm test
- 所有新功能必须有测试
## Git
- 分支命名:feat/xxx, fix/xxx, chore/xxx
- Commit message:Conventional Commits
- 不自动commit,需要手动确认
{
"permissions": {
"defaultMode": "acceptEdits",
"allow": [
"Bash(npm run *)",
"Bash(npx *)",
"Bash(git status)",
"Bash(git diff *)",
"Bash(git log *)",
"Bash(node *)",
"Read",
"Grep",
"Glob"
],
"deny": [
"Bash(rm -rf *)",
"Bash(sudo *)",
"Write(.env*)",
"Write(*credentials*)",
"Write(*secret*)"
],
"ask": [
"Bash(*)"
]
},
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "npx prettier --write \"$CLAUDE_FILE_PATH\" 2>/dev/null || true"
},
{
"type": "command",
"command": "npx eslint \"$CLAUDE_FILE_PATH\" --fix 2>&1 | tail -5"
}
]
}
],
"Stop": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "npm run typecheck 2>&1 | tail -10"
}
]
}
]
},
"additionalDirectories": [],
"spinnerTipsEnabled": false
}
<!-- .claude/rules/api-routes.md -->
---
description: API路由开发规则
globs: ["src/app/api/**/*.ts"]
---
# API路由规则
- 所有API路由必须有输入验证(使用zod)
- 错误处理使用统一的 errorResponse 函数
- 响应格式:{ success: boolean, data?: T, error?: string }
- 必须认证的路由使用 withAuth 中间件包装
<!-- .claude/rules/components.md -->
---
description: React组件开发规则
globs: ["src/components/**/*.tsx"]
---
# 组件规则
- 使用 "use client" 标记客户端组件
- Props使用 interface 定义
- 事件处理函数使用 handle 前缀
- 状态管理优先使用 useState,复杂场景用 zustand
- 每个组件对应一个 .test.tsx 测试文件
每个开发者可以在 .claude/settings.local.json 中添加个人偏好:
{
"model": "claude-opus-4-6",
"outputStyle": "concise",
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"File: $CLAUDE_FILE_PATH\" with title \"Claude Code\"' 2>/dev/null || true"
}
]
}
]
}
}
在CI环境中使用Claude Code,需要特殊配置:
# .github/workflows/claude-review.yml
name: Claude Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
permission_mode: "plan"
settings: |
{
"permissions": {
"defaultMode": "plan",
"deny": ["Bash", "Write", "Edit"]
}
}
CI中使用 plan 模式确保Claude Code只能读取和分析代码,不会做出任何修改。
# 验证配置文件存在且格式正确
find . -name "settings*.json" -o -name "CLAUDE*.md" -o -name "*.mcp.json" | \
while read f; do
echo "=== $f ==="
if [[ "$f" == *.json ]]; then
python3 -m json.tool "$f" > /dev/null && echo "✅ Valid JSON" || echo "❌ Invalid JSON"
else
head -3 "$f"
fi
done
预期输出:
=== ./CLAUDE.md ===
# 项目:Next.js电商平台
=== ./CLAUDE.local.md ===
# 个人项目偏好
=== .claude/settings.json ===
✅ Valid JSON
=== .claude/settings.local.json ===
✅ Valid JSON
企业环境中,IT管理员可以通过MDM(移动设备管理)系统将配置推送到所有开发者的机器上:
| 平台 | 配置位置 | 部署方式 |
|---|---|---|
| macOS | ~/Library/Preferences/com.anthropic.claude-code.plist |
Jamf / Kandji / MDM配置文件 |
| Windows | Registry: HKLM\SOFTWARE\Anthropic\Claude Code |
Intune / Group Policy |
| Linux | /etc/claude-code/managed-settings.json |
配置管理工具 |
{
"permissions": {
"disableBypassPermissionsMode": "disable",
"disableAutoMode": "disable",
"deny": [
"WebSearch",
"WebFetch",
"Bash(curl * | *)",
"Bash(wget * | *)"
],
"ask": [
"Bash(*)"
]
},
"allowManagedPermissionRulesOnly": true,
"allowManagedHooksOnly": true,
"strictKnownMarketplaces": ["https://marketplace.example.com"],
"sandbox": {
"enabled": true,
"autoAllowBashIfSandboxed": false,
"allowUnsandboxedCommands": false,
"network": {
"allowedDomains": [
"registry.npmjs.org",
"github.com",
"internal-npm.company.com"
],
"allowLocalBinding": false
}
}
}
此配置确保:
- bypassPermissions 和 auto 模式被禁用
- 用户无法覆盖权限规则和Hooks
- 只允许安装来自指定市场的插件
- 所有Bash命令在沙箱内执行
- 网络访问限制为公司内部和必要的外部域名
# macOS
defaults read com.anthropic.claude-code
# 在Claude Code中
/config
# 查看 "Managed Settings" 标签页
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 修改settings.json后行为未变 | 更高层级在覆盖 | 检查 /permissions 查看来源 |
| Hook未触发 | matcher不匹配 | 确认工具名大小写 |
| JSON解析失败 | 格式错误 | python3 -m json.tool settings.json |
| 权限拒绝但已配置allow | deny规则优先级更高 | 检查是否有deny规则匹配 |
| MCP服务器连接失败 | 命令路径问题 | 使用绝对路径 |
| 环境变量未生效 | settings中env优先级较低 | 使用系统环境变量 |
# 查看Claude Code实际加载的配置(需要开启verbose模式)
claude --verbose "check config"
# 检查各层级配置文件是否存在
echo "=== User Level ===" && cat ~/.claude/settings.json 2>/dev/null || echo "Not found"
echo "=== Project Level ===" && cat .claude/settings.json 2>/dev/null || echo "Not found"
echo "=== Local Override ===" && cat .claude/settings.local.json 2>/dev/null || echo "Not found"
flowchart TD
A["配置行为异常"] --> B{"是权限问题?"}
B -->|是| C["运行 /permissions"]
C --> D["检查规则来源层级"]
D --> E["调整对应层级配置"]
B -->|否| F{"是Hook问题?"}
F -->|是| G["检查 /hooks 菜单"]
G --> H["验证matcher和命令"]
H --> I["手动运行Hook命令测试"]
F -->|否| J{"是环境变量?"}
J -->|是| K["检查 settings.json env 字段"]
K --> L["对比系统环境变量"]
J -->|否| M["检查CLAUDE.md加载"]
M --> N["确认文件位置和格式"]
Claude Code的配置体系可以用一个矩阵来总结:
| 维度 | 机制 | 核心文件 |
|---|---|---|
| 指令 | CLAUDE.md多层合并 | CLAUDE.md, .claude/rules/*.md |
| 权限 | deny→ask→allow规则链 | settings.json permissions字段 |
| 安全 | 沙箱隔离+网络白名单 | settings.json sandbox字段 |
| 自动化 | 30+生命周期事件钩子 | settings.json hooks字段 |
| 扩展 | MCP协议连接外部工具 | .mcp.json |
| 治理 | 五层优先级+托管配置 | managed-settings.json |
配置Claude Code不是一次性工作,而是随着团队成熟度逐步演进的过程:
[!tip] 51学通信知识星球 星主:爱卫生(微信:gprshome201101)——公众号「51学通信」创办者,19 年通信行业运维与讲师经验,著有《GPRS网络信令实例详解》《EPC原理与实践》《5G核心网原理与实践》三本纸质书(各大电商平台有售)。 星球定位:深耕 5G 核心网、IMS、NFV/AI、云原生等 ICT 领域,主打运维岗位与信令分析。 当前规模:5200 篇主题 / 990 个回答,198 元/年。 加入福利:加入星球后请加爱卫生微信,拉您进知识星球年度陪伴与答疑群——不限量回复您的各种问题,另有群内分享。 AI 加持:51学通信知识星球已作为 skill 接入 WorkBuddy,使用 deepseek-4-flash 在海量星球帖子中精准找贴、找视频、找 FAQ 和案例,做总结、找文档和 PPT 等场景全覆盖。
