SpyBara
Go Premium

Documentation 2026-05-07 22:59 UTC to 2026-05-08 22:00 UTC

29 files changed +2,201 −1,646. View all changes and history on the product overview
2026
Sun 31 06:39 Sat 30 06:23 Fri 29 06:38 Thu 28 06:37 Wed 27 06:42 Tue 26 06:33 Sun 24 06:25 Sat 23 06:18 Fri 22 06:33 Thu 21 06:36 Wed 20 06:35 Tue 19 06:34 Mon 18 23:59 Sun 17 01:01 Fri 15 22:58 Thu 14 17:02 Wed 13 23:01 Tue 12 22:57 Mon 11 23:00 Sun 10 23:03 Sat 9 04:57 Fri 8 22:00 Thu 7 22:59 Tue 5 23:00 Mon 4 22:58 Sat 2 18:14 Fri 1 18:19
Details

14 14 

15## 使用 settingSources 控制文件系统设置15## 使用 settingSources 控制文件系统设置

16 16 

17设置源选项(Python 中的 [`setting_sources`](/zh-CN/agent-sdk/python#claude-agent-options)、TypeScript 中的 [`settingSources`](/zh-CN/agent-sdk/typescript#setting-source))控制 SDK 加载哪些基于文件系统的设置。传递显式列表以选择加入特定源,或传递空数组以禁用用户、项目和本地设置。17设置源选项(Python 中的 [`setting_sources`](/zh-CN/agent-sdk/python#claudeagentoptions)、TypeScript 中的 [`settingSources`](/zh-CN/agent-sdk/typescript#settingsource))控制 SDK 加载哪些基于文件系统的设置。传递显式列表以选择加入特定源,或传递空数组以禁用用户、项目和本地设置。

18 18 

19此示例通过将 `settingSources` 设置为 `["user", "project"]` 来加载用户级和项目级设置:19此示例通过将 `settingSources` 设置为 `["user", "project"]` 来加载用户级和项目级设置:

20 20 


65 ```65 ```

66</CodeGroup>66</CodeGroup>

67 67 

68每个源从特定位置加载设置,其中 `<cwd>` 是您通过 `cwd` 选项传递的工作目录(如果未设置则为进程的当前目录)。有关完整的类型定义,请参阅 [`SettingSource`](/zh-CN/agent-sdk/typescript#setting-source)(TypeScript)或 [`SettingSource`](/zh-CN/agent-sdk/python#setting-source)(Python)。68每个源从特定位置加载设置,其中 `<cwd>` 是您通过 `cwd` 选项传递的工作目录,或者如果未设置则为进程的当前目录。有关完整的类型定义,请参阅 [`SettingSource`](/zh-CN/agent-sdk/typescript#settingsource)(TypeScript)或 [`SettingSource`](/zh-CN/agent-sdk/python#settingsource)(Python)。

69 69 

70| 源 | 加载的内容 | 位置 |70| 源 | 加载的内容 | 位置 |

71| :---------- | :---------------------------------------------------------------------- | :----------------------------------------------------------- |71| :---------- | :---------------------------------------------------------------------- | :----------------------------------------------------------- |


119 119 

120Skills 是 markdown 文件,为您的代理提供专业知识和可调用的工作流。与 `CLAUDE.md`(每个会话都加载)不同,skills 按需加载。代理在启动时接收 skill 描述,并在相关时加载完整内容。120Skills 是 markdown 文件,为您的代理提供专业知识和可调用的工作流。与 `CLAUDE.md`(每个会话都加载)不同,skills 按需加载。代理在启动时接收 skill 描述,并在相关时加载完整内容。

121 121 

122Skills 通过 `settingSources` 从文件系统中发现。使用默认选项用户和项目 skills 会自动加载当您不指定 `allowedTools` 时,`Skill` 工具默认启用如果您使用 `allowedTools` 允许列表请明确包含 `"Skill"`。122Skills 通过 `settingSources` 从文件系统中发现。当 `query()` 上的 `skills` 选项被省略时发现的用户和项目 skills 会被启用,Skill 工具可用,与 CLI 行为相匹配要控制启用哪些 skills,请将 `skills` 作为 `"all"`、skill 名称列表或 `[]` 传递以禁用所有SDK 在设置 `skills` 时会自动启用 Skill 工具因此您无需将其添加到 `allowedTools`。

123 123 

124<CodeGroup>124<CodeGroup>

125 ```python Python theme={null}125 ```python Python theme={null}


131 prompt="Review this PR using our code review checklist",131 prompt="Review this PR using our code review checklist",

132 options=ClaudeAgentOptions(132 options=ClaudeAgentOptions(

133 setting_sources=["user", "project"],133 setting_sources=["user", "project"],

134 allowed_tools=["Skill", "Read", "Grep", "Glob"],134 skills="all",

135 allowed_tools=["Read", "Grep", "Glob"],

135 ),136 ),

136 ):137 ):

137 if isinstance(message, ResultMessage) and message.subtype == "success":138 if isinstance(message, ResultMessage) and message.subtype == "success":


147 prompt: "Review this PR using our code review checklist",148 prompt: "Review this PR using our code review checklist",

148 options: {149 options: {

149 settingSources: ["user", "project"],150 settingSources: ["user", "project"],

150 allowedTools: ["Skill", "Read", "Grep", "Glob"]151 skills: "all",

152 allowedTools: ["Read", "Grep", "Glob"]

151 }153 }

152 })) {154 })) {

153 if (message.type === "result" && message.subtype === "success") {155 if (message.type === "result" && message.subtype === "success") {


260| 您想要... | 使用 | SDK 表面 |262| 您想要... | 使用 | SDK 表面 |

261| :-------------------------------------- | :--------------------------------------- | :------------------------------------------------------ |263| :-------------------------------------- | :--------------------------------------- | :------------------------------------------------------ |

262| 设置代理始终遵循的项目约定 | [CLAUDE.md](/zh-CN/memory) | `settingSources: ["project"]` 自动加载它 |264| 设置代理始终遵循的项目约定 | [CLAUDE.md](/zh-CN/memory) | `settingSources: ["project"]` 自动加载它 |

263| 为代理提供它在相关时加载的参考材料 | [Skills](/zh-CN/agent-sdk/skills) | `settingSources` + `allowedTools: ["Skill"]` |265| 为代理提供它在相关时加载的参考材料 | [Skills](/zh-CN/agent-sdk/skills) | `settingSources` + `skills` 选项 |

264| 运行可重用的工作流(部署、审查、发布) | [用户可调用的 skills](/zh-CN/agent-sdk/skills) | `settingSources` + `allowedTools: ["Skill"]` |266| 运行可重用的工作流(部署、审查、发布) | [用户可调用的 skills](/zh-CN/agent-sdk/skills) | `settingSources` + `skills` 选项 |

265| 将隔离的子任务委托给新的上下文(研究、审查) | [子代理](/zh-CN/agent-sdk/subagents) | `agents` 参数 + `allowedTools: ["Agent"]` |267| 将隔离的子任务委托给新的上下文(研究、审查) | [子代理](/zh-CN/agent-sdk/subagents) | `agents` 参数 + `allowedTools: ["Agent"]` |

266| 协调多个 Claude Code 实例,具有共享任务列表和直接的代理间消息传递 | [代理团队](/zh-CN/agent-teams) | 不直接通过 SDK 选项配置。代理团队是一个 CLI 功能,其中一个会话充当团队负责人,协调独立队友之间的工作 |268| 协调多个 Claude Code 实例,具有共享任务列表和直接的代理间消息传递 | [代理团队](/zh-CN/agent-teams) | 不直接通过 SDK 选项配置。代理团队是一个 CLI 功能,其中一个会话充当团队负责人,协调独立队友之间的工作 |

267| 在工具调用上运行确定性逻辑(审计、阻止、转换) | [Hooks](/zh-CN/agent-sdk/hooks) | `hooks` 参数带回调,或通过 `settingSources` 加载的 shell 脚本 |269| 在工具调用上运行确定性逻辑(审计、阻止、转换) | [Hooks](/zh-CN/agent-sdk/hooks) | `hooks` 参数带回调,或通过 `settingSources` 加载的 shell 脚本 |

agent-sdk/mcp.md +772 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 使用 MCP 连接外部工具

6 

7> 配置 MCP 服务器以扩展您的代理的外部工具。涵盖传输类型、大型工具集的工具搜索、身份验证和错误处理。

8 

9[Model Context Protocol (MCP)](https://modelcontextprotocol.io/docs/getting-started/intro) 是一个开放标准,用于将 AI 代理连接到外部工具和数据源。使用 MCP,您的代理可以查询数据库、与 Slack 和 GitHub 等 API 集成,以及连接到其他服务,而无需编写自定义工具实现。

10 

11MCP 服务器可以作为本地进程运行、通过 HTTP 连接或直接在您的 SDK 应用程序中执行。

12 

13<Note>

14 本页面涵盖 Agent SDK 的 MCP 配置。要将 MCP 服务器添加到 Claude Code CLI 以便在每个项目中加载,请参阅 [MCP 安装范围](/zh-CN/mcp#mcp-installation-scopes)。

15</Note>

16 

17## 快速开始

18 

19此示例使用 [HTTP 传输](#httpsse-servers) 连接到 [Claude Code 文档](https://code.claude.com/docs) MCP 服务器,并使用 [`allowedTools`](#allow-mcp-tools) 与通配符来允许来自服务器的所有工具。

20 

21<CodeGroup>

22 ```typescript TypeScript theme={null}

23 import { query } from "@anthropic-ai/claude-agent-sdk";

24 

25 for await (const message of query({

26 prompt: "Use the docs MCP server to explain what hooks are in Claude Code",

27 options: {

28 mcpServers: {

29 "claude-code-docs": {

30 type: "http",

31 url: "https://code.claude.com/docs/mcp"

32 }

33 },

34 allowedTools: ["mcp__claude-code-docs__*"]

35 }

36 })) {

37 if (message.type === "result" && message.subtype === "success") {

38 console.log(message.result);

39 }

40 }

41 ```

42 

43 ```python Python theme={null}

44 import asyncio

45 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

46 

47 

48 async def main():

49 options = ClaudeAgentOptions(

50 mcp_servers={

51 "claude-code-docs": {

52 "type": "http",

53 "url": "https://code.claude.com/docs/mcp",

54 }

55 },

56 allowed_tools=["mcp__claude-code-docs__*"],

57 )

58 

59 async for message in query(

60 prompt="Use the docs MCP server to explain what hooks are in Claude Code",

61 options=options,

62 ):

63 if isinstance(message, ResultMessage) and message.subtype == "success":

64 print(message.result)

65 

66 

67 asyncio.run(main())

68 ```

69</CodeGroup>

70 

71代理连接到文档服务器,搜索有关 hooks 的信息,并返回结果。

72 

73## 添加 MCP 服务器

74 

75您可以在调用 `query()` 时在代码中配置 MCP 服务器,或在通过 [`settingSources`](#from-a-config-file) 加载的 `.mcp.json` 文件中配置。

76 

77### 在代码中

78 

79在 `mcpServers` 选项中直接传递 MCP 服务器:

80 

81<CodeGroup>

82 ```typescript TypeScript theme={null}

83 import { query } from "@anthropic-ai/claude-agent-sdk";

84 

85 for await (const message of query({

86 prompt: "List files in my project",

87 options: {

88 mcpServers: {

89 filesystem: {

90 command: "npx",

91 args: ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]

92 }

93 },

94 allowedTools: ["mcp__filesystem__*"]

95 }

96 })) {

97 if (message.type === "result" && message.subtype === "success") {

98 console.log(message.result);

99 }

100 }

101 ```

102 

103 ```python Python theme={null}

104 import asyncio

105 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

106 

107 

108 async def main():

109 options = ClaudeAgentOptions(

110 mcp_servers={

111 "filesystem": {

112 "command": "npx",

113 "args": [

114 "-y",

115 "@modelcontextprotocol/server-filesystem",

116 "/Users/me/projects",

117 ],

118 }

119 },

120 allowed_tools=["mcp__filesystem__*"],

121 )

122 

123 async for message in query(prompt="List files in my project", options=options):

124 if isinstance(message, ResultMessage) and message.subtype == "success":

125 print(message.result)

126 

127 

128 asyncio.run(main())

129 ```

130</CodeGroup>

131 

132### 从配置文件

133 

134在项目根目录创建一个 `.mcp.json` 文件。当启用 `project` 设置源时,该文件会被选中,这对默认 `query()` 选项是默认的。如果您显式设置 `settingSources`,请包含 `"project"` 以便加载此文件:

135 

136```json theme={null}

137{

138 "mcpServers": {

139 "filesystem": {

140 "command": "npx",

141 "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]

142 }

143 }

144}

145```

146 

147## 允许 MCP 工具

148 

149MCP 工具需要明确的权限才能让 Claude 使用它们。没有权限,Claude 会看到工具可用,但无法调用它们。

150 

151### 工具命名约定

152 

153MCP 工具遵循命名模式 `mcp__<server-name>__<tool-name>`。例如,名为 `"github"` 的 GitHub 服务器与 `list_issues` 工具变成 `mcp__github__list_issues`。

154 

155### 使用 allowedTools 授予访问权限

156 

157使用 `allowedTools` 指定 Claude 可以使用哪些 MCP 工具:

158 

159```typescript hidelines={1,-1} theme={null}

160const _ = {

161 options: {

162 mcpServers: {

163 // your servers

164 },

165 allowedTools: [

166 "mcp__github__*", // All tools from the github server

167 "mcp__db__query", // Only the query tool from db server

168 "mcp__slack__send_message" // Only send_message from slack server

169 ]

170 }

171};

172```

173 

174通配符 (`*`) 让您允许来自服务器的所有工具,而无需逐个列出每一个。

175 

176<Note>

177 **对于 MCP 访问,优先使用 `allowedTools` 而不是权限模式。** `permissionMode: "acceptEdits"` 不会自动批准 MCP 工具(仅文件编辑和文件系统 Bash 命令)。`permissionMode: "bypassPermissions"` 确实会自动批准 MCP 工具,但也会禁用所有其他安全提示,这比必要的范围更广。`allowedTools` 中的通配符仅授予您想要的 MCP 服务器,没有其他。请参阅 [权限模式](/zh-CN/agent-sdk/permissions#permission-modes) 以获得完整比较。

178</Note>

179 

180### 发现可用工具

181 

182要查看 MCP 服务器提供的工具,请检查服务器的文档或连接到服务器并检查 `system` init 消息:

183 

184```typescript theme={null}

185for await (const message of query({ prompt: "...", options })) {

186 if (message.type === "system" && message.subtype === "init") {

187 console.log("Available MCP tools:", message.mcp_servers);

188 }

189}

190```

191 

192## 传输类型

193 

194MCP 服务器使用不同的传输协议与您的代理通信。检查服务器的文档以查看它支持哪种传输:

195 

196* 如果文档给您一个**要运行的命令**(如 `npx @modelcontextprotocol/server-github`),请使用 stdio

197* 如果文档给您一个 **URL**,请使用 HTTP 或 SSE

198* 如果您在代码中构建自己的工具,请使用 SDK MCP 服务器

199 

200### stdio 服务器

201 

202通过 stdin/stdout 通信的本地进程。对于在同一台机器上运行的 MCP 服务器,请使用此选项:

203 

204<Tabs>

205 <Tab title="在代码中">

206 <CodeGroup>

207 ```typescript TypeScript hidelines={1,-1} theme={null}

208 const _ = {

209 options: {

210 mcpServers: {

211 github: {

212 command: "npx",

213 args: ["-y", "@modelcontextprotocol/server-github"],

214 env: {

215 GITHUB_TOKEN: process.env.GITHUB_TOKEN

216 }

217 }

218 },

219 allowedTools: ["mcp__github__list_issues", "mcp__github__search_issues"]

220 }

221 };

222 ```

223 

224 ```python Python theme={null}

225 options = ClaudeAgentOptions(

226 mcp_servers={

227 "github": {

228 "command": "npx",

229 "args": ["-y", "@modelcontextprotocol/server-github"],

230 "env": {"GITHUB_TOKEN": os.environ["GITHUB_TOKEN"]},

231 }

232 },

233 allowed_tools=["mcp__github__list_issues", "mcp__github__search_issues"],

234 )

235 ```

236 </CodeGroup>

237 </Tab>

238 

239 <Tab title=".mcp.json">

240 ```json theme={null}

241 {

242 "mcpServers": {

243 "github": {

244 "command": "npx",

245 "args": ["-y", "@modelcontextprotocol/server-github"],

246 "env": {

247 "GITHUB_TOKEN": "${GITHUB_TOKEN}"

248 }

249 }

250 }

251 }

252 ```

253 </Tab>

254</Tabs>

255 

256### HTTP/SSE 服务器

257 

258对于云托管的 MCP 服务器和远程 API,请使用 HTTP 或 SSE:

259 

260<Tabs>

261 <Tab title="在代码中">

262 <CodeGroup>

263 ```typescript TypeScript hidelines={1,-1} theme={null}

264 const _ = {

265 options: {

266 mcpServers: {

267 "remote-api": {

268 type: "sse",

269 url: "https://api.example.com/mcp/sse",

270 headers: {

271 Authorization: `Bearer ${process.env.API_TOKEN}`

272 }

273 }

274 },

275 allowedTools: ["mcp__remote-api__*"]

276 }

277 };

278 ```

279 

280 ```python Python theme={null}

281 options = ClaudeAgentOptions(

282 mcp_servers={

283 "remote-api": {

284 "type": "sse",

285 "url": "https://api.example.com/mcp/sse",

286 "headers": {"Authorization": f"Bearer {os.environ['API_TOKEN']}"},

287 }

288 },

289 allowed_tools=["mcp__remote-api__*"],

290 )

291 ```

292 </CodeGroup>

293 </Tab>

294 

295 <Tab title=".mcp.json">

296 ```json theme={null}

297 {

298 "mcpServers": {

299 "remote-api": {

300 "type": "sse",

301 "url": "https://api.example.com/mcp/sse",

302 "headers": {

303 "Authorization": "Bearer ${API_TOKEN}"

304 }

305 }

306 }

307 }

308 ```

309 </Tab>

310</Tabs>

311 

312对于 HTTP(非流式),请改用 `"type": "http"`。

313 

314### SDK MCP 服务器

315 

316直接在应用程序代码中定义自定义工具,而不是运行单独的服务器进程。有关实现详情,请参阅 [自定义工具指南](/zh-CN/agent-sdk/custom-tools)。

317 

318## MCP 工具搜索

319 

320当您配置了许多 MCP 工具时,工具定义可能会消耗上下文窗口的很大一部分。工具搜索通过从上下文中隐藏工具定义并仅加载 Claude 每轮需要的工具来解决此问题。

321 

322工具搜索默认启用。有关配置选项和详情,请参阅 [工具搜索](/zh-CN/agent-sdk/tool-search)。

323 

324有关更多详情,包括最佳实践和将工具搜索与自定义 SDK 工具一起使用,请参阅 [工具搜索指南](/zh-CN/agent-sdk/tool-search)。

325 

326## 身份验证

327 

328大多数 MCP 服务器需要身份验证才能访问外部服务。通过服务器配置中的环境变量传递凭据。

329 

330### 通过环境变量传递凭据

331 

332使用 `env` 字段将 API 密钥、令牌和其他凭据传递给 MCP 服务器:

333 

334<Tabs>

335 <Tab title="在代码中">

336 <CodeGroup>

337 ```typescript TypeScript hidelines={1,-1} theme={null}

338 const _ = {

339 options: {

340 mcpServers: {

341 github: {

342 command: "npx",

343 args: ["-y", "@modelcontextprotocol/server-github"],

344 env: {

345 GITHUB_TOKEN: process.env.GITHUB_TOKEN

346 }

347 }

348 },

349 allowedTools: ["mcp__github__list_issues"]

350 }

351 };

352 ```

353 

354 ```python Python theme={null}

355 options = ClaudeAgentOptions(

356 mcp_servers={

357 "github": {

358 "command": "npx",

359 "args": ["-y", "@modelcontextprotocol/server-github"],

360 "env": {"GITHUB_TOKEN": os.environ["GITHUB_TOKEN"]},

361 }

362 },

363 allowed_tools=["mcp__github__list_issues"],

364 )

365 ```

366 </CodeGroup>

367 </Tab>

368 

369 <Tab title=".mcp.json">

370 ```json theme={null}

371 {

372 "mcpServers": {

373 "github": {

374 "command": "npx",

375 "args": ["-y", "@modelcontextprotocol/server-github"],

376 "env": {

377 "GITHUB_TOKEN": "${GITHUB_TOKEN}"

378 }

379 }

380 }

381 }

382 ```

383 

384 `${GITHUB_TOKEN}` 语法在运行时展开环境变量。

385 </Tab>

386</Tabs>

387 

388有关带有调试日志的完整工作示例,请参阅 [从存储库列出问题](#list-issues-from-a-repository)。

389 

390### 远程服务器的 HTTP 标头

391 

392对于 HTTP 和 SSE 服务器,直接在服务器配置中传递身份验证标头:

393 

394<Tabs>

395 <Tab title="在代码中">

396 <CodeGroup>

397 ```typescript TypeScript hidelines={1,-1} theme={null}

398 const _ = {

399 options: {

400 mcpServers: {

401 "secure-api": {

402 type: "http",

403 url: "https://api.example.com/mcp",

404 headers: {

405 Authorization: `Bearer ${process.env.API_TOKEN}`

406 }

407 }

408 },

409 allowedTools: ["mcp__secure-api__*"]

410 }

411 };

412 ```

413 

414 ```python Python theme={null}

415 options = ClaudeAgentOptions(

416 mcp_servers={

417 "secure-api": {

418 "type": "http",

419 "url": "https://api.example.com/mcp",

420 "headers": {"Authorization": f"Bearer {os.environ['API_TOKEN']}"},

421 }

422 },

423 allowed_tools=["mcp__secure-api__*"],

424 )

425 ```

426 </CodeGroup>

427 </Tab>

428 

429 <Tab title=".mcp.json">

430 ```json theme={null}

431 {

432 "mcpServers": {

433 "secure-api": {

434 "type": "http",

435 "url": "https://api.example.com/mcp",

436 "headers": {

437 "Authorization": "Bearer ${API_TOKEN}"

438 }

439 }

440 }

441 }

442 ```

443 

444 `${API_TOKEN}` 语法在运行时展开环境变量。

445 </Tab>

446</Tabs>

447 

448### OAuth2 身份验证

449 

450[MCP 规范支持 OAuth 2.1](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization) 用于授权。SDK 不会自动处理 OAuth 流程,但您可以在应用程序中完成 OAuth 流程后通过标头传递访问令牌:

451 

452<CodeGroup>

453 ```typescript TypeScript theme={null}

454 // After completing OAuth flow in your app

455 const accessToken = await getAccessTokenFromOAuthFlow();

456 

457 const options = {

458 mcpServers: {

459 "oauth-api": {

460 type: "http",

461 url: "https://api.example.com/mcp",

462 headers: {

463 Authorization: `Bearer ${accessToken}`

464 }

465 }

466 },

467 allowedTools: ["mcp__oauth-api__*"]

468 };

469 ```

470 

471 ```python Python theme={null}

472 # After completing OAuth flow in your app

473 access_token = await get_access_token_from_oauth_flow()

474 

475 options = ClaudeAgentOptions(

476 mcp_servers={

477 "oauth-api": {

478 "type": "http",

479 "url": "https://api.example.com/mcp",

480 "headers": {"Authorization": f"Bearer {access_token}"},

481 }

482 },

483 allowed_tools=["mcp__oauth-api__*"],

484 )

485 ```

486</CodeGroup>

487 

488## 示例

489 

490### 从存储库列出问题

491 

492此示例连接到 [GitHub MCP 服务器](https://github.com/modelcontextprotocol/servers/tree/main/src/github) 以列出最近的问题。该示例包括调试日志以验证 MCP 连接和工具调用。

493 

494在运行之前,创建一个具有 `repo` 范围的 [GitHub 个人访问令牌](https://github.com/settings/tokens) 并将其设置为环境变量:

495 

496```bash theme={null}

497export GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx

498```

499 

500<CodeGroup>

501 ```typescript TypeScript theme={null}

502 import { query } from "@anthropic-ai/claude-agent-sdk";

503 

504 for await (const message of query({

505 prompt: "List the 3 most recent issues in anthropics/claude-code",

506 options: {

507 mcpServers: {

508 github: {

509 command: "npx",

510 args: ["-y", "@modelcontextprotocol/server-github"],

511 env: {

512 GITHUB_TOKEN: process.env.GITHUB_TOKEN

513 }

514 }

515 },

516 allowedTools: ["mcp__github__list_issues"]

517 }

518 })) {

519 // Verify MCP server connected successfully

520 if (message.type === "system" && message.subtype === "init") {

521 console.log("MCP servers:", message.mcp_servers);

522 }

523 

524 // Log when Claude calls an MCP tool

525 if (message.type === "assistant") {

526 for (const block of message.message.content) {

527 if (block.type === "tool_use" && block.name.startsWith("mcp__")) {

528 console.log("MCP tool called:", block.name);

529 }

530 }

531 }

532 

533 // Print the final result

534 if (message.type === "result" && message.subtype === "success") {

535 console.log(message.result);

536 }

537 }

538 ```

539 

540 ```python Python theme={null}

541 import asyncio

542 import os

543 from claude_agent_sdk import (

544 query,

545 ClaudeAgentOptions,

546 ResultMessage,

547 SystemMessage,

548 AssistantMessage,

549 )

550 

551 

552 async def main():

553 options = ClaudeAgentOptions(

554 mcp_servers={

555 "github": {

556 "command": "npx",

557 "args": ["-y", "@modelcontextprotocol/server-github"],

558 "env": {"GITHUB_TOKEN": os.environ["GITHUB_TOKEN"]},

559 }

560 },

561 allowed_tools=["mcp__github__list_issues"],

562 )

563 

564 async for message in query(

565 prompt="List the 3 most recent issues in anthropics/claude-code",

566 options=options,

567 ):

568 # Verify MCP server connected successfully

569 if isinstance(message, SystemMessage) and message.subtype == "init":

570 print("MCP servers:", message.data.get("mcp_servers"))

571 

572 # Log when Claude calls an MCP tool

573 if isinstance(message, AssistantMessage):

574 for block in message.content:

575 if hasattr(block, "name") and block.name.startswith("mcp__"):

576 print("MCP tool called:", block.name)

577 

578 # Print the final result

579 if isinstance(message, ResultMessage) and message.subtype == "success":

580 print(message.result)

581 

582 

583 asyncio.run(main())

584 ```

585</CodeGroup>

586 

587### 查询数据库

588 

589此示例使用 [Postgres MCP 服务器](https://github.com/modelcontextprotocol/servers/tree/main/src/postgres) 查询数据库。连接字符串作为参数传递给服务器。代理自动发现数据库架构、编写 SQL 查询并返回结果:

590 

591<CodeGroup>

592 ```typescript TypeScript theme={null}

593 import { query } from "@anthropic-ai/claude-agent-sdk";

594 

595 // Connection string from environment variable

596 const connectionString = process.env.DATABASE_URL;

597 

598 for await (const message of query({

599 // Natural language query - Claude writes the SQL

600 prompt: "How many users signed up last week? Break it down by day.",

601 options: {

602 mcpServers: {

603 postgres: {

604 command: "npx",

605 // Pass connection string as argument to the server

606 args: ["-y", "@modelcontextprotocol/server-postgres", connectionString]

607 }

608 },

609 // Allow only read queries, not writes

610 allowedTools: ["mcp__postgres__query"]

611 }

612 })) {

613 if (message.type === "result" && message.subtype === "success") {

614 console.log(message.result);

615 }

616 }

617 ```

618 

619 ```python Python theme={null}

620 import asyncio

621 import os

622 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

623 

624 

625 async def main():

626 # Connection string from environment variable

627 connection_string = os.environ["DATABASE_URL"]

628 

629 options = ClaudeAgentOptions(

630 mcp_servers={

631 "postgres": {

632 "command": "npx",

633 # Pass connection string as argument to the server

634 "args": [

635 "-y",

636 "@modelcontextprotocol/server-postgres",

637 connection_string,

638 ],

639 }

640 },

641 # Allow only read queries, not writes

642 allowed_tools=["mcp__postgres__query"],

643 )

644 

645 # Natural language query - Claude writes the SQL

646 async for message in query(

647 prompt="How many users signed up last week? Break it down by day.",

648 options=options,

649 ):

650 if isinstance(message, ResultMessage) and message.subtype == "success":

651 print(message.result)

652 

653 

654 asyncio.run(main())

655 ```

656</CodeGroup>

657 

658## 错误处理

659 

660MCP 服务器可能因各种原因连接失败:服务器进程可能未安装、凭据可能无效,或远程服务器可能无法访问。

661 

662SDK 在每个查询开始时发出一个 `system` 消息,子类型为 `init`。此消息包括每个 MCP 服务器的连接状态。检查 `status` 字段以在代理开始工作之前检测连接失败:

663 

664<CodeGroup>

665 ```typescript TypeScript theme={null}

666 import { query } from "@anthropic-ai/claude-agent-sdk";

667 

668 for await (const message of query({

669 prompt: "Process data",

670 options: {

671 mcpServers: {

672 "data-processor": dataServer

673 }

674 }

675 })) {

676 if (message.type === "system" && message.subtype === "init") {

677 const failedServers = message.mcp_servers.filter((s) => s.status !== "connected");

678 

679 if (failedServers.length > 0) {

680 console.warn("Failed to connect:", failedServers);

681 }

682 }

683 

684 if (message.type === "result" && message.subtype === "error_during_execution") {

685 console.error("Execution failed");

686 }

687 }

688 ```

689 

690 ```python Python theme={null}

691 import asyncio

692 from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage, ResultMessage

693 

694 

695 async def main():

696 options = ClaudeAgentOptions(mcp_servers={"data-processor": data_server})

697 

698 async for message in query(prompt="Process data", options=options):

699 if isinstance(message, SystemMessage) and message.subtype == "init":

700 failed_servers = [

701 s

702 for s in message.data.get("mcp_servers", [])

703 if s.get("status") != "connected"

704 ]

705 

706 if failed_servers:

707 print(f"Failed to connect: {failed_servers}")

708 

709 if (

710 isinstance(message, ResultMessage)

711 and message.subtype == "error_during_execution"

712 ):

713 print("Execution failed")

714 

715 

716 asyncio.run(main())

717 ```

718</CodeGroup>

719 

720## 故障排除

721 

722### 服务器显示"失败"状态

723 

724检查 `init` 消息以查看哪些服务器连接失败:

725 

726```typescript theme={null}

727if (message.type === "system" && message.subtype === "init") {

728 for (const server of message.mcp_servers) {

729 if (server.status === "failed") {

730 console.error(`Server ${server.name} failed to connect`);

731 }

732 }

733}

734```

735 

736常见原因:

737 

738* **缺少环境变量**:确保设置了所需的令牌和凭据。对于 stdio 服务器,检查 `env` 字段是否与服务器期望的匹配。

739* **服务器未安装**:对于 `npx` 命令,验证包存在且 Node.js 在您的 PATH 中。

740* **无效的连接字符串**:对于数据库服务器,验证连接字符串格式以及数据库是否可访问。

741* **网络问题**:对于远程 HTTP/SSE 服务器,检查 URL 是否可达以及任何防火墙是否允许连接。

742 

743### 工具未被调用

744 

745如果 Claude 看到工具但不使用它们,请检查您是否已使用 `allowedTools` 授予权限:

746 

747```typescript hidelines={1,-1} theme={null}

748const _ = {

749 options: {

750 mcpServers: {

751 // your servers

752 },

753 allowedTools: ["mcp__servername__*"] // Required for Claude to use the tools

754 }

755};

756```

757 

758### 连接超时

759 

760MCP SDK 对服务器连接的默认超时为 60 秒。如果您的服务器需要更长时间才能启动,连接将失败。对于需要更多启动时间的服务器,请考虑:

761 

762* 使用更轻量级的服务器(如果可用)

763* 在启动代理之前预热服务器

764* 检查服务器日志以了解缓慢初始化的原因

765 

766## 相关资源

767 

768* **[自定义工具指南](/zh-CN/agent-sdk/custom-tools)**:构建您自己的 MCP 服务器,与您的 SDK 应用程序在进程中运行

769* **[权限](/zh-CN/agent-sdk/permissions)**:使用 `allowedTools` 和 `disallowedTools` 控制您的代理可以使用哪些 MCP 工具

770* **[TypeScript SDK 参考](/zh-CN/agent-sdk/typescript)**:完整的 API 参考,包括 MCP 配置选项

771* **[Python SDK 参考](/zh-CN/agent-sdk/python)**:完整的 API 参考,包括 MCP 配置选项

772* **[MCP 服务器目录](https://github.com/modelcontextprotocol/servers)**:浏览可用的 MCP 服务器,用于数据库、API 等

Details

834| `plugins` | `list[SdkPluginConfig]` | `[]` | 从本地路径加载自定义插件。见 [Plugins](/zh-CN/agent-sdk/plugins) 了解详情 |834| `plugins` | `list[SdkPluginConfig]` | `[]` | 从本地路径加载自定义插件。见 [Plugins](/zh-CN/agent-sdk/plugins) 了解详情 |

835| `sandbox` | [`SandboxSettings`](#sandboxsettings) ` \| None` | `None` | 以编程方式配置沙箱行为。见 [沙箱设置](#sandboxsettings) 了解详情 |835| `sandbox` | [`SandboxSettings`](#sandboxsettings) ` \| None` | `None` | 以编程方式配置沙箱行为。见 [沙箱设置](#sandboxsettings) 了解详情 |

836| `setting_sources` | `list[SettingSource] \| None` | `None`(CLI 默认值:所有源) | 控制加载哪些文件系统设置。传递 `[]` 以禁用用户、项目和本地设置。无论如何都会加载托管策略设置。见 [使用 Claude Code 功能](/zh-CN/agent-sdk/claude-code-features#what-settingsources-does-not-control) |836| `setting_sources` | `list[SettingSource] \| None` | `None`(CLI 默认值:所有源) | 控制加载哪些文件系统设置。传递 `[]` 以禁用用户、项目和本地设置。无论如何都会加载托管策略设置。见 [使用 Claude Code 功能](/zh-CN/agent-sdk/claude-code-features#what-settingsources-does-not-control) |

837| `skills` | `list[str] \| Literal["all"] \| None` | `None` | 会话可用的技能。传递 `"all"` 以启用每个发现的技能,或传递技能名称列表。设置时,SDK 会自动启用 Skill 工具,无需在 `allowed_tools` 中列出。见 [Skills](/zh-CN/agent-sdk/skills) |

837| `max_thinking_tokens` | `int \| None` | `None` | *已弃用* - 思考块的最大令牌数。改用 `thinking` |838| `max_thinking_tokens` | `int \| None` | `None` | *已弃用* - 思考块的最大令牌数。改用 `thinking` |

838| `thinking` | [`ThinkingConfig`](#thinkingconfig) ` \| None` | `None` | 控制扩展思考行为。优先于 `max_thinking_tokens` |839| `thinking` | [`ThinkingConfig`](#thinkingconfig) ` \| None` | `None` | 控制扩展思考行为。优先于 `max_thinking_tokens` |

839| `effort` | `Literal["low", "medium", "high", "xhigh", "max"] \| None` | `None` | 思考深度的努力级别 |840| `effort` | `Literal["low", "medium", "high", "xhigh", "max"] \| None` | `None` | 思考深度的努力级别 |

agent-sdk/sessions.md +324 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# 使用会话

6 

7> 会话如何保持代理对话历史记录,以及何时使用 continue、resume 和 fork 返回到之前的运行。

8 

9会话是 SDK 在代理工作时积累的对话历史记录。它包含您的提示、代理进行的每个工具调用、每个工具结果和每个响应。SDK 会自动将其写入磁盘,以便您稍后可以返回到它。

10 

11返回到会话意味着代理具有之前的完整上下文:它已经读取的文件、它已经执行的分析、它已经做出的决定。您可以提出后续问题、从中断中恢复或分支以尝试不同的方法。

12 

13<Note>

14 会话保持**对话**,而不是文件系统。要快照和还原代理所做的文件更改,请使用[文件检查点](/zh-CN/agent-sdk/file-checkpointing)。

15</Note>

16 

17本指南涵盖如何为您的应用选择正确的方法、自动跟踪会话的 SDK 接口、如何捕获会话 ID 以及手动使用 `resume` 和 `fork` 的方法,以及关于在主机之间恢复会话需要了解的内容。

18 

19## 选择一种方法

20 

21您需要多少会话处理取决于应用的形状。当您发送应该共享上下文的多个提示时,会话管理就会发挥作用。在单个 `query()` 调用中,代理已经根据需要进行了尽可能多的轮次,权限提示和 `AskUserQuestion` 是[在循环中处理的](/zh-CN/agent-sdk/user-input)(它们不会结束调用)。

22 

23| 您正在构建的内容 | 使用什么 |

24| :------------------------------ | :------------------------------------------------------------------------------------------------------------ |

25| 一次性任务:单个提示,无后续 | 无需额外操作。一个 `query()` 调用可以处理它。 |

26| 在一个进程中进行多轮聊天 | [`ClaudeSDKClient`(Python)或 `continue: true`(TypeScript)](#automatic-session-management)。SDK 为您跟踪会话,无需 ID 处理。 |

27| 在进程重启后从中断处继续 | `continue_conversation=True`(Python)/ `continue: true`(TypeScript)。恢复目录中最近的会话,无需 ID。 |

28| 恢复特定的过去会话(不是最近的) | 捕获会话 ID 并将其传递给 `resume`。 |

29| 尝试替代方法而不丢失原始方法 | Fork 会话。 |

30| 无状态任务,不希望任何内容写入磁盘(仅 TypeScript) | 设置 [`persistSession: false`](/zh-CN/agent-sdk/typescript#options)。会话仅在调用期间存在于内存中。Python 始终保持到磁盘。 |

31 

32### Continue、resume 和 fork

33 

34Continue、resume 和 fork 是您在 `query()` 上设置的选项字段(Python 中的 [`ClaudeAgentOptions`](/zh-CN/agent-sdk/python#claudeagentoptions),TypeScript 中的 [`Options`](/zh-CN/agent-sdk/typescript#options))。

35 

36**Continue** 和 **resume** 都会选择现有会话并添加到其中。区别在于它们如何找到该会话:

37 

38* **Continue** 在当前目录中查找最近的会话。您无需跟踪任何内容。当您的应用一次运行一个对话时效果很好。

39* **Resume** 采用特定的会话 ID。您跟踪 ID。当您有多个会话(例如,多用户应用中每个用户一个)或想要返回到不是最近的会话时需要。

40 

41**Fork** 不同:它创建一个新会话,从原始会话历史记录的副本开始。原始会话保持不变。使用 fork 尝试不同的方向,同时保持返回的选项。

42 

43## 自动会话管理

44 

45两个 SDK 都提供了一个接口,可以跨调用为您跟踪会话状态,因此您无需手动传递 ID。将这些用于单个进程中的多轮对话。

46 

47### Python:`ClaudeSDKClient`

48 

49[`ClaudeSDKClient`](/zh-CN/agent-sdk/python#claudesdkclient) 在内部处理会话 ID。每次调用 `client.query()` 都会自动继续同一会话。调用 [`client.receive_response()`](/zh-CN/agent-sdk/python#claudesdkclient) 以迭代当前查询的消息。客户端必须用作异步上下文管理器。

50 

51此示例针对同一 `client` 运行两个查询。第一个要求代理分析一个模块;第二个要求它重构该模块。因为两个调用都通过同一客户端实例进行,第二个查询具有来自第一个查询的完整上下文,无需任何显式 `resume` 或会话 ID:

52 

53```python Python theme={null}

54import asyncio

55from claude_agent_sdk import (

56 ClaudeSDKClient,

57 ClaudeAgentOptions,

58 AssistantMessage,

59 ResultMessage,

60 TextBlock,

61)

62 

63 

64def print_response(message):

65 """Print only the human-readable parts of a message."""

66 if isinstance(message, AssistantMessage):

67 for block in message.content:

68 if isinstance(block, TextBlock):

69 print(block.text)

70 elif isinstance(message, ResultMessage):

71 cost = (

72 f"${message.total_cost_usd:.4f}"

73 if message.total_cost_usd is not None

74 else "N/A"

75 )

76 print(f"[done: {message.subtype}, cost: {cost}]")

77 

78 

79async def main():

80 options = ClaudeAgentOptions(

81 allowed_tools=["Read", "Edit", "Glob", "Grep"],

82 )

83 

84 async with ClaudeSDKClient(options=options) as client:

85 # First query: client captures the session ID internally

86 await client.query("Analyze the auth module")

87 async for message in client.receive_response():

88 print_response(message)

89 

90 # Second query: automatically continues the same session

91 await client.query("Now refactor it to use JWT")

92 async for message in client.receive_response():

93 print_response(message)

94 

95 

96asyncio.run(main())

97```

98 

99有关何时使用 `ClaudeSDKClient` 与独立 `query()` 函数的详细信息,请参阅 [Python SDK 参考](/zh-CN/agent-sdk/python#choosing-between-query-and-claudesdkclient)。

100 

101### TypeScript:`continue: true`

102 

103稳定的 TypeScript SDK(整个文档中使用的 `query()` 函数,有时称为 V1)没有像 Python 的 `ClaudeSDKClient` 那样的会话保持客户端对象。相反,在每个后续 `query()` 调用上传递 `continue: true`,SDK 会在当前目录中选择最近的会话。无需 ID 跟踪。

104 

105此示例进行两个单独的 `query()` 调用。第一个创建一个新会话;第二个设置 `continue: true`,这告诉 SDK 在磁盘上查找并恢复最近的会话。代理具有来自第一个调用的完整上下文:

106 

107```typescript TypeScript theme={null}

108import { query } from "@anthropic-ai/claude-agent-sdk";

109 

110// First query: creates a new session

111for await (const message of query({

112 prompt: "Analyze the auth module",

113 options: { allowedTools: ["Read", "Glob", "Grep"] }

114})) {

115 if (message.type === "result" && message.subtype === "success") {

116 console.log(message.result);

117 }

118}

119 

120// Second query: continue: true resumes the most recent session

121for await (const message of query({

122 prompt: "Now refactor it to use JWT",

123 options: {

124 continue: true,

125 allowedTools: ["Read", "Edit", "Write", "Glob", "Grep"]

126 }

127})) {

128 if (message.type === "result" && message.subtype === "success") {

129 console.log(message.result);

130 }

131}

132```

133 

134<Note>

135 实验性的 [V2 会话 API](/zh-CN/agent-sdk/typescript-v2-preview)(提供了带有 `send` / `stream` 模式的 `createSession()`)已弃用。使用 V1 `query()` 函数和本页面上描述的会话选项。

136</Note>

137 

138## 将会话选项与 `query()` 一起使用

139 

140### 捕获会话 ID

141 

142Resume 和 fork 需要会话 ID。从结果消息上的 `session_id` 字段读取它(Python 中的 [`ResultMessage`](/zh-CN/agent-sdk/python#resultmessage),TypeScript 中的 [`SDKResultMessage`](/zh-CN/agent-sdk/typescript#sdkresultmessage)),该字段存在于每个结果上,无论成功还是错误。在 TypeScript 中,ID 也可以作为初始化 `SystemMessage` 上的直接字段更早获得;在 Python 中,它嵌套在 `SystemMessage.data` 内。

143 

144<CodeGroup>

145 ```python Python theme={null}

146 import asyncio

147 from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

148 

149 

150 async def main():

151 session_id = None

152 

153 async for message in query(

154 prompt="Analyze the auth module and suggest improvements",

155 options=ClaudeAgentOptions(

156 allowed_tools=["Read", "Glob", "Grep"],

157 ),

158 ):

159 if isinstance(message, ResultMessage):

160 session_id = message.session_id

161 if message.subtype == "success":

162 print(message.result)

163 

164 print(f"Session ID: {session_id}")

165 return session_id

166 

167 

168 session_id = asyncio.run(main())

169 ```

170 

171 ```typescript TypeScript theme={null}

172 import { query } from "@anthropic-ai/claude-agent-sdk";

173 

174 let sessionId: string | undefined;

175 

176 for await (const message of query({

177 prompt: "Analyze the auth module and suggest improvements",

178 options: { allowedTools: ["Read", "Glob", "Grep"] }

179 })) {

180 if (message.type === "result") {

181 sessionId = message.session_id;

182 if (message.subtype === "success") {

183 console.log(message.result);

184 }

185 }

186 }

187 

188 console.log(`Session ID: ${sessionId}`);

189 ```

190</CodeGroup>

191 

192### 按 ID 恢复

193 

194将会话 ID 传递给 `resume` 以返回到该特定会话。代理从会话中断的任何地方继续,具有完整的上下文。恢复的常见原因:

195 

196* **跟进已完成的任务。** 代理已经分析了某些内容;现在您希望它根据该分析采取行动,而无需重新读取文件。

197* **从限制中恢复。** 第一次运行以 `error_max_turns` 或 `error_max_budget_usd` 结束(请参阅[处理结果](/zh-CN/agent-sdk/agent-loop#handle-the-result));使用更高的限制恢复。

198* **重启您的进程。** 您在关闭前捕获了 ID,并希望恢复对话。

199 

200此示例使用后续提示恢复[捕获会话 ID](#capture-the-session-id) 中的会话。因为您正在恢复,代理已经在上下文中具有先前的分析:

201 

202<CodeGroup>

203 ```python Python theme={null}

204 # Earlier session analyzed the code; now build on that analysis

205 async for message in query(

206 prompt="Now implement the refactoring you suggested",

207 options=ClaudeAgentOptions(

208 resume=session_id,

209 allowed_tools=["Read", "Edit", "Write", "Glob", "Grep"],

210 ),

211 ):

212 if isinstance(message, ResultMessage) and message.subtype == "success":

213 print(message.result)

214 ```

215 

216 ```typescript TypeScript theme={null}

217 // Earlier session analyzed the code; now build on that analysis

218 for await (const message of query({

219 prompt: "Now implement the refactoring you suggested",

220 options: {

221 resume: sessionId,

222 allowedTools: ["Read", "Edit", "Write", "Glob", "Grep"]

223 }

224 })) {

225 if (message.type === "result" && message.subtype === "success") {

226 console.log(message.result);

227 }

228 }

229 ```

230</CodeGroup>

231 

232<Tip>

233 如果 `resume` 调用返回新会话而不是预期的历史记录,最常见的原因是不匹配的 `cwd`。会话存储在 `~/.claude/projects/<encoded-cwd>/*.jsonl` 下,其中 `<encoded-cwd>` 是绝对工作目录,每个非字母数字字符都被替换为 `-`(所以 `/Users/me/proj` 变成 `-Users-me-proj`)。如果您的 resume 调用从不同的目录运行,SDK 会在错误的位置查找。会话文件也需要存在于当前机器上。

234</Tip>

235 

236要在机器之间或在无服务器环境中恢复会话,请使用 [`SessionStore` 适配器](/zh-CN/agent-sdk/session-storage)将记录镜像到共享存储。

237 

238### Fork 以探索替代方案

239 

240Forking 创建一个新会话,从原始会话历史记录的副本开始,但从该点开始分支。fork 获得自己的会话 ID;原始的 ID 和历史记录保持不变。您最终会得到两个独立的会话,可以分别恢复。

241 

242<Note>

243 Forking 分支对话历史记录,而不是文件系统。如果 forked 代理编辑文件,这些更改是真实的,对在同一目录中工作的任何会话都可见。要分支和还原文件更改,请使用[文件检查点](/zh-CN/agent-sdk/file-checkpointing)。

244</Note>

245 

246此示例基于[捕获会话 ID](#capture-the-session-id):您已经在 `session_id` 中分析了一个身份验证模块,并希望探索 OAuth2 而不丢失 JWT 焦点线程。第一个块 forks 会话并捕获 fork 的 ID(`forked_id`);第二个块恢复原始 `session_id` 以继续沿着 JWT 路径。您现在有两个会话 ID 指向两个单独的历史记录:

247 

248<CodeGroup>

249 ```python Python theme={null}

250 # Fork: branch from session_id into a new session

251 forked_id = None

252 async for message in query(

253 prompt="Instead of JWT, implement OAuth2 for the auth module",

254 options=ClaudeAgentOptions(

255 resume=session_id,

256 fork_session=True,

257 ),

258 ):

259 if isinstance(message, ResultMessage):

260 forked_id = message.session_id # The fork's ID, distinct from session_id

261 if message.subtype == "success":

262 print(message.result)

263 

264 print(f"Forked session: {forked_id}")

265 

266 # Original session is untouched; resuming it continues the JWT thread

267 async for message in query(

268 prompt="Continue with the JWT approach",

269 options=ClaudeAgentOptions(resume=session_id),

270 ):

271 if isinstance(message, ResultMessage) and message.subtype == "success":

272 print(message.result)

273 ```

274 

275 ```typescript TypeScript theme={null}

276 // Fork: branch from sessionId into a new session

277 let forkedId: string | undefined;

278 

279 for await (const message of query({

280 prompt: "Instead of JWT, implement OAuth2 for the auth module",

281 options: {

282 resume: sessionId,

283 forkSession: true

284 }

285 })) {

286 if (message.type === "system" && message.subtype === "init") {

287 forkedId = message.session_id; // The fork's ID, distinct from sessionId

288 }

289 if (message.type === "result" && message.subtype === "success") {

290 console.log(message.result);

291 }

292 }

293 

294 console.log(`Forked session: ${forkedId}`);

295 

296 // Original session is untouched; resuming it continues the JWT thread

297 for await (const message of query({

298 prompt: "Continue with the JWT approach",

299 options: { resume: sessionId }

300 })) {

301 if (message.type === "result" && message.subtype === "success") {

302 console.log(message.result);

303 }

304 }

305 ```

306</CodeGroup>

307 

308## 跨主机恢复

309 

310会话文件是创建它们的机器的本地文件。要在不同的主机上恢复会话(CI 工作者、临时容器、无服务器),您有两个选项:

311 

312* **移动会话文件。** 从第一次运行中保持 `~/.claude/projects/<encoded-cwd>/<session-id>.jsonl`,并在调用 `resume` 之前将其恢复到新主机上的相同路径。`cwd` 必须匹配。

313* **不依赖会话恢复。** 捕获您需要的结果(分析输出、决定、文件差异)作为应用状态,并将其传递到新会话的提示中。这通常比在周围运送记录文件更强大。

314 

315两个 SDK 都公开了用于枚举磁盘上的会话和读取其消息的函数:TypeScript 中的 [`listSessions()`](/zh-CN/agent-sdk/typescript#listsessions) 和 [`getSessionMessages()`](/zh-CN/agent-sdk/typescript#getsessionmessages),Python 中的 [`list_sessions()`](/zh-CN/agent-sdk/python#list_sessions) 和 [`get_session_messages()`](/zh-CN/agent-sdk/python#get_session_messages)。使用它们来构建自定义会话选择器、清理逻辑或记录查看器。

316 

317两个 SDK 也公开了用于查找和改变单个会话的函数:Python 中的 [`get_session_info()`](/zh-CN/agent-sdk/python#get_session_info)、[`rename_session()`](/zh-CN/agent-sdk/python#rename_session) 和 [`tag_session()`](/zh-CN/agent-sdk/python#tag_session),以及 TypeScript 中的 [`getSessionInfo()`](/zh-CN/agent-sdk/typescript#getsessioninfo)、[`renameSession()`](/zh-CN/agent-sdk/typescript#renamesession) 和 [`tagSession()`](/zh-CN/agent-sdk/typescript#tagsession)。使用它们按标签组织会话或给它们人类可读的标题。

318 

319## 相关资源

320 

321* [代理循环如何工作](/zh-CN/agent-sdk/agent-loop):了解会话中的轮次、消息和上下文累积

322* [文件检查点](/zh-CN/agent-sdk/file-checkpointing):跟踪和还原会话中的文件更改

323* [Python `ClaudeAgentOptions`](/zh-CN/agent-sdk/python#claudeagentoptions):Python 的完整会话选项参考

324* [TypeScript `Options`](/zh-CN/agent-sdk/typescript#options):TypeScript 的完整会话选项参考

agent-sdk/skills.md +314 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# SDK 中的 Agent Skills

6 

7> 使用 Claude Agent SDK 中的 Agent Skills 扩展 Claude 的专业能力

8 

9## 概述

10 

11Agent Skills 通过专业能力扩展 Claude,Claude 会在相关时自动调用这些能力。Skills 被打包为 `SKILL.md` 文件,包含说明、描述和可选的支持资源。

12 

13有关 Skills 的全面信息,包括优势、架构和编写指南,请参阅 [Agent Skills 概述](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview)。

14 

15## Skills 如何与 SDK 配合使用

16 

17使用 Claude Agent SDK 时,Skills 的工作方式如下:

18 

191. **定义为文件系统工件**:在特定目录(`.claude/skills/`)中创建为 `SKILL.md` 文件

202. **从文件系统加载**:Skills 从由 `settingSources`(TypeScript)或 `setting_sources`(Python)管理的文件系统位置加载

213. **自动发现**:加载文件系统设置后,在启动时从用户和项目目录发现 Skill 元数据;触发时加载完整内容

224. **由模型调用**:Claude 根据上下文自动选择何时使用它们

235. **通过 `skills` 选项过滤**:发现的 Skills 默认启用。传递 Skill 名称列表、`"all"` 或 `[]` 来控制会话中可用的 Skills

24 

25与子代理(可以通过编程方式定义)不同,Skills 必须创建为文件系统工件。SDK 不提供用于注册 Skills 的编程 API。

26 

27<Note>

28 Skills 通过文件系统设置源发现。使用默认 `query()` 选项时,SDK 加载用户和项目源,因此 `~/.claude/skills/` 和 `<cwd>/.claude/skills/` 中的 Skills 可用。如果显式设置 `settingSources`,请包含 `'user'` 或 `'project'` 以保持 Skill 发现,或使用 [`plugins` 选项](/zh-CN/agent-sdk/plugins) 从特定路径加载 Skills。

29</Note>

30 

31## 在 SDK 中使用 Skills

32 

33在 `query()` 上设置 `skills` 选项以控制会话中可用的 Skills。省略时,发现的 Skills 启用且 Skill 工具可用,与 CLI 行为匹配。传递 `"all"` 以启用每个发现的 Skill,传递 Skill 名称列表以仅启用那些,或传递 `[]` 以禁用所有。设置 `skills` 时,SDK 自动启用 Skill 工具,因此无需在 `allowedTools` 中列出它。

34 

35配置后,Claude 自动从文件系统发现 Skills 并在与用户请求相关时调用它们。

36 

37<CodeGroup>

38 ```python Python theme={null}

39 import asyncio

40 from claude_agent_sdk import query, ClaudeAgentOptions

41 

42 

43 async def main():

44 options = ClaudeAgentOptions(

45 cwd="/path/to/project", # Project with .claude/skills/

46 setting_sources=["user", "project"], # Load Skills from filesystem

47 skills="all", # Enable every discovered Skill

48 allowed_tools=["Read", "Write", "Bash"],

49 )

50 

51 async for message in query(

52 prompt="Help me process this PDF document", options=options

53 ):

54 print(message)

55 

56 

57 asyncio.run(main())

58 ```

59 

60 ```typescript TypeScript theme={null}

61 import { query } from "@anthropic-ai/claude-agent-sdk";

62 

63 for await (const message of query({

64 prompt: "Help me process this PDF document",

65 options: {

66 cwd: "/path/to/project", // Project with .claude/skills/

67 settingSources: ["user", "project"], // Load Skills from filesystem

68 skills: "all", // Enable every discovered Skill

69 allowedTools: ["Read", "Write", "Bash"]

70 }

71 })) {

72 console.log(message);

73 }

74 ```

75</CodeGroup>

76 

77要仅启用特定 Skills,请传递它们的名称。名称与 `SKILL.md` 中的 `name` 字段或 Skill 的目录名称匹配。对于插件提供的 Skills,使用 `plugin:skill`。

78 

79<CodeGroup>

80 ```python Python theme={null}

81 options = ClaudeAgentOptions(skills=["pdf", "docx"])

82 ```

83 

84 ```typescript TypeScript theme={null}

85 const options = { skills: ["pdf", "docx"] };

86 ```

87</CodeGroup>

88 

89`skills` 选项是上下文过滤器,不是沙箱。未列出的 Skills 对模型隐藏,并被 Skill 工具拒绝,但它们的文件仍在磁盘上,可通过 Read 和 Bash 访问。

90 

91## Skill 位置

92 

93Skills 根据您的 `settingSources`/`setting_sources` 配置从文件系统目录加载:

94 

95* **项目 Skills**(`.claude/skills/`):通过 git 与您的团队共享 - 当 `setting_sources` 包含 `"project"` 时加载

96* **用户 Skills**(`~/.claude/skills/`):跨所有项目的个人 Skills - 当 `setting_sources` 包含 `"user"` 时加载

97* **插件 Skills**:与已安装的 Claude Code 插件捆绑

98 

99## 创建 Skills

100 

101Skills 定义为包含带有 YAML frontmatter 和 Markdown 内容的 `SKILL.md` 文件的目录。`description` 字段确定 Claude 何时调用您的 Skill。

102 

103**示例目录结构**:

104 

105```bash theme={null}

106.claude/skills/processing-pdfs/

107└── SKILL.md

108```

109 

110有关创建 Skills 的完整指导,包括 SKILL.md 结构、多文件 Skills 和示例,请参阅:

111 

112* [Claude Code 中的 Agent Skills](/zh-CN/skills):包含示例的完整指南

113* [Agent Skills 最佳实践](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices):编写指南和命名约定

114 

115## 工具限制

116 

117<Note>

118 SKILL.md 中的 `allowed-tools` frontmatter 字段仅在直接使用 Claude Code CLI 时受支持。**通过 SDK 使用 Skills 时不适用**。

119 

120 使用 SDK 时,通过查询配置中的主 `allowedTools` 选项控制工具访问。

121</Note>

122 

123要在 SDK 应用程序中控制 Skills 的工具访问,使用 `allowedTools` 预先批准特定工具。没有 `canUseTool` 回调时,列表中没有的任何内容都被拒绝:

124 

125<Note>

126 假设第一个示例中的导入语句在以下代码片段中。

127</Note>

128 

129<CodeGroup>

130 ```python Python theme={null}

131 options = ClaudeAgentOptions(

132 setting_sources=["user", "project"], # Load Skills from filesystem

133 skills="all",

134 allowed_tools=["Read", "Grep", "Glob"],

135 )

136 

137 async for message in query(prompt="Analyze the codebase structure", options=options):

138 print(message)

139 ```

140 

141 ```typescript TypeScript theme={null}

142 for await (const message of query({

143 prompt: "Analyze the codebase structure",

144 options: {

145 settingSources: ["user", "project"], // Load Skills from filesystem

146 skills: "all",

147 allowedTools: ["Read", "Grep", "Glob"],

148 permissionMode: "dontAsk" // Deny anything not in allowedTools

149 }

150 })) {

151 console.log(message);

152 }

153 ```

154</CodeGroup>

155 

156## 发现可用的 Skills

157 

158要查看 SDK 应用程序中可用的 Skills,只需询问 Claude:

159 

160<CodeGroup>

161 ```python Python theme={null}

162 options = ClaudeAgentOptions(

163 setting_sources=["user", "project"], # Load Skills from filesystem

164 skills="all",

165 )

166 

167 async for message in query(prompt="What Skills are available?", options=options):

168 print(message)

169 ```

170 

171 ```typescript TypeScript theme={null}

172 for await (const message of query({

173 prompt: "What Skills are available?",

174 options: {

175 settingSources: ["user", "project"], // Load Skills from filesystem

176 skills: "all"

177 }

178 })) {

179 console.log(message);

180 }

181 ```

182</CodeGroup>

183 

184Claude 将根据您当前的工作目录和已安装的插件列出可用的 Skills。

185 

186## 测试 Skills

187 

188通过提出与其描述匹配的问题来测试 Skills:

189 

190<CodeGroup>

191 ```python Python theme={null}

192 options = ClaudeAgentOptions(

193 cwd="/path/to/project",

194 setting_sources=["user", "project"], # Load Skills from filesystem

195 skills="all",

196 allowed_tools=["Read", "Bash"],

197 )

198 

199 async for message in query(prompt="Extract text from invoice.pdf", options=options):

200 print(message)

201 ```

202 

203 ```typescript TypeScript theme={null}

204 for await (const message of query({

205 prompt: "Extract text from invoice.pdf",

206 options: {

207 cwd: "/path/to/project",

208 settingSources: ["user", "project"], // Load Skills from filesystem

209 skills: "all",

210 allowedTools: ["Read", "Bash"]

211 }

212 })) {

213 console.log(message);

214 }

215 ```

216</CodeGroup>

217 

218如果描述与您的请求匹配,Claude 会自动调用相关的 Skill。

219 

220## 故障排除

221 

222### 找不到 Skills

223 

224**检查 settingSources 配置**:Skills 通过 `user` 和 `project` 设置源发现。如果显式设置 `settingSources`/`setting_sources` 并省略这些源,Skills 不会加载:

225 

226<CodeGroup>

227 ```python Python theme={null}

228 # Skills not loaded: setting_sources excludes user and project

229 options = ClaudeAgentOptions(setting_sources=[], skills="all")

230 

231 # Skills loaded: user and project sources included

232 options = ClaudeAgentOptions(

233 setting_sources=["user", "project"],

234 skills="all",

235 )

236 ```

237 

238 ```typescript TypeScript theme={null}

239 // Skills not loaded: settingSources excludes user and project

240 const options = {

241 settingSources: [],

242 skills: "all"

243 };

244 

245 // Skills loaded: user and project sources included

246 const options = {

247 settingSources: ["user", "project"],

248 skills: "all"

249 };

250 ```

251</CodeGroup>

252 

253有关 `settingSources`/`setting_sources` 的更多详情,请参阅 [TypeScript SDK 参考](/zh-CN/agent-sdk/typescript#settingsource) 或 [Python SDK 参考](/zh-CN/agent-sdk/python#settingsource)。

254 

255**检查工作目录**:SDK 相对于 `cwd` 选项加载 Skills。确保它指向包含 `.claude/skills/` 的目录:

256 

257<CodeGroup>

258 ```python Python theme={null}

259 # Ensure your cwd points to the directory containing .claude/skills/

260 options = ClaudeAgentOptions(

261 cwd="/path/to/project", # Must contain .claude/skills/

262 setting_sources=["user", "project"], # Loads skills from these sources

263 skills="all",

264 )

265 ```

266 

267 ```typescript TypeScript theme={null}

268 // Ensure your cwd points to the directory containing .claude/skills/

269 const options = {

270 cwd: "/path/to/project", // Must contain .claude/skills/

271 settingSources: ["user", "project"], // Loads skills from these sources

272 skills: "all"

273 };

274 ```

275</CodeGroup>

276 

277有关完整模式,请参阅上面的"在 SDK 中使用 Skills"部分。

278 

279**验证文件系统位置**:

280 

281```bash theme={null}

282# Check project Skills

283ls .claude/skills/*/SKILL.md

284 

285# Check personal Skills

286ls ~/.claude/skills/*/SKILL.md

287```

288 

289### Skill 未被使用

290 

291**检查 `skills` 选项**:如果传递了 `skills` 列表,确认 Skill 的名称已包含。传递 `[]` 会禁用所有 Skills。

292 

293**检查描述**:确保它具体且包含相关关键字。有关编写有效描述的指导,请参阅 [Agent Skills 最佳实践](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices#writing-effective-descriptions)。

294 

295### 其他故障排除

296 

297有关一般 Skills 故障排除(YAML 语法、调试等),请参阅 [Claude Code Skills 故障排除部分](/zh-CN/skills#troubleshooting)。

298 

299## 相关文档

300 

301### Skills 指南

302 

303* [Claude Code 中的 Agent Skills](/zh-CN/skills):包含创建、示例和故障排除的完整 Skills 指南

304* [Agent Skills 概述](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview):概念概述、优势和架构

305* [Agent Skills 最佳实践](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices):有效 Skills 的编写指南

306* [Agent Skills 食谱](https://platform.claude.com/cookbook/skills-notebooks-01-skills-introduction):示例 Skills 和模板

307 

308### SDK 资源

309 

310* [SDK 中的子代理](/zh-CN/agent-sdk/subagents):具有编程选项的类似文件系统代理

311* [SDK 中的 Slash Commands](/zh-CN/agent-sdk/slash-commands):用户调用的命令

312* [SDK 概述](/zh-CN/agent-sdk/overview):常规 SDK 概念

313* [TypeScript SDK 参考](/zh-CN/agent-sdk/typescript):完整 API 文档

314* [Python SDK 参考](/zh-CN/agent-sdk/python):完整 API 文档

agent-sdk/subagents.md +601 −0 created

Details

1> ## Documentation Index

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.

4 

5# SDK 中的子代理

6 

7> 定义和调用子代理以隔离上下文、并行运行任务,以及在 Claude Agent SDK 应用程序中应用专门的指令。

8 

9子代理是您的主代理可以生成的独立代理实例,用于处理专注的子任务。

10使用子代理来隔离专注子任务的上下文、并行运行多个分析,以及应用专门的指令,而不会使主代理的提示词过于复杂。

11 

12本指南说明如何使用 `agents` 参数在 SDK 中定义和使用子代理。

13 

14## 概述

15 

16您可以通过三种方式创建子代理:

17 

18* **以编程方式**:在您的 `query()` 选项中使用 `agents` 参数([TypeScript](/zh-CN/agent-sdk/typescript#agentdefinition)、[Python](/zh-CN/agent-sdk/python#agentdefinition))

19* **基于文件系统**:在 `.claude/agents/` 目录中将代理定义为 markdown 文件(请参阅[将子代理定义为文件](/zh-CN/sub-agents))

20* **内置通用代理**:Claude 可以随时通过 Agent 工具调用内置的 `general-purpose` 子代理,无需您定义任何内容

21 

22本指南重点介绍编程方法,这是 SDK 应用程序的推荐方法。

23 

24定义子代理时,Claude 根据每个子代理的 `description` 字段确定是否调用它。编写清晰的描述,说明何时应使用子代理,Claude 将自动委派适当的任务。您也可以在提示词中按名称显式请求子代理(例如,"使用代码审查员代理来...")。

25 

26## 使用子代理的好处

27 

28### 上下文隔离

29 

30每个子代理在其自己的新对话中运行。中间工具调用和结果保留在子代理内部;只有其最终消息返回到父代理。请参阅[子代理继承的内容](#what-subagents-inherit)以了解子代理上下文中的确切内容。

31 

32**示例:** `research-assistant` 子代理可以探索数十个文件,而这些内容都不会在主对话中累积。父代理收到的是简洁的摘要,而不是子代理读取的每个文件。

33 

34### 并行化

35 

36多个子代理可以并发运行,大大加快复杂工作流的速度。

37 

38**示例:** 在代码审查期间,您可以同时运行 `style-checker`、`security-scanner` 和 `test-coverage` 子代理,将审查时间从几分钟减少到几秒钟。

39 

40### 专门的指令和知识

41 

42每个子代理都可以有定制的系统提示词,具有特定的专业知识、最佳实践和约束。

43 

44**示例:** `database-migration` 子代理可以具有关于 SQL 最佳实践、回滚策略和数据完整性检查的详细知识,这些在主代理的指令中将是不必要的噪音。

45 

46### 工具限制

47 

48子代理可以限制为特定工具,降低意外操作的风险。

49 

50**示例:** `doc-reviewer` 子代理可能只能访问 Read 和 Grep 工具,确保它可以分析但永远不会意外修改您的文档文件。

51 

52## 创建子代理

53 

54### 以编程方式定义(推荐)

55 

56使用 `agents` 参数直接在代码中定义子代理。此示例创建两个子代理:一个具有只读访问权限的代码审查员和一个可以执行命令的测试运行器。`Agent` 工具必须包含在 `allowedTools` 中,因为 Claude 通过 Agent 工具调用子代理。

57 

58<CodeGroup>

59 ```python Python theme={null}

60 import asyncio

61 from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

62 

63 

64 async def main():

65 async for message in query(

66 prompt="Review the authentication module for security issues",

67 options=ClaudeAgentOptions(

68 # Agent tool is required for subagent invocation

69 allowed_tools=["Read", "Grep", "Glob", "Agent"],

70 agents={

71 "code-reviewer": AgentDefinition(

72 # description tells Claude when to use this subagent

73 description="Expert code review specialist. Use for quality, security, and maintainability reviews.",

74 # prompt defines the subagent's behavior and expertise

75 prompt="""You are a code review specialist with expertise in security, performance, and best practices.

76 

77 When reviewing code:

78 - Identify security vulnerabilities

79 - Check for performance issues

80 - Verify adherence to coding standards

81 - Suggest specific improvements

82 

83 Be thorough but concise in your feedback.""",

84 # tools restricts what the subagent can do (read-only here)

85 tools=["Read", "Grep", "Glob"],

86 # model overrides the default model for this subagent

87 model="sonnet",

88 ),

89 "test-runner": AgentDefinition(

90 description="Runs and analyzes test suites. Use for test execution and coverage analysis.",

91 prompt="""You are a test execution specialist. Run tests and provide clear analysis of results.

92 

93 Focus on:

94 - Running test commands

95 - Analyzing test output

96 - Identifying failing tests

97 - Suggesting fixes for failures""",

98 # Bash access lets this subagent run test commands

99 tools=["Bash", "Read", "Grep"],

100 ),

101 },

102 ),

103 ):

104 if hasattr(message, "result"):

105 print(message.result)

106 

107 

108 asyncio.run(main())

109 ```

110 

111 ```typescript TypeScript theme={null}

112 import { query } from "@anthropic-ai/claude-agent-sdk";

113 

114 for await (const message of query({

115 prompt: "Review the authentication module for security issues",

116 options: {

117 // Agent tool is required for subagent invocation

118 allowedTools: ["Read", "Grep", "Glob", "Agent"],

119 agents: {

120 "code-reviewer": {

121 // description tells Claude when to use this subagent

122 description:

123 "Expert code review specialist. Use for quality, security, and maintainability reviews.",

124 // prompt defines the subagent's behavior and expertise

125 prompt: `You are a code review specialist with expertise in security, performance, and best practices.

126 

127 When reviewing code:

128 - Identify security vulnerabilities

129 - Check for performance issues

130 - Verify adherence to coding standards

131 - Suggest specific improvements

132 

133 Be thorough but concise in your feedback.`,

134 // tools restricts what the subagent can do (read-only here)

135 tools: ["Read", "Grep", "Glob"],

136 // model overrides the default model for this subagent

137 model: "sonnet"

138 },

139 "test-runner": {

140 description:

141 "Runs and analyzes test suites. Use for test execution and coverage analysis.",

142 prompt: `You are a test execution specialist. Run tests and provide clear analysis of results.

143 

144 Focus on:

145 - Running test commands

146 - Analyzing test output

147 - Identifying failing tests

148 - Suggesting fixes for failures`,

149 // Bash access lets this subagent run test commands

150 tools: ["Bash", "Read", "Grep"]

151 }

152 }

153 }

154 })) {

155 if ("result" in message) console.log(message.result);

156 }

157 ```

158</CodeGroup>

159 

160### AgentDefinition 配置

161 

162| 字段 | 类型 | 必需 | 描述 |

163| :---------------- | :---------------------------------------------------------- | :- | :------------------------------------------------------------------------------ |

164| `description` | `string` | 是 | 何时使用此代理的自然语言描述 |

165| `prompt` | `string` | 是 | 代理的系统提示词,定义其角色和行为 |

166| `tools` | `string[]` | 否 | 允许的工具名称数组。如果省略,继承所有工具 |

167| `disallowedTools` | `string[]` | 否 | 要从代理的工具集中移除的工具名称数组 |

168| `model` | `string` | 否 | 此代理的模型覆盖。接受别名,如 `'sonnet'`、`'opus'`、`'haiku'`、`'inherit'`,或完整的模型 ID。如果省略,默认为主模型 |

169| `skills` | `string[]` | 否 | 在启动时预加载到代理上下文中的技能名称列表。未列出的技能仍可通过 Skill 工具调用 |

170| `memory` | `'user' \| 'project' \| 'local'` | 否 | 此代理的内存源 |

171| `mcpServers` | `(string \| object)[]` | 否 | 此代理可用的 MCP 服务器,按名称或内联配置 |

172| `maxTurns` | `number` | 否 | 代理停止前的最大代理轮数 |

173| `background` | `boolean` | 否 | 调用时将此代理作为非阻塞后台任务运行 |

174| `effort` | `'low' \| 'medium' \| 'high' \| 'xhigh' \| 'max' \| number` | 否 | 此代理的推理工作量级别 |

175| `permissionMode` | `PermissionMode` | 否 | 此代理内工具执行的权限模式 |

176 

177在 Python SDK 中,这些字段名称使用 camelCase 以匹配线路格式。有关详细信息,请参阅 [`AgentDefinition` 参考](/zh-CN/agent-sdk/python#agentdefinition)。

178 

179<Note>

180 子代理无法生成自己的子代理。不要在子代理的 `tools` 数组中包含 `Agent`。

181</Note>

182 

183### 基于文件系统的定义(替代方案)

184 

185您也可以在 `.claude/agents/` 目录中将子代理定义为 markdown 文件。有关此方法的详细信息,请参阅 [Claude Code 子代理文档](/zh-CN/sub-agents)。以编程方式定义的代理优先于具有相同名称的基于文件系统的代理。

186 

187<Note>

188 即使不定义自定义子代理,当 `Agent` 在您的 `allowedTools` 中时,Claude 也可以生成内置的 `general-purpose` 子代理。这对于委派研究或探索任务而无需创建专门的代理很有用。

189</Note>

190 

191## 子代理继承的内容

192 

193子代理的上下文窗口从新开始(无父对话),但不是空的。从父代理到子代理的唯一通道是 Agent 工具的提示词字符串,因此请直接在该提示词中包含子代理需要的任何文件路径、错误消息或决策。

194 

195| 子代理接收 | 子代理不接收 |

196| :------------------------------------------------ | :---------------------------------------- |

197| 其自己的系统提示词(`AgentDefinition.prompt`)和 Agent 工具的提示词 | 父代理的对话历史或工具结果 |

198| 项目 CLAUDE.md(通过 `settingSources` 加载) | 预加载的技能内容,除非在 `AgentDefinition.skills` 中列出 |

199| 工具定义(从父代理继承,或 `tools` 中的子集) | 父代理的系统提示词 |

200 

201<Note>

202 父代理逐字接收子代理的最终消息作为 Agent 工具结果,但可能在其自己的响应中总结它。要在面向用户的响应中逐字保留子代理输出,请在您传递给**主** `query()` 调用的提示词或 `systemPrompt` 选项中包含一条指令。

203</Note>

204 

205## 调用子代理

206 

207### 自动调用

208 

209Claude 根据任务和每个子代理的 `description` 自动决定何时调用子代理。例如,如果您定义了一个 `performance-optimizer` 子代理,其描述为"用于查询调优的性能优化专家",当您的提示词提到优化查询时,Claude 将调用它。

210 

211编写清晰、具体的描述,以便 Claude 可以将任务匹配到正确的子代理。

212 

213### 显式调用

214 

215要保证 Claude 使用特定的子代理,请在您的提示词中按名称提及它:

216 

217```text theme={null}

218"Use the code-reviewer agent to check the authentication module"

219```

220 

221这绕过自动匹配并直接调用命名的子代理。

222 

223### 动态代理配置

224 

225您可以根据运行时条件动态创建代理定义。此示例创建一个安全审查员,具有不同的严格级别,对严格审查使用更强大的模型。

226 

227<CodeGroup>

228 ```python Python theme={null}

229 import asyncio

230 from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

231 

232 

233 # Factory function that returns an AgentDefinition

234 # This pattern lets you customize agents based on runtime conditions

235 def create_security_agent(security_level: str) -> AgentDefinition:

236 is_strict = security_level == "strict"

237 return AgentDefinition(

238 description="Security code reviewer",

239 # Customize the prompt based on strictness level

240 prompt=f"You are a {'strict' if is_strict else 'balanced'} security reviewer...",

241 tools=["Read", "Grep", "Glob"],

242 # Key insight: use a more capable model for high-stakes reviews

243 model="opus" if is_strict else "sonnet",

244 )

245 

246 

247 async def main():

248 # The agent is created at query time, so each request can use different settings

249 async for message in query(

250 prompt="Review this PR for security issues",

251 options=ClaudeAgentOptions(

252 allowed_tools=["Read", "Grep", "Glob", "Agent"],

253 agents={

254 # Call the factory with your desired configuration

255 "security-reviewer": create_security_agent("strict")

256 },

257 ),

258 ):

259 if hasattr(message, "result"):

260 print(message.result)

261 

262 

263 asyncio.run(main())

264 ```

265 

266 ```typescript TypeScript theme={null}

267 import { query, type AgentDefinition } from "@anthropic-ai/claude-agent-sdk";

268 

269 // Factory function that returns an AgentDefinition

270 // This pattern lets you customize agents based on runtime conditions

271 function createSecurityAgent(securityLevel: "basic" | "strict"): AgentDefinition {

272 const isStrict = securityLevel === "strict";

273 return {

274 description: "Security code reviewer",

275 // Customize the prompt based on strictness level

276 prompt: `You are a ${isStrict ? "strict" : "balanced"} security reviewer...`,

277 tools: ["Read", "Grep", "Glob"],

278 // Key insight: use a more capable model for high-stakes reviews

279 model: isStrict ? "opus" : "sonnet"

280 };

281 }

282 

283 // The agent is created at query time, so each request can use different settings

284 for await (const message of query({

285 prompt: "Review this PR for security issues",

286 options: {

287 allowedTools: ["Read", "Grep", "Glob", "Agent"],

288 agents: {

289 // Call the factory with your desired configuration

290 "security-reviewer": createSecurityAgent("strict")

291 }

292 }

293 })) {

294 if ("result" in message) console.log(message.result);

295 }

296 ```

297</CodeGroup>

298 

299## 检测子代理调用

300 

301子代理通过 Agent 工具调用。要检测何时调用子代理,请检查 `tool_use` 块,其中 `name` 是 `"Agent"`。来自子代理上下文内的消息包含 `parent_tool_use_id` 字段。

302 

303<Note>

304 工具名称在 Claude Code v2.1.63 中从 `"Task"` 重命名为 `"Agent"`。当前 SDK 版本在 `tool_use` 块中发出 `"Agent"`,但在 `system:init` 工具列表和 `result.permission_denials[].tool_name` 中仍使用 `"Task"`。检查 `block.name` 中的两个值可确保跨 SDK 版本的兼容性。

305</Note>

306 

307此示例遍历流式消息,记录何时调用子代理以及后续消息何时源自该子代理的执行上下文。

308 

309<Note>

310 消息结构在 SDK 之间有所不同。在 Python 中,内容块直接通过 `message.content` 访问。在 TypeScript 中,`SDKAssistantMessage` 包装 Claude API 消息,因此内容通过 `message.message.content` 访问。

311</Note>

312 

313<CodeGroup>

314 ```python Python theme={null}

315 import asyncio

316 from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

317 

318 

319 async def main():

320 async for message in query(

321 prompt="Use the code-reviewer agent to review this codebase",

322 options=ClaudeAgentOptions(

323 allowed_tools=["Read", "Glob", "Grep", "Agent"],

324 agents={

325 "code-reviewer": AgentDefinition(

326 description="Expert code reviewer.",

327 prompt="Analyze code quality and suggest improvements.",

328 tools=["Read", "Glob", "Grep"],

329 )

330 },

331 ),

332 ):

333 # Check for subagent invocation. Match both names: older SDK

334 # versions emitted "Task", current versions emit "Agent".

335 if hasattr(message, "content") and message.content:

336 for block in message.content:

337 if getattr(block, "type", None) == "tool_use" and block.name in (

338 "Task",

339 "Agent",

340 ):

341 print(f"Subagent invoked: {block.input.get('subagent_type')}")

342 

343 # Check if this message is from within a subagent's context

344 if hasattr(message, "parent_tool_use_id") and message.parent_tool_use_id:

345 print(" (running inside subagent)")

346 

347 if hasattr(message, "result"):

348 print(message.result)

349 

350 

351 asyncio.run(main())

352 ```

353 

354 ```typescript TypeScript theme={null}

355 import { query } from "@anthropic-ai/claude-agent-sdk";

356 

357 for await (const message of query({

358 prompt: "Use the code-reviewer agent to review this codebase",

359 options: {

360 allowedTools: ["Read", "Glob", "Grep", "Agent"],

361 agents: {

362 "code-reviewer": {

363 description: "Expert code reviewer.",

364 prompt: "Analyze code quality and suggest improvements.",

365 tools: ["Read", "Glob", "Grep"]

366 }

367 }

368 }

369 })) {

370 const msg = message as any;

371 

372 // Check for subagent invocation. Match both names: older SDK versions

373 // emitted "Task", current versions emit "Agent".

374 for (const block of msg.message?.content ?? []) {

375 if (block.type === "tool_use" && (block.name === "Task" || block.name === "Agent")) {

376 console.log(`Subagent invoked: ${block.input.subagent_type}`);

377 }

378 }

379 

380 // Check if this message is from within a subagent's context

381 if (msg.parent_tool_use_id) {

382 console.log(" (running inside subagent)");

383 }

384 

385 if ("result" in message) {

386 console.log(message.result);

387 }

388 }

389 ```

390</CodeGroup>

391 

392## 恢复子代理

393 

394子代理可以恢复以继续中断的地方。恢复的子代理保留其完整的对话历史,包括所有先前的工具调用、结果和推理。子代理从停止的地方继续,而不是重新开始。

395 

396当子代理完成时,Claude 在 Agent 工具结果中接收其代理 ID。要以编程方式恢复子代理:

397 

3981. **捕获会话 ID**:在第一个查询期间从消息中提取 `session_id`

3992. **提取代理 ID**:从消息内容中解析 `agentId`

4003. **恢复会话**:在第二个查询的选项中传递 `resume: sessionId`,并在您的提示词中包含代理 ID

401 

402<Note>

403 您必须恢复同一会话以访问子代理的记录。默认情况下,每个 `query()` 调用都会启动一个新会话,因此请传递 `resume: sessionId` 以在同一会话中继续。

404 

405 如果您使用的是自定义代理(而不是内置代理),您还需要在两个查询的 `agents` 参数中传递相同的代理定义。

406</Note>

407 

408下面的示例演示了此流程:第一个查询运行子代理并捕获会话 ID 和代理 ID,然后第二个查询恢复会话以提出需要来自第一个分析的上下文的后续问题。

409 

410<CodeGroup>

411 ```typescript TypeScript theme={null}

412 import { query, type SDKMessage } from "@anthropic-ai/claude-agent-sdk";

413 

414 // Helper to extract agentId from message content

415 // Stringify to avoid traversing different block types (TextBlock, ToolResultBlock, etc.)

416 function extractAgentId(message: SDKMessage): string | undefined {

417 if (!("message" in message)) return undefined;

418 // Stringify the content so we can search it without traversing nested blocks

419 const content = JSON.stringify(message.message.content);

420 const match = content.match(/agentId:\s*([a-f0-9-]+)/);

421 return match?.[1];

422 }

423 

424 let agentId: string | undefined;

425 let sessionId: string | undefined;

426 

427 // First invocation - use the Explore agent to find API endpoints

428 for await (const message of query({

429 prompt: "Use the Explore agent to find all API endpoints in this codebase",

430 options: { allowedTools: ["Read", "Grep", "Glob", "Agent"] }

431 })) {

432 // Capture session_id from ResultMessage (needed to resume this session)

433 if ("session_id" in message) sessionId = message.session_id;

434 // Search message content for the agentId (appears in Agent tool results)

435 const extractedId = extractAgentId(message);

436 if (extractedId) agentId = extractedId;

437 // Print the final result

438 if ("result" in message) console.log(message.result);

439 }

440 

441 // Second invocation - resume and ask follow-up

442 if (agentId && sessionId) {

443 for await (const message of query({

444 prompt: `Resume agent ${agentId} and list the top 3 most complex endpoints`,

445 options: { allowedTools: ["Read", "Grep", "Glob", "Agent"], resume: sessionId }

446 })) {

447 if ("result" in message) console.log(message.result);

448 }

449 }

450 ```

451 

452 ```python Python theme={null}

453 import asyncio

454 import json

455 import re

456 from claude_agent_sdk import query, ClaudeAgentOptions

457 

458 

459 def extract_agent_id(text: str) -> str | None:

460 """Extract agentId from Agent tool result text."""

461 match = re.search(r"agentId:\s*([a-f0-9-]+)", text)

462 return match.group(1) if match else None

463 

464 

465 async def main():

466 agent_id = None

467 session_id = None

468 

469 # First invocation - use the Explore agent to find API endpoints

470 async for message in query(

471 prompt="Use the Explore agent to find all API endpoints in this codebase",

472 options=ClaudeAgentOptions(allowed_tools=["Read", "Grep", "Glob", "Agent"]),

473 ):

474 # Capture session_id from ResultMessage (needed to resume this session)

475 if hasattr(message, "session_id"):

476 session_id = message.session_id

477 # Search message content for the agentId (appears in Agent tool results)

478 if hasattr(message, "content"):

479 # Stringify the content so we can search it without traversing nested blocks

480 content_str = json.dumps(message.content, default=str)

481 extracted = extract_agent_id(content_str)

482 if extracted:

483 agent_id = extracted

484 # Print the final result

485 if hasattr(message, "result"):

486 print(message.result)

487 

488 # Second invocation - resume and ask follow-up

489 if agent_id and session_id:

490 async for message in query(

491 prompt=f"Resume agent {agent_id} and list the top 3 most complex endpoints",

492 options=ClaudeAgentOptions(

493 allowed_tools=["Read", "Grep", "Glob", "Agent"], resume=session_id

494 ),

495 ):

496 if hasattr(message, "result"):

497 print(message.result)

498 

499 

500 asyncio.run(main())

501 ```

502</CodeGroup>

503 

504子代理记录独立于主对话而持久存在:

505 

506* **主对话压缩**:当主对话压缩时,子代理记录不受影响。它们存储在单独的文件中。

507* **会话持久性**:子代理记录在其会话内持久存在。您可以通过恢复同一会话在重启 Claude Code 后恢复子代理。

508* **自动清理**:记录根据 `cleanupPeriodDays` 设置进行清理(默认:30 天)。

509 

510## 工具限制

511 

512子代理可以通过 `tools` 字段具有受限的工具访问:

513 

514* **省略该字段**:代理继承所有可用工具(默认)

515* **指定工具**:代理只能使用列出的工具

516 

517此示例创建一个只读分析代理,可以检查代码但无法修改文件或运行命令。

518 

519<CodeGroup>

520 ```python Python theme={null}

521 import asyncio

522 from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

523 

524 

525 async def main():

526 async for message in query(

527 prompt="Analyze the architecture of this codebase",

528 options=ClaudeAgentOptions(

529 allowed_tools=["Read", "Grep", "Glob", "Agent"],

530 agents={

531 "code-analyzer": AgentDefinition(

532 description="Static code analysis and architecture review",

533 prompt="""You are a code architecture analyst. Analyze code structure,

534 identify patterns, and suggest improvements without making changes.""",

535 # Read-only tools: no Edit, Write, or Bash access

536 tools=["Read", "Grep", "Glob"],

537 )

538 },

539 ),

540 ):

541 if hasattr(message, "result"):

542 print(message.result)

543 

544 

545 asyncio.run(main())

546 ```

547 

548 ```typescript TypeScript theme={null}

549 import { query } from "@anthropic-ai/claude-agent-sdk";

550 

551 for await (const message of query({

552 prompt: "Analyze the architecture of this codebase",

553 options: {

554 allowedTools: ["Read", "Grep", "Glob", "Agent"],

555 agents: {

556 "code-analyzer": {

557 description: "Static code analysis and architecture review",

558 prompt: `You are a code architecture analyst. Analyze code structure,

559 identify patterns, and suggest improvements without making changes.`,

560 // Read-only tools: no Edit, Write, or Bash access

561 tools: ["Read", "Grep", "Glob"]

562 }

563 }

564 }

565 })) {

566 if ("result" in message) console.log(message.result);

567 }

568 ```

569</CodeGroup>

570 

571### 常见工具组合

572 

573| 用例 | 工具 | 描述 |

574| :--- | :---------------------------------- | :------------------------ |

575| 只读分析 | `Read`、`Grep`、`Glob` | 可以检查代码但不能修改或执行 |

576| 测试执行 | `Bash`、`Read`、`Grep` | 可以运行命令并分析输出 |

577| 代码修改 | `Read`、`Edit`、`Write`、`Grep`、`Glob` | 完整的读/写访问,无命令执行 |

578| 完全访问 | 所有工具 | 从父代理继承所有工具(省略 `tools` 字段) |

579 

580## 故障排除

581 

582### Claude 不委派给子代理

583 

584如果 Claude 直接完成任务而不是委派给您的子代理:

585 

5861. **包含 Agent 工具**:子代理通过 Agent 工具调用,因此它必须在 `allowedTools` 中

5872. **使用显式提示**:在您的提示词中按名称提及子代理(例如,"使用代码审查员代理来...")

5883. **编写清晰的描述**:准确解释何时应使用子代理,以便 Claude 可以适当地匹配任务

589 

590### 基于文件系统的代理未加载

591 

592在 `.claude/agents/` 中定义的代理仅在启动时加载。如果在 Claude Code 运行时创建新的代理文件,请重启会话以加载它。

593 

594### Windows:长提示词失败

595 

596在 Windows 上,具有非常长提示词的子代理可能因命令行长度限制(8191 个字符)而失败。保持提示词简洁或使用基于文件系统的代理来处理复杂指令。

597 

598## 相关文档

599 

600* [Claude Code 子代理](/zh-CN/sub-agents):包括基于文件系统的定义的全面子代理文档

601* [SDK 概述](/zh-CN/agent-sdk/overview):Claude Agent SDK 入门

Details

358| `sessionStore` | [`SessionStore`](/zh-CN/agent-sdk/session-storage#the-sessionstore-interface) | `undefined` | 将会话记录镜像到外部后端,以便任何主机都可以恢复它们。请参阅[将会话持久化到外部存储](/zh-CN/agent-sdk/session-storage) |358| `sessionStore` | [`SessionStore`](/zh-CN/agent-sdk/session-storage#the-sessionstore-interface) | `undefined` | 将会话记录镜像到外部后端,以便任何主机都可以恢复它们。请参阅[将会话持久化到外部存储](/zh-CN/agent-sdk/session-storage) |

359| `settings` | `string \| Settings` | `undefined` | 内联[设置](/zh-CN/settings)对象或设置文件的路径。填充[优先级顺序](/zh-CN/settings#settings-precedence)中的标志设置层。使用 [`applyFlagSettings()`](#applyflagsettings) 在运行时更改 |359| `settings` | `string \| Settings` | `undefined` | 内联[设置](/zh-CN/settings)对象或设置文件的路径。填充[优先级顺序](/zh-CN/settings#settings-precedence)中的标志设置层。使用 [`applyFlagSettings()`](#applyflagsettings) 在运行时更改 |

360| `settingSources` | [`SettingSource`](#settingsource)`[]` | CLI 默认值(所有源) | 控制加载哪些文件系统设置。传递 `[]` 以禁用用户、项目和本地设置。无论如何都会加载托管策略设置。请参阅[使用 Claude Code 功能](/zh-CN/agent-sdk/claude-code-features#what-settingsources-does-not-control) |360| `settingSources` | [`SettingSource`](#settingsource)`[]` | CLI 默认值(所有源) | 控制加载哪些文件系统设置。传递 `[]` 以禁用用户、项目和本地设置。无论如何都会加载托管策略设置。请参阅[使用 Claude Code 功能](/zh-CN/agent-sdk/claude-code-features#what-settingsources-does-not-control) |

361| `skills` | `string[] \| 'all'` | `undefined` | 会话可用的技能。传递 `'all'` 以启用每个发现的技能,或传递技能名称列表。设置后,SDK 会自动启用 Skill 工具,无需在 `allowedTools` 中列出。请参阅[Skills](/zh-CN/agent-sdk/skills) |

361| `spawnClaudeCodeProcess` | `(options: SpawnOptions) => SpawnedProcess` | `undefined` | 用于生成 Claude Code 进程的自定义函数。用于在 VM、容器或远程环境中运行 Claude Code |362| `spawnClaudeCodeProcess` | `(options: SpawnOptions) => SpawnedProcess` | `undefined` | 用于生成 Claude Code 进程的自定义函数。用于在 VM、容器或远程环境中运行 Claude Code |

362| `stderr` | `(data: string) => void` | `undefined` | stderr 输出的回调 |363| `stderr` | `(data: string) => void` | `undefined` | stderr 输出的回调 |

363| `strictMcpConfig` | `boolean` | `false` | 强制执行严格的 MCP 验证 |364| `strictMcpConfig` | `boolean` | `false` | 强制执行严格的 MCP 验证 |


530| 字段 | 必需 | 描述 |531| 字段 | 必需 | 描述 |

531| :------------------------------------ | :- | :------------------------------------------------------------------------------------------ |532| :------------------------------------ | :- | :------------------------------------------------------------------------------------------ |

532| `description` | 是 | 何时使用此代理的自然语言描述 |533| `description` | 是 | 何时使用此代理的自然语言描述 |

533| `tools` | 否 | 允许的工具名称数组。如果省略,继承父级的所有工具 |534| `tools` | 否 | 允许的工具名称数组。如果省略,继承父级的所有工具。要将 Skills 预加载到代理的上下文中,请使用 `skills` 字段而不是在此处列出 `'Skill'` |

534| `disallowedTools` | 否 | 要为此代理明确禁止的工具名称数组 |535| `disallowedTools` | 否 | 要为此代理明确禁止的工具名称数组 |

535| `prompt` | 是 | 代理的系统提示 |536| `prompt` | 是 | 代理的系统提示 |

536| `model` | 否 | 此代理的模型覆盖。接受别名,如 `'sonnet'`、`'opus'`、`'haiku'`、`'inherit'`,或完整的模型 ID。如果省略或 `'inherit'`,使用主模型 |537| `model` | 否 | 此代理的模型覆盖。接受别名,如 `'sonnet'`、`'opus'`、`'haiku'`、`'inherit'`,或完整的模型 ID。如果省略或 `'inherit'`,使用主模型 |


1176 transcript_path: string;1177 transcript_path: string;

1177 cwd: string;1178 cwd: string;

1178 permission_mode?: string;1179 permission_mode?: string;

1180 effort?: { level: string };

1179 agent_id?: string;1181 agent_id?: string;

1180 agent_type?: string;1182 agent_type?: string;

1181};1183};

Details

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.3> Use this file to discover all available pages before exploring further.

4 4 

5# TypeScript SDK V2 interface (preview)5# TypeScript SDK V2 session API(已弃用)

6 6 

7> 简化的 V2 TypeScript Agent SDK 预览,具有用于多轮对话的基于会话的 send/stream 模式。7> 已弃用的 V2 TypeScript Agent SDK session API 参考,具有用于多轮对话的基于会话的 send/stream 模式。

8 8 

9<Warning>9<Warning>

10 V2 interface 是一个**不稳定的预览版**。在变得稳定之前,API 可能会根据反馈而改变某些功能(如会话分叉)仅在 [V1 SDK](/zh-CN/agent-sdk/typescript) 中可用10 V2 session API 函数 `unstable_v2_createSession`、`unstable_v2_resumeSession` 和 `unstable_v2_prompt` 已弃用,将在未来版本中删除请改用 [V1 `query()` API](/zh-CN/agent-sdk/typescript)。

11</Warning>11</Warning>

12 12 

13V2 Claude Agent TypeScript SDK 消除了对异步生成器和 yield 协调的需求。这使多轮对话更简单,而不是在各轮之间管理生成器状态,每一轮都是一个单独的 `send()`/`stream()` 周期。API 表面简化为三个概念:13V2 是一个实验性的 session API,消除了对异步生成器和 yield 协调的需求。与其在各轮之间管理生成器状态,每一轮都是一个单独的 `send()`/`stream()` 周期。API 表面简化为三个概念:

14 14 

15* `createSession()` / `resumeSession()`:启动或继续对话15* `createSession()` / `resumeSession()`:启动或继续对话

16* `session.send()`:发送消息16* `session.send()`:发送消息


380 380 

381## 功能可用性381## 功能可用性

382 382 

383并非所有 V1 功能在 V2 中都可用。以下功能需要使用 [V1 SDK](/zh-CN/agent-sdk/typescript):383V2 session API 不支持所有 V1 功能。以下功能需要使用 [V1 SDK](/zh-CN/agent-sdk/typescript):

384 384 

385* 会话分叉(`forkSession` 选项)385* 会话分叉(`forkSession` 选项)

386* 某些高级流式输入模式386* 某些高级流式输入模式

387 387 

388## 反馈

389 

390在 V2 interface 变得稳定之前分享您的反馈。通过 [GitHub Issues](https://github.com/anthropics/claude-code/issues) 报告问题和建议。

391 

392## 另请参阅388## 另请参阅

393 389 

394* [TypeScript SDK 参考(V1)](/zh-CN/agent-sdk/typescript) - 完整的 V1 SDK 文档390* [TypeScript SDK 参考(V1)](/zh-CN/agent-sdk/typescript) - 完整的 V1 SDK 文档

agent-teams.md +3 −3

Details

419 419 

420探索用于并行工作和委派的相关方法:420探索用于并行工作和委派的相关方法:

421 421 

422* **轻量级委派**:[subagents](/zh-CN/sub-agents) 在你的会话中为研究或验证生成辅助代理,更适合不需要代理间协调的任务422* **轻量级委派**:[subagents](/zh-CN/sub-agents) 在你的会话中生成辅助代理以进行研究或验证,更适合不需要代理间协调的任务

423* **手动并行会话**:[Git worktrees](/zh-CN/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees) 让你自己运行多个 Claude Code 会话,无需自动化团队协调423* **手动并行会话**:[Git worktrees](/zh-CN/worktrees) 让你自己运行多个 Claude Code 会话,无需自动化团队协调

424* **比较方法**:有关并排分解,请参阅 [subagent vs agent team](/zh-CN/features-overview#compare-similar-features) 比较424* **比较方法**:查看 [subagent vs agent team](/zh-CN/features-overview#compare-similar-features) 比较以获得并排分解

amazon-bedrock.md +1 −111

Details

76 </div>;76 </div>;

77};77};

78 78 

79export const Experiment = ({flag, treatment, children}) => {79<ContactSalesCard surface="bedrock" />

80 const VID_KEY = 'exp_vid';

81 const CONSENT_COUNTRIES = new Set(['AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'RE', 'GP', 'MQ', 'GF', 'YT', 'BL', 'MF', 'PM', 'WF', 'PF', 'NC', 'AW', 'CW', 'SX', 'FO', 'GL', 'AX', 'GB', 'UK', 'AI', 'BM', 'IO', 'VG', 'KY', 'FK', 'GI', 'MS', 'PN', 'SH', 'TC', 'GG', 'JE', 'IM', 'CA', 'BR', 'IN']);

82 const fnv1a = s => {

83 let h = 0x811c9dc5;

84 for (let i = 0; i < s.length; i++) {

85 h ^= s.charCodeAt(i);

86 h += (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24);

87 }

88 return h >>> 0;

89 };

90 const bucket = (seed, vid) => fnv1a(fnv1a(seed + vid) + '') % 10000 < 5000 ? 'control' : 'treatment';

91 const [decision] = useState(() => {

92 const params = new URLSearchParams(location.search);

93 const preBucketed = document.documentElement.dataset['gb_' + flag.replace(/-/g, '_')];

94 const force = params.get('gb-force');

95 if (force) {

96 for (const p of force.split(',')) {

97 const [k, v] = p.split(':');

98 if (k === flag) return {

99 variant: v || 'treatment',

100 track: false

101 };

102 }

103 }

104 if (navigator.globalPrivacyControl) {

105 return {

106 variant: 'control',

107 track: false

108 };

109 }

110 const prefsMatch = document.cookie.match(/(?:^|; )anthropic-consent-preferences=([^;]+)/);

111 if (prefsMatch) {

112 try {

113 if (JSON.parse(decodeURIComponent(prefsMatch[1])).analytics !== true) {

114 return {

115 variant: 'control',

116 track: false

117 };

118 }

119 } catch {

120 return {

121 variant: 'control',

122 track: false

123 };

124 }

125 } else {

126 const country = params.get('country')?.toUpperCase() || (document.cookie.match(/(?:^|; )cf_geo=([A-Z]{2})/) || [])[1];

127 if (!country || CONSENT_COUNTRIES.has(country)) {

128 return {

129 variant: 'control',

130 track: false

131 };

132 }

133 }

134 let vid;

135 try {

136 const ajsMatch = document.cookie.match(/(?:^|; )ajs_anonymous_id=([^;]+)/);

137 if (ajsMatch) {

138 vid = decodeURIComponent(ajsMatch[1]).replace(/^"|"$/g, '');

139 } else {

140 vid = localStorage.getItem(VID_KEY);

141 if (!vid) {

142 vid = crypto.randomUUID();

143 }

144 document.cookie = `ajs_anonymous_id=${vid}; domain=.claude.com; path=/; Secure; SameSite=Lax; max-age=31536000`;

145 }

146 try {

147 localStorage.setItem(VID_KEY, vid);

148 } catch {}

149 } catch {

150 return {

151 variant: 'control',

152 track: false

153 };

154 }

155 const variant = preBucketed === '1' ? 'treatment' : preBucketed === '0' ? 'control' : bucket(flag, vid);

156 return {

157 variant,

158 track: true,

159 vid

160 };

161 });

162 useEffect(() => {

163 if (!decision.track) return;

164 fetch('https://api.anthropic.com/api/event_logging/v2/batch', {

165 method: 'POST',

166 headers: {

167 'Content-Type': 'application/json',

168 'x-service-name': 'claude_code_docs'

169 },

170 body: JSON.stringify({

171 events: [{

172 event_type: 'GrowthbookExperimentEvent',

173 event_data: {

174 device_id: decision.vid,

175 anonymous_id: decision.vid,

176 timestamp: new Date().toISOString(),

177 experiment_id: flag,

178 variation_id: decision.variant === 'treatment' ? 1 : 0,

179 environment: 'production'

180 }

181 }]

182 }),

183 keepalive: true

184 }).catch(() => {});

185 }, []);

186 return decision.variant === 'treatment' ? treatment : children;

187};

188 

189<Experiment flag="docs-contact-sales-cta" treatment={<ContactSalesCard surface="bedrock" />} />

190 80 

191## 前置条件81## 前置条件

192 82 

Details

84| `--permission-mode` | 以指定的 [权限模式](/zh-CN/permission-modes) 开始。接受 `default`、`acceptEdits`、`plan`、`auto`、`dontAsk` 或 `bypassPermissions`。覆盖设置文件中的 `defaultMode` | `claude --permission-mode plan` |84| `--permission-mode` | 以指定的 [权限模式](/zh-CN/permission-modes) 开始。接受 `default`、`acceptEdits`、`plan`、`auto`、`dontAsk` 或 `bypassPermissions`。覆盖设置文件中的 `defaultMode` | `claude --permission-mode plan` |

85| `--permission-prompt-tool` | 指定 MCP 工具以在非交互模式下处理权限提示 | `claude -p --permission-prompt-tool mcp_auth_tool "query"` |85| `--permission-prompt-tool` | 指定 MCP 工具以在非交互模式下处理权限提示 | `claude -p --permission-prompt-tool mcp_auth_tool "query"` |

86| `--plugin-dir` | 仅为此会话从目录或 `.zip` 存档加载插件。每个标志采用一个路径。重复该标志以获取多个插件:`--plugin-dir A --plugin-dir B.zip` | `claude --plugin-dir ./my-plugin` |86| `--plugin-dir` | 仅为此会话从目录或 `.zip` 存档加载插件。每个标志采用一个路径。重复该标志以获取多个插件:`--plugin-dir A --plugin-dir B.zip` | `claude --plugin-dir ./my-plugin` |

87| `--plugin-url` | 仅为此会话从 URL 获取插件 `.zip` 存档。每个标志采用一个 URL。重复该标志以获取多个插件 | `claude --plugin-url https://example.com/plugin.zip` |87| `--plugin-url` | 仅为此会话从 URL 获取插件 `.zip` 存档。重复该标志以获取多个插件,或在单个引用值中传递以空格分隔的 URL | `claude --plugin-url https://example.com/plugin.zip` |

88| `--print`, `-p` | 打印响应而不进入交互模式(请参阅 [Agent SDK 文档](/zh-CN/agent-sdk/overview) 了解编程使用详情) | `claude -p "query"` |88| `--print`, `-p` | 打印响应而不进入交互模式(请参阅 [Agent SDK 文档](/zh-CN/agent-sdk/overview) 了解编程使用详情) | `claude -p "query"` |

89| `--remote` | 在 claude.ai 上创建新的 [网络会话](/zh-CN/claude-code-on-the-web),提供任务描述 | `claude --remote "Fix the login bug"` |89| `--remote` | 在 claude.ai 上创建新的 [网络会话](/zh-CN/claude-code-on-the-web),提供任务描述 | `claude --remote "Fix the login bug"` |

90| `--remote-control`, `--rc` | 启动启用了 [Remote Control](/zh-CN/remote-control#start-a-remote-control-session) 的交互式会话,以便您也可以从 claude.ai 或 Claude 应用控制它。可选地为会话传递名称 | `claude --remote-control "My Project"` |90| `--remote-control`, `--rc` | 启动启用了 [Remote Control](/zh-CN/remote-control#start-a-remote-control-session) 的交互式会话,以便您也可以从 claude.ai 或 Claude 应用控制它。可选地为会话传递名称 | `claude --remote-control "My Project"` |


103| `--tools` | 限制 Claude 可以使用的内置工具。使用 `""` 禁用所有,`"default"` 表示全部,或工具名称如 `"Bash,Edit,Read"` | `claude --tools "Bash,Edit,Read"` |103| `--tools` | 限制 Claude 可以使用的内置工具。使用 `""` 禁用所有,`"default"` 表示全部,或工具名称如 `"Bash,Edit,Read"` | `claude --tools "Bash,Edit,Read"` |

104| `--verbose` | 启用详细日志记录,显示完整的逐轮输出。覆盖此会话的 [`viewMode`](/zh-CN/settings#available-settings) 设置 | `claude --verbose` |104| `--verbose` | 启用详细日志记录,显示完整的逐轮输出。覆盖此会话的 [`viewMode`](/zh-CN/settings#available-settings) 设置 | `claude --verbose` |

105| `--version`, `-v` | 输出版本号 | `claude -v` |105| `--version`, `-v` | 输出版本号 | `claude -v` |

106| `--worktree`, `-w` | 在隔离的 [git worktree](/zh-CN/worktrees) 中启动 Claude,位于 `<repo>/.claude/worktrees/<name>`。如果未给出名称,则自动生成一个 | `claude -w feature-auth` |106| `--worktree`, `-w` | 在隔离的 [git worktree](/zh-CN/worktrees) 中启动 Claude,位于 `<repo>/.claude/worktrees/<name>`。如果未给出名称,则自动生成一个。传递 `#<number>` 或 GitHub 拉取请求 URL 以从 `origin` 获取该 PR 并从其分支 worktree | `claude -w feature-auth` |

107 107 

108### 系统提示标志108### 系统提示标志

109 109 

commands.md +21 −3

Details

12 12 

13命令只在您的消息开头被识别。命令名称后面的文本作为参数传递给它。13命令只在您的消息开头被识别。命令名称后面的文本作为参数传递给它。

14 14 

15下表列出了 Claude Code 中包含的所有命令。标记为 **[Skill](/zh-CN/skills#bundled-skills)** 的条目是捆绑的 skills。它们使用与您自己编写的 skills 相同的机制:一个提示交给 Claude,Claude 也可以在相关时自动调用。其他所有内容都是内置命令,其行为被编码到 CLI 中。要添加您自己的命令,请参阅 [skills](/zh-CN/skills)。15## 典型工作流程中的命令

16 

17大多数命令在会话的特定点很有用,从设置项目到发布更改。

18 

19**首次在存储库中的会话。** 运行 `/init` 以生成启动器 `CLAUDE.md`,然后运行 `/memory` 以完善它。使用 `/mcp` 和 `/agents` 来设置项目需要的任何服务器或子代理,并使用 `/permissions` 来设置您想要的批准规则。

20 

21**在任务期间。** `/plan` 在大型更改前切换到 Plan Mode。`/model` 和 `/effort` 调整您花费的推理量。当对话变长时,`/context` 显示窗口的去向,`/compact` 将其总结下来;使用 `/btw` 进行快速附加说明,不应该增加历史记录。

22 

23**在您发布之前。** `/diff` 显示更改的内容,`/simplify` 审阅最近的文件并应用质量和效率修复,`/review` 或 `/security-review` 进行更深入的只读检查。

16 24 

17并非每个命令都对每个用户显示。可用性取决于您的平台、计划和环境例如,`/desktop` 仅在 macOSWindows 上显示,`/upgrade` 仅在 Pro 和 Max 计划上显示25**在会话之间** `/clear` 在保持项目内存的同时开始新任务。`/resume` 和 `/branch` 让您返回或分叉早期的对话。`/teleport` 将网络会话拉入此终端,`/remote-control` 让您从另一台设备继续此本地会话

26 

27**当出现问题时。** `/rewind` 将代码和对话回滚到检查点。`/doctor` 和 `/debug` 诊断安装和运行时问题,`/feedback` 报告附加会话上下文的错误。

28 

29## 所有命令

30 

31下表列出了 Claude Code 中包含的所有命令。标记为 **[Skill](/zh-CN/skills#bundled-skills)** 的条目是捆绑的 skills。它们使用与您自己编写的 skills 相同的机制:一个提示交给 Claude,Claude 也可以在相关时自动调用。其他所有内容都是内置命令,其行为被编码到 CLI 中。要添加您自己的命令,请参阅 [skills](/zh-CN/skills)。

18 32 

19在下表中,`<arg>` 表示必需的参数,`[arg]` 表示可选参数。33在下表中,`<arg>` 表示必需的参数,`[arg]` 表示可选参数。

20 34 

35<Note>

36 并非每个命令都对每个用户显示。可用性取决于您的平台、计划和环境。例如,`/desktop` 仅在 macOS 和 Windows 上显示,`/upgrade` 仅在 Pro 和 Max 计划上显示。

37</Note>

38 

21| 命令 | 用途 |39| 命令 | 用途 |

22| :---------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |40| :---------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

23| `/add-dir <path>` | 为当前会话期间的文件访问添加工作目录。大多数 `.claude/` 配置[不会从添加的目录中发现](/zh-CN/permissions#additional-directories-grant-file-access-not-configuration)。您可以稍后使用 `--continue` 或 `--resume` 从添加的目录恢复会话 |41| `/add-dir <path>` | 为当前会话期间的文件访问添加工作目录。大多数 `.claude/` 配置[不会从添加的目录中发现](/zh-CN/permissions#additional-directories-grant-file-access-not-configuration)。您可以稍后使用 `--continue` 或 `--resume` 从添加的目录恢复会话 |


80| `/review [PR]` | 在当前会话中本地审阅 pull request。要进行更深入的基于云的审阅,请参阅 [`/ultrareview`](/zh-CN/ultrareview) |98| `/review [PR]` | 在当前会话中本地审阅 pull request。要进行更深入的基于云的审阅,请参阅 [`/ultrareview`](/zh-CN/ultrareview) |

81| `/rewind` | 将对话和/或代码倒回到上一个点,或从选定的消息进行总结。请参阅 [checkpointing](/zh-CN/checkpointing)。别名:`/checkpoint`、`/undo` |99| `/rewind` | 将对话和/或代码倒回到上一个点,或从选定的消息进行总结。请参阅 [checkpointing](/zh-CN/checkpointing)。别名:`/checkpoint`、`/undo` |

82| `/sandbox` | 切换 [sandbox mode](/zh-CN/sandboxing)。仅在支持的平台上可用 |100| `/sandbox` | 切换 [sandbox mode](/zh-CN/sandboxing)。仅在支持的平台上可用 |

83| `/schedule [description]` | 创建、更新、列出或运行 [routines](/zh-CN/routines)。Claude 会以对话方式引导您完成设置。别名:`/routines` |101| `/schedule [description]` | 创建、更新、列出或运行 [routines](/zh-CN/routines),这些 routines 在 Anthropic 管理的云基础设施上执行。Claude 会以对话方式引导您完成设置。别名:`/routines` |

84| `/security-review` | 分析当前分支上的待处理更改以查找安全漏洞。审查 git 差异并识别注入、身份验证问题和数据泄露等风险 |102| `/security-review` | 分析当前分支上的待处理更改以查找安全漏洞。审查 git 差异并识别注入、身份验证问题和数据泄露等风险 |

85| `/setup-bedrock` | 通过交互式向导配置 [Amazon Bedrock](/zh-CN/amazon-bedrock) 身份验证、区域和模型固定。仅在设置 `CLAUDE_CODE_USE_BEDROCK=1` 时可见。首次 Bedrock 用户也可以从登录屏幕访问此向导 |103| `/setup-bedrock` | 通过交互式向导配置 [Amazon Bedrock](/zh-CN/amazon-bedrock) 身份验证、区域和模型固定。仅在设置 `CLAUDE_CODE_USE_BEDROCK=1` 时可见。首次 Bedrock 用户也可以从登录屏幕访问此向导 |

86| `/setup-vertex` | 通过交互式向导配置 [Google Vertex AI](/zh-CN/google-vertex-ai) 身份验证、项目、区域和模型固定。仅在设置 `CLAUDE_CODE_USE_VERTEX=1` 时可见。首次 Vertex AI 用户也可以从登录屏幕访问此向导 |104| `/setup-vertex` | 通过交互式向导配置 [Google Vertex AI](/zh-CN/google-vertex-ai) 身份验证、项目、区域和模型固定。仅在设置 `CLAUDE_CODE_USE_VERTEX=1` 时可见。首次 Vertex AI 用户也可以从登录屏幕访问此向导 |

desktop.md +17 −0

Details

564 564 

565每个条目需要 `id`、`name` 和 `sshHost`。`sshPort`、`sshIdentityFile` 和 `startDirectory` 字段是可选的。用户也可以将 `sshConfigs` 添加到他们自己的 `~/.claude/settings.json`,这是通过对话框添加的连接存储的位置。565每个条目需要 `id`、`name` 和 `sshHost`。`sshPort`、`sshIdentityFile` 和 `startDirectory` 字段是可选的。用户也可以将 `sshConfigs` 添加到他们自己的 `~/.claude/settings.json`,这是通过对话框添加的连接存储的位置。

566 566 

567#### 限制用户可以连接的 SSH 主机

568 

569管理员可以通过将 `sshHostAllowlist` 添加到[托管设置](/zh-CN/settings#settings-precedence)文件来限制 Desktop 的 SSH 会话到一组已批准的主机。设置后,用户只能连接到其解析的主机名与其中一个模式匹配的主机。将其设置为空数组以完全禁用 SSH 会话。

570 

571以下示例允许连接到 `devboxes.example.com` 下的任何主机以及单个命名的堡垒主机:

572 

573```json theme={null}

574{

575 "sshHostAllowlist": ["*.devboxes.example.com", "bastion.example.com"]

576}

577```

578 

579模式不区分大小写。`*` 匹配任何主机,`*.example.com` 匹配 `example.com` 和任何子域。其他任何内容都是精确匹配。检查针对通过 `ssh -G` 进行 `~/.ssh/config` 解析后的主机名运行,因此允许 `Host` 别名和 `ProxyCommand`/`ProxyJump` 条目,只要解析的 `HostName` 匹配。

580 

581`sshHostAllowlist` 仅从托管设置中读取;用户或项目设置中的值被忽略。只有 Claude Desktop 应用遵守此设置;Claude Code CLI 和 IDE 扩展不读取它,它也不限制通过 Bash 工具运行的 `ssh` 命令。它管理 Desktop 应用连接到的主机,而不是网络出口,因此如果你需要硬边界,请将其与你的组织的网络或零信任控制配对。

582 

567## 企业配置583## 企业配置

568 584 

569Teams 或 Enterprise 计划上的组织可以通过管理员控制台控制、托管设置文件和设备管理策略来管理桌面应用行为。585Teams 或 Enterprise 计划上的组织可以通过管理员控制台控制、托管设置文件和设备管理策略来管理桌面应用行为。


587| `disableAutoMode` | 设置为 `"disable"` 以防止用户启用 [Auto](/zh-CN/permission-modes#eliminate-prompts-with-auto-mode) 模式。从模式选择器中删除 Auto。也在 `permissions` 下接受。 |603| `disableAutoMode` | 设置为 `"disable"` 以防止用户启用 [Auto](/zh-CN/permission-modes#eliminate-prompts-with-auto-mode) 模式。从模式选择器中删除 Auto。也在 `permissions` 下接受。 |

588| `autoMode` | 自定义 auto 模式分类器在你的组织中信任和阻止的内容。请参阅[配置 auto 模式](/zh-CN/auto-mode-config)。 |604| `autoMode` | 自定义 auto 模式分类器在你的组织中信任和阻止的内容。请参阅[配置 auto 模式](/zh-CN/auto-mode-config)。 |

589| `sshConfigs` | 预配置[SSH 连接](#pre-configure-ssh-connections-for-your-team),在环境下拉菜单中显示。用户无法编辑或删除托管连接。 |605| `sshConfigs` | 预配置[SSH 连接](#pre-configure-ssh-connections-for-your-team),在环境下拉菜单中显示。用户无法编辑或删除托管连接。 |

606| `sshHostAllowlist` | 限制 [SSH 会话](#restrict-which-ssh-hosts-users-can-connect-to)连接到已解析主机名与这些模式之一匹配的主机。空数组禁用 SSH 会话。仅从托管设置中读取。 |

590 607 

591部署到每台机器上磁盘的托管设置文件适用于 Desktop 会话。通过管理员控制台远程推送的托管设置目前仅适用于 CLI 和 IDE 会话,因此对于 Desktop 部署,要么通过 MDM 分发文件,要么使用上面的[管理员控制台控制](#admin-console-controls)。608部署到每台机器上磁盘的托管设置文件适用于 Desktop 会话。通过管理员控制台远程推送的托管设置目前仅适用于 CLI 和 IDE 会话,因此对于 Desktop 部署,要么通过 MDM 分发文件,要么使用上面的[管理员控制台控制](#admin-console-controls)。

592 609 

env-vars.md +3 −1

Details

92| `CLAUDE_CODE_EFFORT_LEVEL` | 为支持的模型设置努力级别。值:`low`、`medium`、`high`、`xhigh`、`max` 或 `auto` 以使用模型默认值。可用级别取决于模型。优先于 `/effort` 和 `effortLevel` 设置。请参阅[调整努力级别](/zh-CN/model-config#adjust-effort-level) |92| `CLAUDE_CODE_EFFORT_LEVEL` | 为支持的模型设置努力级别。值:`low`、`medium`、`high`、`xhigh`、`max` 或 `auto` 以使用模型默认值。可用级别取决于模型。优先于 `/effort` 和 `effortLevel` 设置。请参阅[调整努力级别](/zh-CN/model-config#adjust-effort-level) |

93| `CLAUDE_CODE_ENABLE_AWAY_SUMMARY` | 覆盖[会话回顾](/zh-CN/interactive-mode#session-recap)可用性。设置为 `0` 以强制关闭回顾,无论 `/config` 切换如何。设置为 `1` 以在 [`awaySummaryEnabled`](/zh-CN/settings#available-settings) 为 `false` 时强制启用回顾。优先于设置和 `/config` 切换 |93| `CLAUDE_CODE_ENABLE_AWAY_SUMMARY` | 覆盖[会话回顾](/zh-CN/interactive-mode#session-recap)可用性。设置为 `0` 以强制关闭回顾,无论 `/config` 切换如何。设置为 `1` 以在 [`awaySummaryEnabled`](/zh-CN/settings#available-settings) 为 `false` 时强制启用回顾。优先于设置和 `/config` 切换 |

94| `CLAUDE_CODE_ENABLE_BACKGROUND_PLUGIN_REFRESH` | 设置为 `1` 以在[非交互模式](/zh-CN/headless)中的转换边界处刷新插件状态,在后台安装完成后。默认关闭,因为刷新会在会话中途更改系统提示,这会使该转换的 [prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) 失效 |94| `CLAUDE_CODE_ENABLE_BACKGROUND_PLUGIN_REFRESH` | 设置为 `1` 以在[非交互模式](/zh-CN/headless)中的转换边界处刷新插件状态,在后台安装完成后。默认关闭,因为刷新会在会话中途更改系统提示,这会使该转换的 [prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) 失效 |

95| `CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING` | 控制工具调用输入是否在 API 生成时从 API 流式传输。关闭此选项时,大型工具输入(如长文件写入)仅在 Claude 完成生成后才到达,这可能看起来像是挂起。对于直接 Anthropic API 连接默认启用。设置为 `0` 以选择退出。设置为 `1` 以强制启用,即使服务器端默认值为关闭。对 Bedrock、Vertex、Foundry [网关](/zh-CN/llm-gateway)连接无效 |95| `CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING` | 控制工具调用输入是否在 API 生成时从 API 流式传输。关闭此选项时,大型工具输入(如长文件写入)仅在 Claude 完成生成后才到达,这可能看起来像是挂起。对于 Anthropic API 默认启用。设置为 `0` 以选择退出。设置为 `1` 以在通过 `ANTHROPIC_BASE_URL`、`ANTHROPIC_VERTEX_BASE_URL` 或 `ANTHROPIC_BEDROCK_BASE_URL` 路由到代理时强制启用。对 Foundry [网关](/zh-CN/llm-gateway)连接默认关闭 |

96| `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY` | 设置为 `1` 以在 `ANTHROPIC_BASE_URL` 指向 Anthropic 兼容网关(如 LiteLLM、Kong 或内部代理)时从网关的 `/v1/models` 端点填充 `/model` 选择器。默认关闭,因为由共享 API 密钥支持的网关会显示该密钥可以访问的每个用户的每个模型。发现的模型仍由 [`availableModels`](/zh-CN/settings#available-settings) 允许列表过滤 |96| `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY` | 设置为 `1` 以在 `ANTHROPIC_BASE_URL` 指向 Anthropic 兼容网关(如 LiteLLM、Kong 或内部代理)时从网关的 `/v1/models` 端点填充 `/model` 选择器。默认关闭,因为由共享 API 密钥支持的网关会显示该密钥可以访问的每个用户的每个模型。发现的模型仍由 [`availableModels`](/zh-CN/settings#available-settings) 允许列表过滤 |

97| `CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION` | 设置为 `false` 以禁用提示建议(`/config` 中的"提示建议"切换)。这些是在 Claude 响应后出现在提示输入中的灰显预测。请参阅[提示建议](/zh-CN/interactive-mode#prompt-suggestions) |97| `CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION` | 设置为 `false` 以禁用提示建议(`/config` 中的"提示建议"切换)。这些是在 Claude 响应后出现在提示输入中的灰显预测。请参阅[提示建议](/zh-CN/interactive-mode#prompt-suggestions) |

98| `CLAUDE_CODE_ENABLE_TASKS` | 设置为 `1` 以在非交互模式(`-p` 标志)中启用任务跟踪系统。任务在交互模式中默认启用。请参阅[任务列表](/zh-CN/interactive-mode#task-list) |98| `CLAUDE_CODE_ENABLE_TASKS` | 设置为 `1` 以在非交互模式(`-p` 标志)中启用任务跟踪系统。任务在交互模式中默认启用。请参阅[任务列表](/zh-CN/interactive-mode#task-list) |


164| `CLAUDE_CODE_USE_POWERSHELL_TOOL` | 控制 PowerShell 工具。在没有 Git Bash 的 Windows 上,该工具会自动启用;设置为 `0` 以禁用它。在安装了 Git Bash 的 Windows 上,该工具正在逐步推出:设置为 `1` 以选择加入或 `0` 以选择退出。在 Linux、macOS 和 WSL 上,设置为 `1` 以启用它,这需要您的 `PATH` 上有 `pwsh`。在 Windows 上启用时,Claude 可以本地运行 PowerShell 命令,而不是通过 Git Bash 路由。请参阅 [PowerShell 工具](/zh-CN/tools-reference#powershell-tool) |164| `CLAUDE_CODE_USE_POWERSHELL_TOOL` | 控制 PowerShell 工具。在没有 Git Bash 的 Windows 上,该工具会自动启用;设置为 `0` 以禁用它。在安装了 Git Bash 的 Windows 上,该工具正在逐步推出:设置为 `1` 以选择加入或 `0` 以选择退出。在 Linux、macOS 和 WSL 上,设置为 `1` 以启用它,这需要您的 `PATH` 上有 `pwsh`。在 Windows 上启用时,Claude 可以本地运行 PowerShell 命令,而不是通过 Git Bash 路由。请参阅 [PowerShell 工具](/zh-CN/tools-reference#powershell-tool) |

165| `CLAUDE_CODE_USE_VERTEX` | 使用 [Vertex](/zh-CN/google-vertex-ai) |165| `CLAUDE_CODE_USE_VERTEX` | 使用 [Vertex](/zh-CN/google-vertex-ai) |

166| `CLAUDE_CONFIG_DIR` | 覆盖配置目录(默认值:`~/.claude`)。所有设置、凭证、会话历史和插件都存储在此路径下。对于并行运行多个帐户很有用:例如,`alias claude-work='CLAUDE_CONFIG_DIR=~/.claude-work claude'` |166| `CLAUDE_CONFIG_DIR` | 覆盖配置目录(默认值:`~/.claude`)。所有设置、凭证、会话历史和插件都存储在此路径下。对于并行运行多个帐户很有用:例如,`alias claude-work='CLAUDE_CONFIG_DIR=~/.claude-work claude'` |

167| `CLAUDE_EFFORT` | 在 Bash 工具子进程和 hook 命令中自动设置为该转换的活动[努力级别](/zh-CN/model-config#adjust-effort-level):`low`、`medium`、`high`、`xhigh` 或 `max`。与传递给 [hooks](/zh-CN/hooks) 的 `effort.level` 字段匹配。仅在当前模型支持努力参数时设置 |

167| `CLAUDE_ENABLE_BYTE_WATCHDOG` | 设置为 `1` 以强制启用字节级流式空闲监视程序,或设置为 `0` 以强制禁用它。未设置时,监视程序对 Anthropic API 连接默认启用。字节监视程序在 `CLAUDE_STREAM_IDLE_TIMEOUT_MS` 设置的持续时间内没有字节到达线路时中止连接,最少 5 分钟,独立于事件级监视程序 |168| `CLAUDE_ENABLE_BYTE_WATCHDOG` | 设置为 `1` 以强制启用字节级流式空闲监视程序,或设置为 `0` 以强制禁用它。未设置时,监视程序对 Anthropic API 连接默认启用。字节监视程序在 `CLAUDE_STREAM_IDLE_TIMEOUT_MS` 设置的持续时间内没有字节到达线路时中止连接,最少 5 分钟,独立于事件级监视程序 |

168| `CLAUDE_ENABLE_STREAM_WATCHDOG` | 设置为 `1` 以启用事件级流式空闲监视程序。默认关闭。对于 Bedrock、Vertex 和 Foundry,这是唯一可用的空闲监视程序。使用 `CLAUDE_STREAM_IDLE_TIMEOUT_MS` 配置超时 |169| `CLAUDE_ENABLE_STREAM_WATCHDOG` | 设置为 `1` 以启用事件级流式空闲监视程序。默认关闭。对于 Bedrock、Vertex 和 Foundry,这是唯一可用的空闲监视程序。使用 `CLAUDE_STREAM_IDLE_TIMEOUT_MS` 配置超时 |

169| `CLAUDE_ENV_FILE` | Claude Code 在每个 Bash 命令之前在同一 shell 进程中运行的 shell 脚本的路径,因此文件中的导出对命令可见。用于在命令之间保持 virtualenv 或 conda 激活。也由 [SessionStart](/zh-CN/hooks#persist-environment-variables)、[Setup](/zh-CN/hooks#setup)、[CwdChanged](/zh-CN/hooks#cwdchanged) 和 [FileChanged](/zh-CN/hooks#filechanged) hooks 动态填充 |170| `CLAUDE_ENV_FILE` | Claude Code 在每个 Bash 命令之前在同一 shell 进程中运行的 shell 脚本的路径,因此文件中的导出对命令可见。用于在命令之间保持 virtualenv 或 conda 激活。也由 [SessionStart](/zh-CN/hooks#persist-environment-variables)、[Setup](/zh-CN/hooks#setup)、[CwdChanged](/zh-CN/hooks#cwdchanged) 和 [FileChanged](/zh-CN/hooks#filechanged) hooks 动态填充 |


205| `MAX_THINKING_TOKENS` | 覆盖[扩展思考](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)令牌预算。上限是模型的[最大输出令牌](https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison)减一。设置为 `0` 以完全禁用思考。在具有[自适应推理](/zh-CN/model-config#adjust-effort-level)的模型上,除非通过 `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` 禁用自适应推理,否则预算被忽略 |206| `MAX_THINKING_TOKENS` | 覆盖[扩展思考](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)令牌预算。上限是模型的[最大输出令牌](https://platform.claude.com/docs/en/about-claude/models/overview#latest-models-comparison)减一。设置为 `0` 以完全禁用思考。在具有[自适应推理](/zh-CN/model-config#adjust-effort-level)的模型上,除非通过 `CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING` 禁用自适应推理,否则预算被忽略 |

206| `MCP_CLIENT_SECRET` | 需要[预配置凭证](/zh-CN/mcp#use-pre-configured-oauth-credentials)的 MCP 服务器的 OAuth 客户端密钥。在使用 `--client-secret` 添加服务器时避免交互式提示 |207| `MCP_CLIENT_SECRET` | 需要[预配置凭证](/zh-CN/mcp#use-pre-configured-oauth-credentials)的 MCP 服务器的 OAuth 客户端密钥。在使用 `--client-secret` 添加服务器时避免交互式提示 |

207| `MCP_CONNECTION_NONBLOCKING` | 设置为 `true` 在非交互模式(`-p`)中完全跳过 MCP 连接等待。对于不需要 MCP 工具的脚本化管道很有用。没有此变量,第一个查询会等待最多 5 秒以获得 `--mcp-config` 服务器连接。服务器配置为 [`alwaysLoad: true`](/zh-CN/mcp#exempt-a-server-from-deferral) 始终阻止启动,无论此变量如何,因为它们的工具必须在构建第一个提示时存在 |208| `MCP_CONNECTION_NONBLOCKING` | 设置为 `true` 在非交互模式(`-p`)中完全跳过 MCP 连接等待。对于不需要 MCP 工具的脚本化管道很有用。没有此变量,第一个查询会等待最多 5 秒以获得 `--mcp-config` 服务器连接。服务器配置为 [`alwaysLoad: true`](/zh-CN/mcp#exempt-a-server-from-deferral) 始终阻止启动,无论此变量如何,因为它们的工具必须在构建第一个提示时存在 |

209| `MCP_CONNECT_TIMEOUT_MS` | 第一个查询等待 MCP 连接批处理的时间(以毫秒为单位),然后快照工具列表(默认值:5000)。在截止时间处仍待处理的服务器继续在后台连接,但在下一个查询之前不会出现。与 `MCP_TIMEOUT` 不同,后者限制单个服务器的连接尝试。最相关的是需要慢速连接服务器可见的非交互式会话,这些会话发出单个查询 |

208| `MCP_OAUTH_CALLBACK_PORT` | OAuth 重定向回调的固定端口,作为在使用[预配置凭证](/zh-CN/mcp#use-pre-configured-oauth-credentials)添加 MCP 服务器时 `--callback-port` 的替代方案 |210| `MCP_OAUTH_CALLBACK_PORT` | OAuth 重定向回调的固定端口,作为在使用[预配置凭证](/zh-CN/mcp#use-pre-configured-oauth-credentials)添加 MCP 服务器时 `--callback-port` 的替代方案 |

209| `MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE` | 启动期间并行连接的远程 MCP 服务器(HTTP/SSE)的最大数量(默认值:20) |211| `MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE` | 启动期间并行连接的远程 MCP 服务器(HTTP/SSE)的最大数量(默认值:20) |

210| `MCP_SERVER_CONNECTION_BATCH_SIZE` | 启动期间并行连接的本地 MCP 服务器(stdio)的最大数量(默认值:3) |212| `MCP_SERVER_CONNECTION_BATCH_SIZE` | 启动期间并行连接的本地 MCP 服务器(stdio)的最大数量(默认值:3) |

Details

249 249 

250 **上下文成本:** 低,直到使用。仅用户 skills 在调用前成本为零。250 **上下文成本:** 低,直到使用。仅用户 skills 在调用前成本为零。

251 251 

252 **在 subagents 中:** Skills 在 subagents 中的工作方式不同。不是按需加载,而是传递给 subagent 的 skills 在启动时完全预加载到其上下文中。Subagents 不从主会话继承 skills;您必须明确指定它们252 **在 subagents 中:** Skills 在 subagents 中的工作方式不同。不是按需加载,而是在 subagent 的 `skills:` 字段中列出的 skills 在启动时完全预加载到其上下文中。Subagents 仍然可以通过 Skill 工具发现和调用未列出的项目、用户和插件 skills。

253 253 

254 <Tip>对于有副作用的 skills,使用 `disable-model-invocation: true`。这节省上下文并确保只有您触发它们。</Tip>254 <Tip>对于有副作用的 skills,使用 `disable-model-invocation: true`。这节省上下文并确保只有您触发它们。</Tip>

255 </Tab>255 </Tab>

Details

76 </div>;76 </div>;

77};77};

78 78 

79export const Experiment = ({flag, treatment, children}) => {79<ContactSalesCard surface="vertex" />

80 const VID_KEY = 'exp_vid';

81 const CONSENT_COUNTRIES = new Set(['AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'RE', 'GP', 'MQ', 'GF', 'YT', 'BL', 'MF', 'PM', 'WF', 'PF', 'NC', 'AW', 'CW', 'SX', 'FO', 'GL', 'AX', 'GB', 'UK', 'AI', 'BM', 'IO', 'VG', 'KY', 'FK', 'GI', 'MS', 'PN', 'SH', 'TC', 'GG', 'JE', 'IM', 'CA', 'BR', 'IN']);

82 const fnv1a = s => {

83 let h = 0x811c9dc5;

84 for (let i = 0; i < s.length; i++) {

85 h ^= s.charCodeAt(i);

86 h += (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24);

87 }

88 return h >>> 0;

89 };

90 const bucket = (seed, vid) => fnv1a(fnv1a(seed + vid) + '') % 10000 < 5000 ? 'control' : 'treatment';

91 const [decision] = useState(() => {

92 const params = new URLSearchParams(location.search);

93 const preBucketed = document.documentElement.dataset['gb_' + flag.replace(/-/g, '_')];

94 const force = params.get('gb-force');

95 if (force) {

96 for (const p of force.split(',')) {

97 const [k, v] = p.split(':');

98 if (k === flag) return {

99 variant: v || 'treatment',

100 track: false

101 };

102 }

103 }

104 if (navigator.globalPrivacyControl) {

105 return {

106 variant: 'control',

107 track: false

108 };

109 }

110 const prefsMatch = document.cookie.match(/(?:^|; )anthropic-consent-preferences=([^;]+)/);

111 if (prefsMatch) {

112 try {

113 if (JSON.parse(decodeURIComponent(prefsMatch[1])).analytics !== true) {

114 return {

115 variant: 'control',

116 track: false

117 };

118 }

119 } catch {

120 return {

121 variant: 'control',

122 track: false

123 };

124 }

125 } else {

126 const country = params.get('country')?.toUpperCase() || (document.cookie.match(/(?:^|; )cf_geo=([A-Z]{2})/) || [])[1];

127 if (!country || CONSENT_COUNTRIES.has(country)) {

128 return {

129 variant: 'control',

130 track: false

131 };

132 }

133 }

134 let vid;

135 try {

136 const ajsMatch = document.cookie.match(/(?:^|; )ajs_anonymous_id=([^;]+)/);

137 if (ajsMatch) {

138 vid = decodeURIComponent(ajsMatch[1]).replace(/^"|"$/g, '');

139 } else {

140 vid = localStorage.getItem(VID_KEY);

141 if (!vid) {

142 vid = crypto.randomUUID();

143 }

144 document.cookie = `ajs_anonymous_id=${vid}; domain=.claude.com; path=/; Secure; SameSite=Lax; max-age=31536000`;

145 }

146 try {

147 localStorage.setItem(VID_KEY, vid);

148 } catch {}

149 } catch {

150 return {

151 variant: 'control',

152 track: false

153 };

154 }

155 const variant = preBucketed === '1' ? 'treatment' : preBucketed === '0' ? 'control' : bucket(flag, vid);

156 return {

157 variant,

158 track: true,

159 vid

160 };

161 });

162 useEffect(() => {

163 if (!decision.track) return;

164 fetch('https://api.anthropic.com/api/event_logging/v2/batch', {

165 method: 'POST',

166 headers: {

167 'Content-Type': 'application/json',

168 'x-service-name': 'claude_code_docs'

169 },

170 body: JSON.stringify({

171 events: [{

172 event_type: 'GrowthbookExperimentEvent',

173 event_data: {

174 device_id: decision.vid,

175 anonymous_id: decision.vid,

176 timestamp: new Date().toISOString(),

177 experiment_id: flag,

178 variation_id: decision.variant === 'treatment' ? 1 : 0,

179 environment: 'production'

180 }

181 }]

182 }),

183 keepalive: true

184 }).catch(() => {});

185 }, []);

186 return decision.variant === 'treatment' ? treatment : children;

187};

188 

189<Experiment flag="docs-contact-sales-cta" treatment={<ContactSalesCard surface="vertex" />} />

190 80 

191## 前置条件81## 前置条件

192 82 

hooks.md +5 −4

Details

518所有 hook 事件都接收这些字段作为 JSON,除了每个[hook 事件](#hook-events)部分中记录的事件特定字段。对于命令 hooks,此 JSON 通过 stdin 到达。对于 HTTP hooks,它作为 POST 请求体到达。518所有 hook 事件都接收这些字段作为 JSON,除了每个[hook 事件](#hook-events)部分中记录的事件特定字段。对于命令 hooks,此 JSON 通过 stdin 到达。对于 HTTP hooks,它作为 POST 请求体到达。

519 519 

520| 字段 | 描述 |520| 字段 | 描述 |

521| :---------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------- |521| :---------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

522| `session_id` | 当前会话标识符 |522| `session_id` | 当前会话标识符 |

523| `transcript_path` | 对话 JSON 的路径 |523| `transcript_path` | 对话 JSON 的路径 |

524| `cwd` | 调用 hook 时的当前工作目录 |524| `cwd` | 调用 hook 时的当前工作目录 |

525| `permission_mode` | 当前[权限模式](/zh-CN/permissions#permission-modes):`"default"`、`"plan"`、`"acceptEdits"`、`"auto"`、`"dontAsk"` 或 `"bypassPermissions"`。并非所有事件都接收此字段:请参阅下面每个事件的 JSON 示例以检查 |525| `permission_mode` | 当前[权限模式](/zh-CN/permissions#permission-modes):`"default"`、`"plan"`、`"acceptEdits"`、`"auto"`、`"dontAsk"` 或 `"bypassPermissions"`。并非所有事件都接收此字段:请参阅下面每个事件的 JSON 示例以检查 |

526| `effort` | 对象,其中 `level` 字段保存该轮次的活跃[努力级别](/zh-CN/model-config#adjust-effort-level):`"low"`、`"medium"`、`"high"`、`"xhigh"` 或 `"max"`。如果请求的努力级别超过当前模型支持的级别,这是模型实际使用的降级级别,而不是您请求的级别。该对象与[状态行](/zh-CN/statusline#available-data) `effort` 字段匹配。存在于在工具使用上下文中触发的事件中,例如 `PreToolUse`、`PostToolUse`、`Stop` 和 `SubagentStop`,当当前模型支持努力参数时。该级别也可作为 `$CLAUDE_EFFORT` 环境变量提供给 hook 命令和 Bash 工具。 |

526| `hook_event_name` | 触发的事件名称 |527| `hook_event_name` | 触发的事件名称 |

527 528 

528使用 `--agent` 运行或在 subagent 内部时,包括两个额外字段:529使用 `--agent` 运行或在 subagent 内部时,包括两个额外字段:


1225 1226 

1226如果恢复时延迟的工具不再可用,进程以 `stop_reason: "tool_deferred_unavailable"` 和 `is_error: true` 退出,在 hook 触发之前。这发生在为恢复的会话未连接提供工具的 MCP 服务器时。`deferred_tool_use` 有效负载仍然包括,以便您可以识别哪个工具丢失。1227如果恢复时延迟的工具不再可用,进程以 `stop_reason: "tool_deferred_unavailable"` 和 `is_error: true` 退出,在 hook 触发之前。这发生在为恢复的会话未连接提供工具的 MCP 服务器时。`deferred_tool_use` 有效负载仍然包括,以便您可以识别哪个工具丢失。

1227 1228 

1228<Warning>1229<Note>

1229 `--resume` 不会从先前的会话恢复权限模式。在恢复时传递与工具被延迟时活跃的相同 `--permission-mode` 标志Claude Code 在模式不同时记录警告1230 `--resume` 恢复工具被延迟时活跃的权限模式,因此您不需要再次传递 `--permission-mode`。例外是 `plan` 和 `bypassPermissions`,它们永远不会被携带在恢复时显式传递 `--permission-mode` 会覆盖恢复的值

1230</Warning>1231</Note>

1231 1232 

1232### PermissionRequest1233### PermissionRequest

1233 1234 

memory.md +10 −0

Details

132对 `src/billing/` 下的更改使用 Plan Mode。132对 `src/billing/` 下的更改使用 Plan Mode。

133```133```

134 134 

135一个符号链接也可以工作,如果你不需要添加 Claude 特定的内容:

136 

137```bash theme={null}

138ln -s AGENTS.md CLAUDE.md

139```

140 

141在 Windows 上,创建符号链接需要管理员权限或开发者模式,所以改用 `@AGENTS.md` 导入。

142 

143在已经有 `AGENTS.md` 的存储库中运行 [`/init`](/zh-CN/commands) 会读取它并将相关部分合并到生成的 `CLAUDE.md` 中。它也读取其他工具配置,如 `.cursorrules` 和 `.windsurfrules`。

144 

135### CLAUDE.md 文件如何加载145### CLAUDE.md 文件如何加载

136 146 

137Claude Code 通过从当前工作目录向上遍历目录树来读取 CLAUDE.md 文件,检查沿途的每个目录是否有 `CLAUDE.md` 和 `CLAUDE.local.md` 文件。这意味着如果你在 `foo/bar/` 中运行 Claude Code,它会从 `foo/bar/CLAUDE.md`、`foo/CLAUDE.md` 和沿途的任何 `CLAUDE.local.md` 文件加载指令。147Claude Code 通过从当前工作目录向上遍历目录树来读取 CLAUDE.md 文件,检查沿途的每个目录是否有 `CLAUDE.md` 和 `CLAUDE.local.md` 文件。这意味着如果你在 `foo/bar/` 中运行 Claude Code,它会从 `foo/bar/CLAUDE.md`、`foo/CLAUDE.md` 和沿途的任何 `CLAUDE.local.md` 文件加载指令。

Details

2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt2> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt

3> Use this file to discover all available pages before exploring further.3> Use this file to discover all available pages before exploring further.

4 4 

5# Claude Code on Microsoft Foundry5# Microsoft Foundry 上的 Claude Code

6 6 

7> 了解如何通过 Microsoft Foundry 配置 Claude Code,包括设置、配置和故障排除。7> 了解如何通过 Microsoft Foundry 配置 Claude Code,包括设置、配置和故障排除。

8 8 


76 </div>;76 </div>;

77};77};

78 78 

79export const Experiment = ({flag, treatment, children}) => {79<ContactSalesCard surface="foundry" />

80 const VID_KEY = 'exp_vid';

81 const CONSENT_COUNTRIES = new Set(['AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'RE', 'GP', 'MQ', 'GF', 'YT', 'BL', 'MF', 'PM', 'WF', 'PF', 'NC', 'AW', 'CW', 'SX', 'FO', 'GL', 'AX', 'GB', 'UK', 'AI', 'BM', 'IO', 'VG', 'KY', 'FK', 'GI', 'MS', 'PN', 'SH', 'TC', 'GG', 'JE', 'IM', 'CA', 'BR', 'IN']);

82 const fnv1a = s => {

83 let h = 0x811c9dc5;

84 for (let i = 0; i < s.length; i++) {

85 h ^= s.charCodeAt(i);

86 h += (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24);

87 }

88 return h >>> 0;

89 };

90 const bucket = (seed, vid) => fnv1a(fnv1a(seed + vid) + '') % 10000 < 5000 ? 'control' : 'treatment';

91 const [decision] = useState(() => {

92 const params = new URLSearchParams(location.search);

93 const preBucketed = document.documentElement.dataset['gb_' + flag.replace(/-/g, '_')];

94 const force = params.get('gb-force');

95 if (force) {

96 for (const p of force.split(',')) {

97 const [k, v] = p.split(':');

98 if (k === flag) return {

99 variant: v || 'treatment',

100 track: false

101 };

102 }

103 }

104 if (navigator.globalPrivacyControl) {

105 return {

106 variant: 'control',

107 track: false

108 };

109 }

110 const prefsMatch = document.cookie.match(/(?:^|; )anthropic-consent-preferences=([^;]+)/);

111 if (prefsMatch) {

112 try {

113 if (JSON.parse(decodeURIComponent(prefsMatch[1])).analytics !== true) {

114 return {

115 variant: 'control',

116 track: false

117 };

118 }

119 } catch {

120 return {

121 variant: 'control',

122 track: false

123 };

124 }

125 } else {

126 const country = params.get('country')?.toUpperCase() || (document.cookie.match(/(?:^|; )cf_geo=([A-Z]{2})/) || [])[1];

127 if (!country || CONSENT_COUNTRIES.has(country)) {

128 return {

129 variant: 'control',

130 track: false

131 };

132 }

133 }

134 let vid;

135 try {

136 const ajsMatch = document.cookie.match(/(?:^|; )ajs_anonymous_id=([^;]+)/);

137 if (ajsMatch) {

138 vid = decodeURIComponent(ajsMatch[1]).replace(/^"|"$/g, '');

139 } else {

140 vid = localStorage.getItem(VID_KEY);

141 if (!vid) {

142 vid = crypto.randomUUID();

143 }

144 document.cookie = `ajs_anonymous_id=${vid}; domain=.claude.com; path=/; Secure; SameSite=Lax; max-age=31536000`;

145 }

146 try {

147 localStorage.setItem(VID_KEY, vid);

148 } catch {}

149 } catch {

150 return {

151 variant: 'control',

152 track: false

153 };

154 }

155 const variant = preBucketed === '1' ? 'treatment' : preBucketed === '0' ? 'control' : bucket(flag, vid);

156 return {

157 variant,

158 track: true,

159 vid

160 };

161 });

162 useEffect(() => {

163 if (!decision.track) return;

164 fetch('https://api.anthropic.com/api/event_logging/v2/batch', {

165 method: 'POST',

166 headers: {

167 'Content-Type': 'application/json',

168 'x-service-name': 'claude_code_docs'

169 },

170 body: JSON.stringify({

171 events: [{

172 event_type: 'GrowthbookExperimentEvent',

173 event_data: {

174 device_id: decision.vid,

175 anonymous_id: decision.vid,

176 timestamp: new Date().toISOString(),

177 experiment_id: flag,

178 variation_id: decision.variant === 'treatment' ? 1 : 0,

179 environment: 'production'

180 }

181 }]

182 }),

183 keepalive: true

184 }).catch(() => {});

185 }, []);

186 return decision.variant === 'treatment' ? treatment : children;

187};

188 

189<Experiment flag="docs-contact-sales-cta" treatment={<ContactSalesCard surface="foundry" />} />

190 80 

191## 前置条件81## 前置条件

192 82 

model-config.md +4 −0

Details

17 * Foundry:部署名称17 * Foundry:部署名称

18 * Vertex:版本名称18 * Vertex:版本名称

19 19 

20<Note>

21 `ANTHROPIC_BASE_URL` 改变请求发送的位置,而不是哪个模型回答它们。要通过 LLM 网关路由 Claude,请参阅 [LLM 网关配置](/zh-CN/llm-gateway)。

22</Note>

23 

20### 模型别名24### 模型别名

21 25 

22模型别名提供了一种便捷的方式来选择模型设置,无需记住确切的版本号:26模型别名提供了一种便捷的方式来选择模型设置,无需记住确切的版本号:

overview.md +1 −635

Details

6 6 

7> Claude Code 是一个代理编码工具,可以读取你的代码库、编辑文件、运行命令,并与你的开发工具集成。可在终端、IDE、桌面应用和浏览器中使用。7> Claude Code 是一个代理编码工具,可以读取你的代码库、编辑文件、运行命令,并与你的开发工具集成。可在终端、IDE、桌面应用和浏览器中使用。

8 8 

9export const InstallConfigurator = ({defaultSurface = 'terminal'}) => {

10 const TERM = {

11 mac: {

12 label: 'macOS / Linux',

13 cmd: 'curl -fsSL https://claude.ai/install.sh | bash'

14 },

15 win: {

16 label: 'Windows'

17 },

18 brew: {

19 label: 'Homebrew',

20 cmd: 'brew install --cask claude-code'

21 },

22 winget: {

23 label: 'WinGet',

24 cmd: 'winget install Anthropic.ClaudeCode'

25 }

26 };

27 const WIN_VARIANTS = {

28 ps: 'irm https://claude.ai/install.ps1 | iex',

29 cmd: 'curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd'

30 };

31 const TABS = [{

32 key: 'terminal',

33 label: 'Terminal'

34 }, {

35 key: 'desktop',

36 label: 'Desktop'

37 }, {

38 key: 'vscode',

39 label: 'VS Code'

40 }, {

41 key: 'jetbrains',

42 label: 'JetBrains'

43 }];

44 const ALT_TARGETS = {

45 desktop: {

46 name: 'Desktop',

47 tagline: 'The full agent in a native app for macOS and Windows.',

48 installLabel: 'Download the app',

49 installHref: 'https://claude.com/download?utm_source=claude_code&utm_medium=docs&utm_content=configurator_desktop_download',

50 guideHref: '/en/desktop-quickstart'

51 },

52 vscode: {

53 name: 'VS Code',

54 tagline: 'Review diffs, manage context, and chat without leaving your editor.',

55 installLabel: 'Install from Marketplace',

56 installHref: 'https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code',

57 altCmd: 'code --install-extension anthropic.claude-code',

58 guideHref: '/en/vs-code'

59 },

60 jetbrains: {

61 name: 'JetBrains',

62 tagline: 'Native plugin for IntelliJ, PyCharm, WebStorm, and other JetBrains IDEs.',

63 installLabel: 'Install from Marketplace',

64 installHref: 'https://plugins.jetbrains.com/plugin/27310-claude-code-beta-',

65 guideHref: '/en/jetbrains'

66 }

67 };

68 const PROVIDERS = [{

69 key: 'anthropic',

70 label: 'Anthropic'

71 }, {

72 key: 'bedrock',

73 label: 'Amazon Bedrock'

74 }, {

75 key: 'foundry',

76 label: 'Microsoft Foundry'

77 }, {

78 key: 'vertex',

79 label: 'Google Vertex AI'

80 }];

81 const PROVIDER_NOTICE = {

82 bedrock: <>

83 <strong>Configure your AWS account first.</strong> Running on Bedrock

84 requires model access enabled in the AWS console and IAM credentials.{' '}

85 <a href="/en/amazon-bedrock">Bedrock setup guide →</a>

86 </>,

87 vertex: <>

88 <strong>Configure your GCP project first.</strong> Running on Vertex AI

89 requires the Vertex API enabled and a service account with the right

90 permissions.{' '}

91 <a href="/en/google-vertex-ai">Vertex setup guide →</a>

92 </>,

93 foundry: <>

94 <strong>Configure your Azure resources first.</strong> Running on

95 Microsoft Foundry requires an Azure subscription with a Foundry resource

96 and model deployments provisioned.{' '}

97 <a href="/en/microsoft-foundry">Foundry setup guide →</a>

98 </>

99 };

100 const iconCheck = (size = 14) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

101 <polyline points="20 6 9 17 4 12" />

102 </svg>;

103 const iconCopy = (size = 14) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

104 <rect x="9" y="9" width="13" height="13" rx="2" />

105 <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />

106 </svg>;

107 const iconArrowRight = (size = 13) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

108 <line x1="5" y1="12" x2="19" y2="12" />

109 <polyline points="12 5 19 12 12 19" />

110 </svg>;

111 const iconArrowUpRight = (size = 14) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

112 <line x1="7" y1="17" x2="17" y2="7" />

113 <polyline points="7 7 17 7 17 17" />

114 </svg>;

115 const iconInfo = (size = 16) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

116 <circle cx="12" cy="12" r="10" />

117 <line x1="12" y1="16" x2="12" y2="12" />

118 <line x1="12" y1="8" x2="12.01" y2="8" />

119 </svg>;

120 const [target, setTarget] = useState(defaultSurface);

121 const [team, setTeam] = useState(false);

122 const [provider, setProvider] = useState('anthropic');

123 const [pkg, setPkg] = useState(() => (/Win/).test(navigator.userAgent) ? 'win' : 'mac');

124 const [winCmd, setWinCmd] = useState(false);

125 const [copied, setCopied] = useState(null);

126 const copyTimer = useRef(null);

127 const handleCopy = async (text, key) => {

128 try {

129 await navigator.clipboard.writeText(text);

130 } catch {

131 const ta = document.createElement('textarea');

132 ta.value = text;

133 document.body.appendChild(ta);

134 ta.select();

135 document.execCommand('copy');

136 document.body.removeChild(ta);

137 }

138 clearTimeout(copyTimer.current);

139 setCopied(key);

140 copyTimer.current = setTimeout(() => setCopied(null), 1800);

141 };

142 const cardBodyCmd = (cmd, prompt) => {

143 const on = copied === 'term';

144 return <div className="cc-ic-card-body">

145 <span className="cc-ic-prompt">{prompt || '$'}</span>

146 <div className="cc-ic-cmd">{cmd}</div>

147 <button type="button" className={'cc-ic-copy' + (on ? ' cc-ic-copied' : '')} onClick={() => handleCopy(cmd, 'term')}>

148 {on ? iconCheck(13) : iconCopy(13)}

149 <span>{on ? 'Copied' : 'Copy'}</span>

150 </button>

151 </div>;

152 };

153 const isWinInstaller = pkg === 'win';

154 const isWinPrompt = pkg === 'win' || pkg === 'winget';

155 const terminalCmd = isWinInstaller ? WIN_VARIANTS[winCmd ? 'cmd' : 'ps'] : TERM[pkg].cmd;

156 const alt = ALT_TARGETS[target];

157 const showNotice = team && provider !== 'anthropic';

158 const STYLES = `

159.cc-ic {

160 --ic-slate: #141413;

161 --ic-clay: #d97757;

162 --ic-clay-deep: #c6613f;

163 --ic-gray-000: #ffffff;

164 --ic-gray-150: #f0eee6;

165 --ic-gray-550: #73726c;

166 --ic-gray-700: #3d3d3a;

167 --ic-border-subtle: rgba(31, 30, 29, 0.08);

168 --ic-border-default: rgba(31, 30, 29, 0.15);

169 --ic-border-strong: rgba(31, 30, 29, 0.3);

170 --ic-font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, 'Courier New', monospace;

171 font-family: 'Anthropic Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;

172 font-size: 14px; line-height: 1.5; color: var(--ic-slate);

173 margin: 8px 0 32px;

174}

175.dark .cc-ic {

176 --ic-slate: #f0eee6;

177 --ic-gray-000: #262624;

178 --ic-gray-150: #1f1e1d;

179 --ic-gray-550: #91908a;

180 --ic-gray-700: #bfbdb4;

181 --ic-border-subtle: rgba(240, 238, 230, 0.08);

182 --ic-border-default: rgba(240, 238, 230, 0.14);

183 --ic-border-strong: rgba(240, 238, 230, 0.28);

184}

185.dark .cc-ic-check { background: transparent; }

186.dark .cc-ic-card { border: 0.5px solid var(--ic-border-subtle); }

187.dark .cc-ic-p-pill.cc-ic-active { box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3); }

188.cc-ic *, .cc-ic *::before, .cc-ic *::after { box-sizing: border-box; }

189.cc-ic a { text-decoration: none; }

190.cc-ic a:not([class]) { color: inherit; }

191.cc-ic button { font-family: inherit; cursor: pointer; }

192 

193.cc-ic-tab-strip {

194 display: inline-flex; gap: 2px;

195 padding: 4px; background: var(--ic-gray-150);

196 border-radius: 10px; overflow-x: auto;

197 max-width: 100%;

198}

199.cc-ic-tab {

200 appearance: none; background: none; border: none;

201 padding: 10px 18px; font-size: 15px; font-weight: 430;

202 color: var(--ic-gray-550); border-radius: 7px;

203 white-space: nowrap;

204 transition: color 0.12s, background-color 0.12s;

205}

206.cc-ic-tab:hover { color: var(--ic-gray-700); }

207.cc-ic-tab.cc-ic-active {

208 color: var(--ic-slate); font-weight: 500;

209 background: var(--ic-gray-000);

210 box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);

211}

212.dark .cc-ic-tab.cc-ic-active { box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4); }

213 

214.cc-ic-team-wrap { padding: 16px 0 20px; }

215.cc-ic-team-toggle {

216 display: flex; align-items: center; gap: 12px; font-family: inherit;

217 padding: 12px 16px; font-size: 14px; font-weight: 430;

218 color: var(--ic-gray-700); cursor: pointer; user-select: none;

219 width: fit-content; background: var(--ic-gray-150);

220 border: 0.5px solid var(--ic-border-subtle); border-radius: 8px;

221 transition: border-color 0.15s;

222}

223.cc-ic-team-toggle:hover { border-color: var(--ic-border-default); }

224.cc-ic-team-toggle.cc-ic-checked {

225 background: rgba(217, 119, 87, 0.08);

226 border-color: rgba(217, 119, 87, 0.25);

227}

228.cc-ic-check {

229 width: 16px; height: 16px;

230 border: 1px solid var(--ic-border-strong); border-radius: 4px;

231 background: var(--ic-gray-000);

232 display: flex; align-items: center; justify-content: center;

233 flex-shrink: 0;

234}

235.cc-ic-check svg { color: #fff; display: none; }

236.cc-ic-team-toggle.cc-ic-checked .cc-ic-check { background: var(--ic-clay-deep); border-color: var(--ic-clay-deep); }

237.cc-ic-team-toggle.cc-ic-checked .cc-ic-check svg { display: block; }

238 

239.cc-ic-team-reveal { display: flex; flex-direction: column; gap: 12px; margin-bottom: 16px; }

240.cc-ic-sales {

241 display: flex; align-items: center; justify-content: space-between;

242 gap: 16px; padding: 14px 16px;

243 background: var(--ic-gray-000); border: 0.5px solid var(--ic-border-default);

244 border-radius: 8px; flex-wrap: wrap;

245}

246.cc-ic-sales-text { font-size: 13px; color: var(--ic-gray-700); line-height: 1.5; flex: 1; min-width: 200px; }

247.cc-ic-sales-text strong { font-weight: 550; color: var(--ic-slate); }

248.cc-ic-sales-actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }

249.cc-ic-btn-clay {

250 display: inline-flex; align-items: center; gap: 8px;

251 background: var(--ic-clay-deep); color: #fff; border: none;

252 border-radius: 8px; padding: 8px 14px;

253 font-size: 13px; font-weight: 500;

254 transition: background-color 0.15s; white-space: nowrap;

255}

256.cc-ic-btn-clay:hover { background: var(--ic-clay); }

257.cc-ic-btn-ghost {

258 display: inline-flex; align-items: center; gap: 8px;

259 background: transparent; color: var(--ic-gray-700);

260 border: 0.5px solid var(--ic-border-default);

261 border-radius: 8px; padding: 8px 14px;

262 font-size: 13px; font-weight: 500;

263}

264.cc-ic-btn-ghost:hover { background: rgba(0, 0, 0, 0.04); }

265 

266.cc-ic-provider-bar {

267 display: flex; align-items: center; gap: 12px;

268 padding: 14px 16px; background: var(--ic-gray-150);

269 border-radius: 8px; font-size: 13px; flex-wrap: wrap;

270}

271.cc-ic-provider-bar .cc-ic-label { color: var(--ic-gray-550); flex-shrink: 0; }

272.cc-ic-provider-pills { display: flex; gap: 4px; flex-wrap: wrap; }

273.cc-ic-p-pill {

274 appearance: none; border: none; background: transparent;

275 padding: 6px 12px; border-radius: 6px;

276 font-size: 13px; font-weight: 430; color: var(--ic-gray-700);

277 white-space: nowrap;

278}

279.cc-ic-p-pill:hover { background: rgba(0, 0, 0, 0.04); }

280.cc-ic-p-pill.cc-ic-active {

281 background: var(--ic-gray-000); color: var(--ic-slate);

282 font-weight: 500; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

283}

284.cc-ic-provider-notice {

285 display: flex; padding: 16px 18px;

286 background: var(--ic-gray-000); border: 0.5px solid var(--ic-border-default);

287 border-radius: 8px; gap: 14px; align-items: flex-start;

288}

289.cc-ic-provider-notice > svg { color: var(--ic-gray-550); margin-top: 2px; flex-shrink: 0; }

290.cc-ic-provider-notice-body { font-size: 14px; line-height: 1.55; color: var(--ic-gray-700); }

291.cc-ic-provider-notice-body strong { font-weight: 550; color: var(--ic-slate); }

292.cc-ic-provider-notice-body a { color: var(--ic-clay-deep); font-weight: 500; }

293.cc-ic-provider-notice-body a:hover { text-decoration: underline; }

294 

295.cc-ic-card { background: #141413; border-radius: 12px; overflow: hidden; }

296.cc-ic-subtabs {

297 display: flex; align-items: center;

298 background: #1a1918;

299 border-bottom: 0.5px solid rgba(255, 255, 255, 0.08);

300 padding: 0 8px; overflow-x: auto;

301}

302.cc-ic-subtab {

303 appearance: none; background: none; border: none;

304 padding: 12px 16px; font-size: 12px;

305 color: rgba(255, 255, 255, 0.5);

306 position: relative; white-space: nowrap;

307}

308.cc-ic-subtab:hover { color: rgba(255, 255, 255, 0.75); }

309.cc-ic-subtab.cc-ic-active { color: #fff; }

310.cc-ic-subtab.cc-ic-active::after {

311 content: ''; position: absolute;

312 left: 12px; right: 12px; bottom: -0.5px;

313 height: 2px; background: var(--ic-clay);

314}

315.cc-ic-shell-switch {

316 display: inline-flex; gap: 2px;

317 margin: 14px 26px 0; padding: 3px;

318 background: rgba(255, 255, 255, 0.06);

319 border: 0.5px solid rgba(255, 255, 255, 0.08);

320 border-radius: 8px;

321 font-family: inherit;

322}

323.cc-ic-shell-option {

324 font: inherit; font-size: 12px; font-weight: 500;

325 padding: 5px 12px; border-radius: 6px;

326 background: transparent; border: none;

327 color: rgba(255, 255, 255, 0.55);

328 cursor: pointer; user-select: none; white-space: nowrap;

329 transition: color 120ms ease, background-color 120ms ease;

330}

331.cc-ic-shell-option:hover { color: rgba(255, 255, 255, 0.85); }

332.cc-ic-shell-option.cc-ic-active {

333 background: rgba(255, 255, 255, 0.12);

334 color: #fff;

335 box-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);

336}

337 

338.cc-ic-card-body { padding: 24px 26px; display: flex; align-items: flex-start; gap: 14px; }

339.cc-ic-prompt {

340 color: var(--ic-clay); font-family: var(--ic-font-mono);

341 font-size: 17px; user-select: none; padding-top: 2px;

342}

343.cc-ic-cmd {

344 flex: 1; font-family: var(--ic-font-mono);

345 font-size: 17px; color: #f0eee6;

346 line-height: 1.55; white-space: pre-wrap; word-break: break-word;

347}

348.cc-ic-copy {

349 display: inline-flex; align-items: center; gap: 6px;

350 background: rgba(255, 255, 255, 0.08);

351 border: 0.5px solid rgba(255, 255, 255, 0.12);

352 color: rgba(255, 255, 255, 0.85);

353 padding: 7px 13px; border-radius: 8px;

354 font-size: 13px; font-weight: 500; flex-shrink: 0;

355}

356.cc-ic-copy:hover { background: rgba(255, 255, 255, 0.14); }

357.cc-ic-copy.cc-ic-copied { background: var(--ic-clay-deep); border-color: var(--ic-clay-deep); color: #fff; }

358 

359.cc-ic-below {

360 margin-top: 12px; font-size: 13px; color: var(--ic-gray-550);

361 display: flex; gap: 16px; flex-wrap: wrap; align-items: baseline;

362}

363.cc-ic-below a { color: var(--ic-gray-700); border-bottom: 0.5px solid var(--ic-border-default); }

364.cc-ic-below a:hover { color: var(--ic-clay-deep); border-bottom-color: var(--ic-clay-deep); }

365.cc-ic-handoff {

366 padding: 22px 24px;

367 background: linear-gradient(180deg, #faf9f4 0%, #f3f1e9 100%);

368 border: 0.5px solid var(--ic-border-default);

369 border-radius: 12px;

370 box-shadow: 0 1px 2px rgba(31, 30, 29, 0.04), 0 6px 16px -4px rgba(31, 30, 29, 0.06);

371}

372.dark .cc-ic-handoff {

373 background: linear-gradient(180deg, #262624 0%, #1f1e1d 100%);

374 box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3), 0 6px 16px -4px rgba(0, 0, 0, 0.4);

375}

376.cc-ic-handoff-title {

377 font-size: 16px; font-weight: 550; color: var(--ic-slate);

378 letter-spacing: -0.01em; margin-bottom: 4px;

379}

380.cc-ic-handoff-sub {

381 font-size: 14px; line-height: 1.5; color: var(--ic-gray-700);

382 margin-bottom: 18px;

383}

384.cc-ic-handoff-actions { display: flex; gap: 10px; flex-wrap: wrap; }

385.cc-ic-handoff-alt {

386 margin-top: 12px; font-size: 12px; color: var(--ic-gray-550);

387}

388.cc-ic-handoff-alt code {

389 font-family: var(--ic-font-mono); font-size: 11px;

390 background: var(--ic-gray-150); padding: 2px 6px;

391 border-radius: 4px; color: var(--ic-gray-700);

392}

393.cc-ic-copy-sm {

394 appearance: none; border: none;

395 display: inline-flex; align-items: center; justify-content: center;

396 width: 22px; height: 22px;

397 margin-left: 4px; vertical-align: middle;

398 background: var(--ic-gray-150); color: var(--ic-gray-550);

399 border-radius: 4px;

400 transition: color 0.1s, background-color 0.1s;

401}

402.cc-ic-copy-sm:hover { color: var(--ic-gray-700); background: var(--ic-border-default); }

403.cc-ic-copy-sm.cc-ic-copied { background: var(--ic-clay-deep); color: #fff; }

404 

405@media (max-width: 720px) {

406 .cc-ic-tab { padding: 12px 14px; font-size: 14px; }

407 .cc-ic-sales-actions { width: 100%; }

408 .cc-ic-card-body { padding: 20px; }

409 .cc-ic-cmd { font-size: 15px; }

410}

411`;

412 return <div className="cc-ic not-prose">

413 <style>{STYLES}</style>

414 

415 {}

416 <div className="cc-ic-tab-strip" role="tablist">

417 {TABS.map(t => <button key={t.key} type="button" role="tab" aria-selected={target === t.key} className={'cc-ic-tab' + (target === t.key ? ' cc-ic-active' : '')} onClick={() => setTarget(t.key)}>

418 {t.label}

419 </button>)}

420 </div>

421 

422 {}

423 <div className="cc-ic-team-wrap">

424 <button type="button" role="switch" aria-checked={team} className={'cc-ic-team-toggle' + (team ? ' cc-ic-checked' : '')} onClick={() => setTeam(!team)}>

425 <span className="cc-ic-check">{iconCheck(11)}</span>

426 <span>

427 I’m buying for a team or company (SSO, AWS/Azure/GCP, central billing)

428 </span>

429 </button>

430 </div>

431 

432 {}

433 {team && <div className="cc-ic-team-reveal">

434 <div className="cc-ic-sales">

435 <div className="cc-ic-sales-text">

436 <strong>Set up your team:</strong> self-serve or talk to sales.

437 </div>

438 <div className="cc-ic-sales-actions">

439 <a href="https://claude.ai/upgrade?initialPlanType=team&amp;utm_source=claude_code&amp;utm_medium=docs&amp;utm_content=configurator_team_get_started" className="cc-ic-btn-ghost">

440 Get started

441 </a>

442 <a href="https://www.anthropic.com/contact-sales?utm_source=claude_code&amp;utm_medium=docs&amp;utm_content=configurator_team_contact_sales" className="cc-ic-btn-clay">

443 Contact sales {iconArrowRight()}

444 </a>

445 </div>

446 </div>

447 

448 <div className="cc-ic-provider-bar">

449 <span className="cc-ic-label">Run on</span>

450 <div className="cc-ic-provider-pills" role="radiogroup" aria-label="Provider">

451 {PROVIDERS.map(p => <button key={p.key} type="button" role="radio" aria-checked={provider === p.key} className={'cc-ic-p-pill' + (provider === p.key ? ' cc-ic-active' : '')} onClick={() => setProvider(p.key)}>

452 {p.label}

453 </button>)}

454 </div>

455 </div>

456 

457 {showNotice && <div className="cc-ic-provider-notice">

458 {iconInfo()}

459 <div className="cc-ic-provider-notice-body">

460 {PROVIDER_NOTICE[provider]}

461 </div>

462 </div>}

463 </div>}

464 

465 {}

466 {target === 'terminal' && <div className="cc-ic-card">

467 <div className="cc-ic-subtabs" role="tablist" aria-label="Install method">

468 {Object.keys(TERM).map(k => <button key={k} type="button" role="tab" aria-selected={pkg === k} className={'cc-ic-subtab' + (pkg === k ? ' cc-ic-active' : '')} onClick={() => setPkg(k)}>

469 {TERM[k].label}

470 </button>)}

471 </div>

472 {isWinInstaller && <div className="cc-ic-shell-switch" role="tablist" aria-label="Shell">

473 {[{

474 k: 'ps',

475 label: 'PowerShell'

476 }, {

477 k: 'cmd',

478 label: 'CMD'

479 }].map(({k, label}) => {

480 const active = k === 'cmd' === winCmd;

481 return <button key={k} type="button" role="tab" aria-selected={active} className={'cc-ic-shell-option' + (active ? ' cc-ic-active' : '')} onClick={() => setWinCmd(k === 'cmd')}>

482 {label}

483 </button>;

484 })}

485 </div>}

486 {cardBodyCmd(terminalCmd, isWinPrompt ? '>' : '$')}

487 </div>}

488 

489 {}

490 {target === 'terminal' && <div className="cc-ic-below">

491 {isWinInstaller && <span>

492 <a href="https://git-scm.com/downloads/win" target="_blank" rel="noopener">

493 Git for Windows

494 </a>{' '}

495 recommended. PowerShell is used if Git Bash is absent.

496 </span>}

497 {(pkg === 'brew' || pkg === 'winget') && <span>

498 Does not auto-update. Run{' '}

499 <code>{pkg === 'brew' ? 'brew upgrade claude-code' : 'winget upgrade Anthropic.ClaudeCode'}</code>{' '}

500 periodically.

501 </span>}

502 <a href="/en/troubleshoot-install">Installation troubleshooting</a>

503 </div>}

504 

505 {alt && <div className="cc-ic-handoff">

506 <div className="cc-ic-handoff-title">Claude Code for {alt.name}</div>

507 <div className="cc-ic-handoff-sub">{alt.tagline}</div>

508 <div className="cc-ic-handoff-actions">

509 <a href={alt.installHref} className="cc-ic-btn-clay" {...alt.installHref.startsWith('http') ? {

510 target: '_blank',

511 rel: 'noopener'

512 } : {}}>

513 {alt.installLabel} {iconArrowUpRight(13)}

514 </a>

515 <a href={alt.guideHref} className="cc-ic-btn-ghost">

516 {alt.name} guide {iconArrowRight(12)}

517 </a>

518 </div>

519 {alt.altCmd && <div className="cc-ic-handoff-alt">

520 or run <code>{alt.altCmd}</code>

521 <button type="button" className={'cc-ic-copy-sm' + (copied === 'alt' ? ' cc-ic-copied' : '')} onClick={() => handleCopy(alt.altCmd, 'alt')} aria-label="Copy command">

522 {copied === 'alt' ? iconCheck(11) : iconCopy(11)}

523 </button>

524 </div>}

525 </div>}

526 </div>;

527};

528 

529export const Experiment = ({flag, treatment, children}) => {

530 const VID_KEY = 'exp_vid';

531 const CONSENT_COUNTRIES = new Set(['AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'RE', 'GP', 'MQ', 'GF', 'YT', 'BL', 'MF', 'PM', 'WF', 'PF', 'NC', 'AW', 'CW', 'SX', 'FO', 'GL', 'AX', 'GB', 'UK', 'AI', 'BM', 'IO', 'VG', 'KY', 'FK', 'GI', 'MS', 'PN', 'SH', 'TC', 'GG', 'JE', 'IM', 'CA', 'BR', 'IN']);

532 const fnv1a = s => {

533 let h = 0x811c9dc5;

534 for (let i = 0; i < s.length; i++) {

535 h ^= s.charCodeAt(i);

536 h += (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24);

537 }

538 return h >>> 0;

539 };

540 const bucket = (seed, vid) => fnv1a(fnv1a(seed + vid) + '') % 10000 < 5000 ? 'control' : 'treatment';

541 const [decision] = useState(() => {

542 const params = new URLSearchParams(location.search);

543 const preBucketed = document.documentElement.dataset['gb_' + flag.replace(/-/g, '_')];

544 const force = params.get('gb-force');

545 if (force) {

546 for (const p of force.split(',')) {

547 const [k, v] = p.split(':');

548 if (k === flag) return {

549 variant: v || 'treatment',

550 track: false

551 };

552 }

553 }

554 if (navigator.globalPrivacyControl) {

555 return {

556 variant: 'control',

557 track: false

558 };

559 }

560 const prefsMatch = document.cookie.match(/(?:^|; )anthropic-consent-preferences=([^;]+)/);

561 if (prefsMatch) {

562 try {

563 if (JSON.parse(decodeURIComponent(prefsMatch[1])).analytics !== true) {

564 return {

565 variant: 'control',

566 track: false

567 };

568 }

569 } catch {

570 return {

571 variant: 'control',

572 track: false

573 };

574 }

575 } else {

576 const country = params.get('country')?.toUpperCase() || (document.cookie.match(/(?:^|; )cf_geo=([A-Z]{2})/) || [])[1];

577 if (!country || CONSENT_COUNTRIES.has(country)) {

578 return {

579 variant: 'control',

580 track: false

581 };

582 }

583 }

584 let vid;

585 try {

586 const ajsMatch = document.cookie.match(/(?:^|; )ajs_anonymous_id=([^;]+)/);

587 if (ajsMatch) {

588 vid = decodeURIComponent(ajsMatch[1]).replace(/^"|"$/g, '');

589 } else {

590 vid = localStorage.getItem(VID_KEY);

591 if (!vid) {

592 vid = crypto.randomUUID();

593 }

594 document.cookie = `ajs_anonymous_id=${vid}; domain=.claude.com; path=/; Secure; SameSite=Lax; max-age=31536000`;

595 }

596 try {

597 localStorage.setItem(VID_KEY, vid);

598 } catch {}

599 } catch {

600 return {

601 variant: 'control',

602 track: false

603 };

604 }

605 const variant = preBucketed === '1' ? 'treatment' : preBucketed === '0' ? 'control' : bucket(flag, vid);

606 return {

607 variant,

608 track: true,

609 vid

610 };

611 });

612 useEffect(() => {

613 if (!decision.track) return;

614 fetch('https://api.anthropic.com/api/event_logging/v2/batch', {

615 method: 'POST',

616 headers: {

617 'Content-Type': 'application/json',

618 'x-service-name': 'claude_code_docs'

619 },

620 body: JSON.stringify({

621 events: [{

622 event_type: 'GrowthbookExperimentEvent',

623 event_data: {

624 device_id: decision.vid,

625 anonymous_id: decision.vid,

626 timestamp: new Date().toISOString(),

627 experiment_id: flag,

628 variation_id: decision.variant === 'treatment' ? 1 : 0,

629 environment: 'production'

630 }

631 }]

632 }),

633 keepalive: true

634 }).catch(() => {});

635 }, []);

636 return decision.variant === 'treatment' ? treatment : children;

637};

638 

639Claude Code 是一个由 AI 驱动的编码助手,可帮助你构建功能、修复错误和自动化开发任务。它理解你的整个代码库,可以跨多个文件和工具工作以完成任务。9Claude Code 是一个由 AI 驱动的编码助手,可帮助你构建功能、修复错误和自动化开发任务。它理解你的整个代码库,可以跨多个文件和工具工作以完成任务。

640 10 

641<div data-gb-slot="overview-install-configurator">

642 <Experiment flag="overview-install-configurator" treatment={<InstallConfigurator />} />

643</div>

644 

645## 开始使用11## 开始使用

646 12 

647选择你的环境来开始使用。大多数界面需要 [Claude 订阅](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=overview_pricing) 或 [Anthropic 控制台](https://console.anthropic.com/) 账户。终端 CLI 和 VS Code 也支持[第三方提供商](/zh-CN/third-party-integrations)。13选择你的环境来开始使用。大多数界面需要 [Claude 订阅](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=overview_pricing) 或 [Anthropic 控制台](https://console.anthropic.com/) 账户。终端 CLI 和 VS Code 也支持[第三方提供商](/zh-CN/third-party-integrations)。


798 <Accordion title="使用说明、skills 和 hooks 进行自定义" icon="sliders">164 <Accordion title="使用说明、skills 和 hooks 进行自定义" icon="sliders">

799 [`CLAUDE.md`](/zh-CN/memory) 是一个 markdown 文件,你可以将其添加到项目根目录,Claude Code 会在每个会话开始时读取它。使用它来设置编码标准、架构决策、首选库和审查清单。Claude 还会在工作时构建[自动内存](/zh-CN/memory#auto-memory),保存学习内容,如构建命令和调试见解,跨会话使用,无需你编写任何内容。165 [`CLAUDE.md`](/zh-CN/memory) 是一个 markdown 文件,你可以将其添加到项目根目录,Claude Code 会在每个会话开始时读取它。使用它来设置编码标准、架构决策、首选库和审查清单。Claude 还会在工作时构建[自动内存](/zh-CN/memory#auto-memory),保存学习内容,如构建命令和调试见解,跨会话使用,无需你编写任何内容。

800 166 

801 创建[自定义命令](/zh-CN/skills)来打包你的团队可以共享的可重复工作流,如 `/review-pr` 或 `/deploy-staging`。167 创建 [skills](/zh-CN/skills) 来打包你的团队可以共享的可重复工作流,如 `/review-pr` 或 `/deploy-staging`。

802 168 

803 [Hooks](/zh-CN/hooks) 让你在 Claude Code 操作之前或之后运行 shell 命令,如在每次文件编辑后自动格式化或在提交前运行 lint。169 [Hooks](/zh-CN/hooks) 让你在 Claude Code 操作之前或之后运行 shell 命令,如在每次文件编辑后自动格式化或在提交前运行 lint。

804 </Accordion>170 </Accordion>

plugins.md +9 −1

Details

317 317 

318要测试已打包为 `.zip` 存档并托管在 URL 上的插件(例如 CI 构建工件),请改用 `--plugin-url`。Claude Code 在启动时获取存档并仅为该会话加载它。如果获取失败或存档无效,Claude Code 会报告插件加载错误并在没有它的情况下启动。与任何插件源相同的[信任考虑](/zh-CN/discover-plugins#security)适用:仅将此标志指向你控制或信任的存档。318要测试已打包为 `.zip` 存档并托管在 URL 上的插件(例如 CI 构建工件),请改用 `--plugin-url`。Claude Code 在启动时获取存档并仅为该会话加载它。如果获取失败或存档无效,Claude Code 会报告插件加载错误并在没有它的情况下启动。与任何插件源相同的[信任考虑](/zh-CN/discover-plugins#security)适用:仅将此标志指向你控制或信任的存档。

319 319 

320要加载多个插件,请为每个 URL 重复该标志:

321 

322```bash theme={null}

323claude --plugin-url https://example.com/my-plugin.zip --plugin-url https://example.com/other.zip

324```

325 

326或将空格分隔的 URL 作为一个带引号的参数传递:

327 

320```bash theme={null}328```bash theme={null}

321claude --plugin-url https://example.com/my-plugin.zip329claude --plugin-url "https://example.com/my-plugin.zip https://example.com/other.zip"

322```330```

323 331 

324### 调试插件问题332### 调试插件问题

quickstart.md +4 −637

Details

6 6 

7> 欢迎使用 Claude Code!7> 欢迎使用 Claude Code!

8 8 

9export const InstallConfigurator = ({defaultSurface = 'terminal'}) => {

10 const TERM = {

11 mac: {

12 label: 'macOS / Linux',

13 cmd: 'curl -fsSL https://claude.ai/install.sh | bash'

14 },

15 win: {

16 label: 'Windows'

17 },

18 brew: {

19 label: 'Homebrew',

20 cmd: 'brew install --cask claude-code'

21 },

22 winget: {

23 label: 'WinGet',

24 cmd: 'winget install Anthropic.ClaudeCode'

25 }

26 };

27 const WIN_VARIANTS = {

28 ps: 'irm https://claude.ai/install.ps1 | iex',

29 cmd: 'curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd'

30 };

31 const TABS = [{

32 key: 'terminal',

33 label: 'Terminal'

34 }, {

35 key: 'desktop',

36 label: 'Desktop'

37 }, {

38 key: 'vscode',

39 label: 'VS Code'

40 }, {

41 key: 'jetbrains',

42 label: 'JetBrains'

43 }];

44 const ALT_TARGETS = {

45 desktop: {

46 name: 'Desktop',

47 tagline: 'The full agent in a native app for macOS and Windows.',

48 installLabel: 'Download the app',

49 installHref: 'https://claude.com/download?utm_source=claude_code&utm_medium=docs&utm_content=configurator_desktop_download',

50 guideHref: '/en/desktop-quickstart'

51 },

52 vscode: {

53 name: 'VS Code',

54 tagline: 'Review diffs, manage context, and chat without leaving your editor.',

55 installLabel: 'Install from Marketplace',

56 installHref: 'https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code',

57 altCmd: 'code --install-extension anthropic.claude-code',

58 guideHref: '/en/vs-code'

59 },

60 jetbrains: {

61 name: 'JetBrains',

62 tagline: 'Native plugin for IntelliJ, PyCharm, WebStorm, and other JetBrains IDEs.',

63 installLabel: 'Install from Marketplace',

64 installHref: 'https://plugins.jetbrains.com/plugin/27310-claude-code-beta-',

65 guideHref: '/en/jetbrains'

66 }

67 };

68 const PROVIDERS = [{

69 key: 'anthropic',

70 label: 'Anthropic'

71 }, {

72 key: 'bedrock',

73 label: 'Amazon Bedrock'

74 }, {

75 key: 'foundry',

76 label: 'Microsoft Foundry'

77 }, {

78 key: 'vertex',

79 label: 'Google Vertex AI'

80 }];

81 const PROVIDER_NOTICE = {

82 bedrock: <>

83 <strong>Configure your AWS account first.</strong> Running on Bedrock

84 requires model access enabled in the AWS console and IAM credentials.{' '}

85 <a href="/en/amazon-bedrock">Bedrock setup guide →</a>

86 </>,

87 vertex: <>

88 <strong>Configure your GCP project first.</strong> Running on Vertex AI

89 requires the Vertex API enabled and a service account with the right

90 permissions.{' '}

91 <a href="/en/google-vertex-ai">Vertex setup guide →</a>

92 </>,

93 foundry: <>

94 <strong>Configure your Azure resources first.</strong> Running on

95 Microsoft Foundry requires an Azure subscription with a Foundry resource

96 and model deployments provisioned.{' '}

97 <a href="/en/microsoft-foundry">Foundry setup guide →</a>

98 </>

99 };

100 const iconCheck = (size = 14) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

101 <polyline points="20 6 9 17 4 12" />

102 </svg>;

103 const iconCopy = (size = 14) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

104 <rect x="9" y="9" width="13" height="13" rx="2" />

105 <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />

106 </svg>;

107 const iconArrowRight = (size = 13) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

108 <line x1="5" y1="12" x2="19" y2="12" />

109 <polyline points="12 5 19 12 12 19" />

110 </svg>;

111 const iconArrowUpRight = (size = 14) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

112 <line x1="7" y1="17" x2="17" y2="7" />

113 <polyline points="7 7 17 7 17 17" />

114 </svg>;

115 const iconInfo = (size = 16) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

116 <circle cx="12" cy="12" r="10" />

117 <line x1="12" y1="16" x2="12" y2="12" />

118 <line x1="12" y1="8" x2="12.01" y2="8" />

119 </svg>;

120 const [target, setTarget] = useState(defaultSurface);

121 const [team, setTeam] = useState(false);

122 const [provider, setProvider] = useState('anthropic');

123 const [pkg, setPkg] = useState(() => (/Win/).test(navigator.userAgent) ? 'win' : 'mac');

124 const [winCmd, setWinCmd] = useState(false);

125 const [copied, setCopied] = useState(null);

126 const copyTimer = useRef(null);

127 const handleCopy = async (text, key) => {

128 try {

129 await navigator.clipboard.writeText(text);

130 } catch {

131 const ta = document.createElement('textarea');

132 ta.value = text;

133 document.body.appendChild(ta);

134 ta.select();

135 document.execCommand('copy');

136 document.body.removeChild(ta);

137 }

138 clearTimeout(copyTimer.current);

139 setCopied(key);

140 copyTimer.current = setTimeout(() => setCopied(null), 1800);

141 };

142 const cardBodyCmd = (cmd, prompt) => {

143 const on = copied === 'term';

144 return <div className="cc-ic-card-body">

145 <span className="cc-ic-prompt">{prompt || '$'}</span>

146 <div className="cc-ic-cmd">{cmd}</div>

147 <button type="button" className={'cc-ic-copy' + (on ? ' cc-ic-copied' : '')} onClick={() => handleCopy(cmd, 'term')}>

148 {on ? iconCheck(13) : iconCopy(13)}

149 <span>{on ? 'Copied' : 'Copy'}</span>

150 </button>

151 </div>;

152 };

153 const isWinInstaller = pkg === 'win';

154 const isWinPrompt = pkg === 'win' || pkg === 'winget';

155 const terminalCmd = isWinInstaller ? WIN_VARIANTS[winCmd ? 'cmd' : 'ps'] : TERM[pkg].cmd;

156 const alt = ALT_TARGETS[target];

157 const showNotice = team && provider !== 'anthropic';

158 const STYLES = `

159.cc-ic {

160 --ic-slate: #141413;

161 --ic-clay: #d97757;

162 --ic-clay-deep: #c6613f;

163 --ic-gray-000: #ffffff;

164 --ic-gray-150: #f0eee6;

165 --ic-gray-550: #73726c;

166 --ic-gray-700: #3d3d3a;

167 --ic-border-subtle: rgba(31, 30, 29, 0.08);

168 --ic-border-default: rgba(31, 30, 29, 0.15);

169 --ic-border-strong: rgba(31, 30, 29, 0.3);

170 --ic-font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, 'Courier New', monospace;

171 font-family: 'Anthropic Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;

172 font-size: 14px; line-height: 1.5; color: var(--ic-slate);

173 margin: 8px 0 32px;

174}

175.dark .cc-ic {

176 --ic-slate: #f0eee6;

177 --ic-gray-000: #262624;

178 --ic-gray-150: #1f1e1d;

179 --ic-gray-550: #91908a;

180 --ic-gray-700: #bfbdb4;

181 --ic-border-subtle: rgba(240, 238, 230, 0.08);

182 --ic-border-default: rgba(240, 238, 230, 0.14);

183 --ic-border-strong: rgba(240, 238, 230, 0.28);

184}

185.dark .cc-ic-check { background: transparent; }

186.dark .cc-ic-card { border: 0.5px solid var(--ic-border-subtle); }

187.dark .cc-ic-p-pill.cc-ic-active { box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3); }

188.cc-ic *, .cc-ic *::before, .cc-ic *::after { box-sizing: border-box; }

189.cc-ic a { text-decoration: none; }

190.cc-ic a:not([class]) { color: inherit; }

191.cc-ic button { font-family: inherit; cursor: pointer; }

192 

193.cc-ic-tab-strip {

194 display: inline-flex; gap: 2px;

195 padding: 4px; background: var(--ic-gray-150);

196 border-radius: 10px; overflow-x: auto;

197 max-width: 100%;

198}

199.cc-ic-tab {

200 appearance: none; background: none; border: none;

201 padding: 10px 18px; font-size: 15px; font-weight: 430;

202 color: var(--ic-gray-550); border-radius: 7px;

203 white-space: nowrap;

204 transition: color 0.12s, background-color 0.12s;

205}

206.cc-ic-tab:hover { color: var(--ic-gray-700); }

207.cc-ic-tab.cc-ic-active {

208 color: var(--ic-slate); font-weight: 500;

209 background: var(--ic-gray-000);

210 box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);

211}

212.dark .cc-ic-tab.cc-ic-active { box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4); }

213 

214.cc-ic-team-wrap { padding: 16px 0 20px; }

215.cc-ic-team-toggle {

216 display: flex; align-items: center; gap: 12px; font-family: inherit;

217 padding: 12px 16px; font-size: 14px; font-weight: 430;

218 color: var(--ic-gray-700); cursor: pointer; user-select: none;

219 width: fit-content; background: var(--ic-gray-150);

220 border: 0.5px solid var(--ic-border-subtle); border-radius: 8px;

221 transition: border-color 0.15s;

222}

223.cc-ic-team-toggle:hover { border-color: var(--ic-border-default); }

224.cc-ic-team-toggle.cc-ic-checked {

225 background: rgba(217, 119, 87, 0.08);

226 border-color: rgba(217, 119, 87, 0.25);

227}

228.cc-ic-check {

229 width: 16px; height: 16px;

230 border: 1px solid var(--ic-border-strong); border-radius: 4px;

231 background: var(--ic-gray-000);

232 display: flex; align-items: center; justify-content: center;

233 flex-shrink: 0;

234}

235.cc-ic-check svg { color: #fff; display: none; }

236.cc-ic-team-toggle.cc-ic-checked .cc-ic-check { background: var(--ic-clay-deep); border-color: var(--ic-clay-deep); }

237.cc-ic-team-toggle.cc-ic-checked .cc-ic-check svg { display: block; }

238 

239.cc-ic-team-reveal { display: flex; flex-direction: column; gap: 12px; margin-bottom: 16px; }

240.cc-ic-sales {

241 display: flex; align-items: center; justify-content: space-between;

242 gap: 16px; padding: 14px 16px;

243 background: var(--ic-gray-000); border: 0.5px solid var(--ic-border-default);

244 border-radius: 8px; flex-wrap: wrap;

245}

246.cc-ic-sales-text { font-size: 13px; color: var(--ic-gray-700); line-height: 1.5; flex: 1; min-width: 200px; }

247.cc-ic-sales-text strong { font-weight: 550; color: var(--ic-slate); }

248.cc-ic-sales-actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }

249.cc-ic-btn-clay {

250 display: inline-flex; align-items: center; gap: 8px;

251 background: var(--ic-clay-deep); color: #fff; border: none;

252 border-radius: 8px; padding: 8px 14px;

253 font-size: 13px; font-weight: 500;

254 transition: background-color 0.15s; white-space: nowrap;

255}

256.cc-ic-btn-clay:hover { background: var(--ic-clay); }

257.cc-ic-btn-ghost {

258 display: inline-flex; align-items: center; gap: 8px;

259 background: transparent; color: var(--ic-gray-700);

260 border: 0.5px solid var(--ic-border-default);

261 border-radius: 8px; padding: 8px 14px;

262 font-size: 13px; font-weight: 500;

263}

264.cc-ic-btn-ghost:hover { background: rgba(0, 0, 0, 0.04); }

265 

266.cc-ic-provider-bar {

267 display: flex; align-items: center; gap: 12px;

268 padding: 14px 16px; background: var(--ic-gray-150);

269 border-radius: 8px; font-size: 13px; flex-wrap: wrap;

270}

271.cc-ic-provider-bar .cc-ic-label { color: var(--ic-gray-550); flex-shrink: 0; }

272.cc-ic-provider-pills { display: flex; gap: 4px; flex-wrap: wrap; }

273.cc-ic-p-pill {

274 appearance: none; border: none; background: transparent;

275 padding: 6px 12px; border-radius: 6px;

276 font-size: 13px; font-weight: 430; color: var(--ic-gray-700);

277 white-space: nowrap;

278}

279.cc-ic-p-pill:hover { background: rgba(0, 0, 0, 0.04); }

280.cc-ic-p-pill.cc-ic-active {

281 background: var(--ic-gray-000); color: var(--ic-slate);

282 font-weight: 500; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

283}

284.cc-ic-provider-notice {

285 display: flex; padding: 16px 18px;

286 background: var(--ic-gray-000); border: 0.5px solid var(--ic-border-default);

287 border-radius: 8px; gap: 14px; align-items: flex-start;

288}

289.cc-ic-provider-notice > svg { color: var(--ic-gray-550); margin-top: 2px; flex-shrink: 0; }

290.cc-ic-provider-notice-body { font-size: 14px; line-height: 1.55; color: var(--ic-gray-700); }

291.cc-ic-provider-notice-body strong { font-weight: 550; color: var(--ic-slate); }

292.cc-ic-provider-notice-body a { color: var(--ic-clay-deep); font-weight: 500; }

293.cc-ic-provider-notice-body a:hover { text-decoration: underline; }

294 

295.cc-ic-card { background: #141413; border-radius: 12px; overflow: hidden; }

296.cc-ic-subtabs {

297 display: flex; align-items: center;

298 background: #1a1918;

299 border-bottom: 0.5px solid rgba(255, 255, 255, 0.08);

300 padding: 0 8px; overflow-x: auto;

301}

302.cc-ic-subtab {

303 appearance: none; background: none; border: none;

304 padding: 12px 16px; font-size: 12px;

305 color: rgba(255, 255, 255, 0.5);

306 position: relative; white-space: nowrap;

307}

308.cc-ic-subtab:hover { color: rgba(255, 255, 255, 0.75); }

309.cc-ic-subtab.cc-ic-active { color: #fff; }

310.cc-ic-subtab.cc-ic-active::after {

311 content: ''; position: absolute;

312 left: 12px; right: 12px; bottom: -0.5px;

313 height: 2px; background: var(--ic-clay);

314}

315.cc-ic-shell-switch {

316 display: inline-flex; gap: 2px;

317 margin: 14px 26px 0; padding: 3px;

318 background: rgba(255, 255, 255, 0.06);

319 border: 0.5px solid rgba(255, 255, 255, 0.08);

320 border-radius: 8px;

321 font-family: inherit;

322}

323.cc-ic-shell-option {

324 font: inherit; font-size: 12px; font-weight: 500;

325 padding: 5px 12px; border-radius: 6px;

326 background: transparent; border: none;

327 color: rgba(255, 255, 255, 0.55);

328 cursor: pointer; user-select: none; white-space: nowrap;

329 transition: color 120ms ease, background-color 120ms ease;

330}

331.cc-ic-shell-option:hover { color: rgba(255, 255, 255, 0.85); }

332.cc-ic-shell-option.cc-ic-active {

333 background: rgba(255, 255, 255, 0.12);

334 color: #fff;

335 box-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);

336}

337 

338.cc-ic-card-body { padding: 24px 26px; display: flex; align-items: flex-start; gap: 14px; }

339.cc-ic-prompt {

340 color: var(--ic-clay); font-family: var(--ic-font-mono);

341 font-size: 17px; user-select: none; padding-top: 2px;

342}

343.cc-ic-cmd {

344 flex: 1; font-family: var(--ic-font-mono);

345 font-size: 17px; color: #f0eee6;

346 line-height: 1.55; white-space: pre-wrap; word-break: break-word;

347}

348.cc-ic-copy {

349 display: inline-flex; align-items: center; gap: 6px;

350 background: rgba(255, 255, 255, 0.08);

351 border: 0.5px solid rgba(255, 255, 255, 0.12);

352 color: rgba(255, 255, 255, 0.85);

353 padding: 7px 13px; border-radius: 8px;

354 font-size: 13px; font-weight: 500; flex-shrink: 0;

355}

356.cc-ic-copy:hover { background: rgba(255, 255, 255, 0.14); }

357.cc-ic-copy.cc-ic-copied { background: var(--ic-clay-deep); border-color: var(--ic-clay-deep); color: #fff; }

358 

359.cc-ic-below {

360 margin-top: 12px; font-size: 13px; color: var(--ic-gray-550);

361 display: flex; gap: 16px; flex-wrap: wrap; align-items: baseline;

362}

363.cc-ic-below a { color: var(--ic-gray-700); border-bottom: 0.5px solid var(--ic-border-default); }

364.cc-ic-below a:hover { color: var(--ic-clay-deep); border-bottom-color: var(--ic-clay-deep); }

365.cc-ic-handoff {

366 padding: 22px 24px;

367 background: linear-gradient(180deg, #faf9f4 0%, #f3f1e9 100%);

368 border: 0.5px solid var(--ic-border-default);

369 border-radius: 12px;

370 box-shadow: 0 1px 2px rgba(31, 30, 29, 0.04), 0 6px 16px -4px rgba(31, 30, 29, 0.06);

371}

372.dark .cc-ic-handoff {

373 background: linear-gradient(180deg, #262624 0%, #1f1e1d 100%);

374 box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3), 0 6px 16px -4px rgba(0, 0, 0, 0.4);

375}

376.cc-ic-handoff-title {

377 font-size: 16px; font-weight: 550; color: var(--ic-slate);

378 letter-spacing: -0.01em; margin-bottom: 4px;

379}

380.cc-ic-handoff-sub {

381 font-size: 14px; line-height: 1.5; color: var(--ic-gray-700);

382 margin-bottom: 18px;

383}

384.cc-ic-handoff-actions { display: flex; gap: 10px; flex-wrap: wrap; }

385.cc-ic-handoff-alt {

386 margin-top: 12px; font-size: 12px; color: var(--ic-gray-550);

387}

388.cc-ic-handoff-alt code {

389 font-family: var(--ic-font-mono); font-size: 11px;

390 background: var(--ic-gray-150); padding: 2px 6px;

391 border-radius: 4px; color: var(--ic-gray-700);

392}

393.cc-ic-copy-sm {

394 appearance: none; border: none;

395 display: inline-flex; align-items: center; justify-content: center;

396 width: 22px; height: 22px;

397 margin-left: 4px; vertical-align: middle;

398 background: var(--ic-gray-150); color: var(--ic-gray-550);

399 border-radius: 4px;

400 transition: color 0.1s, background-color 0.1s;

401}

402.cc-ic-copy-sm:hover { color: var(--ic-gray-700); background: var(--ic-border-default); }

403.cc-ic-copy-sm.cc-ic-copied { background: var(--ic-clay-deep); color: #fff; }

404 

405@media (max-width: 720px) {

406 .cc-ic-tab { padding: 12px 14px; font-size: 14px; }

407 .cc-ic-sales-actions { width: 100%; }

408 .cc-ic-card-body { padding: 20px; }

409 .cc-ic-cmd { font-size: 15px; }

410}

411`;

412 return <div className="cc-ic not-prose">

413 <style>{STYLES}</style>

414 

415 {}

416 <div className="cc-ic-tab-strip" role="tablist">

417 {TABS.map(t => <button key={t.key} type="button" role="tab" aria-selected={target === t.key} className={'cc-ic-tab' + (target === t.key ? ' cc-ic-active' : '')} onClick={() => setTarget(t.key)}>

418 {t.label}

419 </button>)}

420 </div>

421 

422 {}

423 <div className="cc-ic-team-wrap">

424 <button type="button" role="switch" aria-checked={team} className={'cc-ic-team-toggle' + (team ? ' cc-ic-checked' : '')} onClick={() => setTeam(!team)}>

425 <span className="cc-ic-check">{iconCheck(11)}</span>

426 <span>

427 I’m buying for a team or company (SSO, AWS/Azure/GCP, central billing)

428 </span>

429 </button>

430 </div>

431 

432 {}

433 {team && <div className="cc-ic-team-reveal">

434 <div className="cc-ic-sales">

435 <div className="cc-ic-sales-text">

436 <strong>Set up your team:</strong> self-serve or talk to sales.

437 </div>

438 <div className="cc-ic-sales-actions">

439 <a href="https://claude.ai/upgrade?initialPlanType=team&amp;utm_source=claude_code&amp;utm_medium=docs&amp;utm_content=configurator_team_get_started" className="cc-ic-btn-ghost">

440 Get started

441 </a>

442 <a href="https://www.anthropic.com/contact-sales?utm_source=claude_code&amp;utm_medium=docs&amp;utm_content=configurator_team_contact_sales" className="cc-ic-btn-clay">

443 Contact sales {iconArrowRight()}

444 </a>

445 </div>

446 </div>

447 

448 <div className="cc-ic-provider-bar">

449 <span className="cc-ic-label">Run on</span>

450 <div className="cc-ic-provider-pills" role="radiogroup" aria-label="Provider">

451 {PROVIDERS.map(p => <button key={p.key} type="button" role="radio" aria-checked={provider === p.key} className={'cc-ic-p-pill' + (provider === p.key ? ' cc-ic-active' : '')} onClick={() => setProvider(p.key)}>

452 {p.label}

453 </button>)}

454 </div>

455 </div>

456 

457 {showNotice && <div className="cc-ic-provider-notice">

458 {iconInfo()}

459 <div className="cc-ic-provider-notice-body">

460 {PROVIDER_NOTICE[provider]}

461 </div>

462 </div>}

463 </div>}

464 

465 {}

466 {target === 'terminal' && <div className="cc-ic-card">

467 <div className="cc-ic-subtabs" role="tablist" aria-label="Install method">

468 {Object.keys(TERM).map(k => <button key={k} type="button" role="tab" aria-selected={pkg === k} className={'cc-ic-subtab' + (pkg === k ? ' cc-ic-active' : '')} onClick={() => setPkg(k)}>

469 {TERM[k].label}

470 </button>)}

471 </div>

472 {isWinInstaller && <div className="cc-ic-shell-switch" role="tablist" aria-label="Shell">

473 {[{

474 k: 'ps',

475 label: 'PowerShell'

476 }, {

477 k: 'cmd',

478 label: 'CMD'

479 }].map(({k, label}) => {

480 const active = k === 'cmd' === winCmd;

481 return <button key={k} type="button" role="tab" aria-selected={active} className={'cc-ic-shell-option' + (active ? ' cc-ic-active' : '')} onClick={() => setWinCmd(k === 'cmd')}>

482 {label}

483 </button>;

484 })}

485 </div>}

486 {cardBodyCmd(terminalCmd, isWinPrompt ? '>' : '$')}

487 </div>}

488 

489 {}

490 {target === 'terminal' && <div className="cc-ic-below">

491 {isWinInstaller && <span>

492 <a href="https://git-scm.com/downloads/win" target="_blank" rel="noopener">

493 Git for Windows

494 </a>{' '}

495 recommended. PowerShell is used if Git Bash is absent.

496 </span>}

497 {(pkg === 'brew' || pkg === 'winget') && <span>

498 Does not auto-update. Run{' '}

499 <code>{pkg === 'brew' ? 'brew upgrade claude-code' : 'winget upgrade Anthropic.ClaudeCode'}</code>{' '}

500 periodically.

501 </span>}

502 <a href="/en/troubleshoot-install">Installation troubleshooting</a>

503 </div>}

504 

505 {alt && <div className="cc-ic-handoff">

506 <div className="cc-ic-handoff-title">Claude Code for {alt.name}</div>

507 <div className="cc-ic-handoff-sub">{alt.tagline}</div>

508 <div className="cc-ic-handoff-actions">

509 <a href={alt.installHref} className="cc-ic-btn-clay" {...alt.installHref.startsWith('http') ? {

510 target: '_blank',

511 rel: 'noopener'

512 } : {}}>

513 {alt.installLabel} {iconArrowUpRight(13)}

514 </a>

515 <a href={alt.guideHref} className="cc-ic-btn-ghost">

516 {alt.name} guide {iconArrowRight(12)}

517 </a>

518 </div>

519 {alt.altCmd && <div className="cc-ic-handoff-alt">

520 or run <code>{alt.altCmd}</code>

521 <button type="button" className={'cc-ic-copy-sm' + (copied === 'alt' ? ' cc-ic-copied' : '')} onClick={() => handleCopy(alt.altCmd, 'alt')} aria-label="Copy command">

522 {copied === 'alt' ? iconCheck(11) : iconCopy(11)}

523 </button>

524 </div>}

525 </div>}

526 </div>;

527};

528 

529export const Experiment = ({flag, treatment, children}) => {

530 const VID_KEY = 'exp_vid';

531 const CONSENT_COUNTRIES = new Set(['AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'RE', 'GP', 'MQ', 'GF', 'YT', 'BL', 'MF', 'PM', 'WF', 'PF', 'NC', 'AW', 'CW', 'SX', 'FO', 'GL', 'AX', 'GB', 'UK', 'AI', 'BM', 'IO', 'VG', 'KY', 'FK', 'GI', 'MS', 'PN', 'SH', 'TC', 'GG', 'JE', 'IM', 'CA', 'BR', 'IN']);

532 const fnv1a = s => {

533 let h = 0x811c9dc5;

534 for (let i = 0; i < s.length; i++) {

535 h ^= s.charCodeAt(i);

536 h += (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24);

537 }

538 return h >>> 0;

539 };

540 const bucket = (seed, vid) => fnv1a(fnv1a(seed + vid) + '') % 10000 < 5000 ? 'control' : 'treatment';

541 const [decision] = useState(() => {

542 const params = new URLSearchParams(location.search);

543 const preBucketed = document.documentElement.dataset['gb_' + flag.replace(/-/g, '_')];

544 const force = params.get('gb-force');

545 if (force) {

546 for (const p of force.split(',')) {

547 const [k, v] = p.split(':');

548 if (k === flag) return {

549 variant: v || 'treatment',

550 track: false

551 };

552 }

553 }

554 if (navigator.globalPrivacyControl) {

555 return {

556 variant: 'control',

557 track: false

558 };

559 }

560 const prefsMatch = document.cookie.match(/(?:^|; )anthropic-consent-preferences=([^;]+)/);

561 if (prefsMatch) {

562 try {

563 if (JSON.parse(decodeURIComponent(prefsMatch[1])).analytics !== true) {

564 return {

565 variant: 'control',

566 track: false

567 };

568 }

569 } catch {

570 return {

571 variant: 'control',

572 track: false

573 };

574 }

575 } else {

576 const country = params.get('country')?.toUpperCase() || (document.cookie.match(/(?:^|; )cf_geo=([A-Z]{2})/) || [])[1];

577 if (!country || CONSENT_COUNTRIES.has(country)) {

578 return {

579 variant: 'control',

580 track: false

581 };

582 }

583 }

584 let vid;

585 try {

586 const ajsMatch = document.cookie.match(/(?:^|; )ajs_anonymous_id=([^;]+)/);

587 if (ajsMatch) {

588 vid = decodeURIComponent(ajsMatch[1]).replace(/^"|"$/g, '');

589 } else {

590 vid = localStorage.getItem(VID_KEY);

591 if (!vid) {

592 vid = crypto.randomUUID();

593 }

594 document.cookie = `ajs_anonymous_id=${vid}; domain=.claude.com; path=/; Secure; SameSite=Lax; max-age=31536000`;

595 }

596 try {

597 localStorage.setItem(VID_KEY, vid);

598 } catch {}

599 } catch {

600 return {

601 variant: 'control',

602 track: false

603 };

604 }

605 const variant = preBucketed === '1' ? 'treatment' : preBucketed === '0' ? 'control' : bucket(flag, vid);

606 return {

607 variant,

608 track: true,

609 vid

610 };

611 });

612 useEffect(() => {

613 if (!decision.track) return;

614 fetch('https://api.anthropic.com/api/event_logging/v2/batch', {

615 method: 'POST',

616 headers: {

617 'Content-Type': 'application/json',

618 'x-service-name': 'claude_code_docs'

619 },

620 body: JSON.stringify({

621 events: [{

622 event_type: 'GrowthbookExperimentEvent',

623 event_data: {

624 device_id: decision.vid,

625 anonymous_id: decision.vid,

626 timestamp: new Date().toISOString(),

627 experiment_id: flag,

628 variation_id: decision.variant === 'treatment' ? 1 : 0,

629 environment: 'production'

630 }

631 }]

632 }),

633 keepalive: true

634 }).catch(() => {});

635 }, []);

636 return decision.variant === 'treatment' ? treatment : children;

637};

638 

639本快速开始指南将在几分钟内让您使用 AI 驱动的编码辅助。完成本指南后,您将了解如何使用 Claude Code 完成常见的开发任务。9本快速开始指南将在几分钟内让您使用 AI 驱动的编码辅助。完成本指南后,您将了解如何使用 Claude Code 完成常见的开发任务。

640 10 

641<Experiment flag="quickstart-install-configurator" treatment={<InstallConfigurator />} />

642 

643## 开始前11## 开始前

644 12 

645确保您拥有:13确保您拥有:


647* 打开的终端或命令提示符15* 打开的终端或命令提示符

648 * 如果您之前从未使用过终端,请查看[终端指南](/zh-CN/terminal-guide)16 * 如果您之前从未使用过终端,请查看[终端指南](/zh-CN/terminal-guide)

649* 一个可以使用的代码项目17* 一个可以使用的代码项目

650* 一个 [Claude 订阅](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=quickstart_prereq)(Pro、Max、Teams 或 Enterprise)、[Claude Console](https://console.anthropic.com/) 账户,或通过[支持的云提供商](/zh-CN/third-party-integrations)的访问权限18* 一个 [Claude 订阅](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=quickstart_prereq)(Pro、Max、Team 或 Enterprise)、[Claude Console](https://console.anthropic.com/) 账户,或通过[支持的云提供商](/zh-CN/third-party-integrations)的访问权限

651 19 

652<Note>20<Note>

653 本指南涵盖终端 CLI。Claude Code 也可在[网页](https://claude.ai/code)、[桌面应用](/zh-CN/desktop)、[VS Code](/zh-CN/vs-code) 和 [JetBrains IDE](/zh-CN/jetbrains)、[Slack](/zh-CN/slack) 中使用,以及通过 [GitHub Actions](/zh-CN/github-actions) 和 [GitLab](/zh-CN/gitlab-ci-cd) 进行 CI/CD。查看[所有界面](/zh-CN/overview#use-claude-code-everywhere)。21 本指南涵盖终端 CLI。Claude Code 也可在[网页](https://claude.ai/code)、[桌面应用](/zh-CN/desktop)、[VS Code](/zh-CN/vs-code) 和 [JetBrains IDE](/zh-CN/jetbrains)、[Slack](/zh-CN/slack) 中使用,以及通过 [GitHub Actions](/zh-CN/github-actions) 和 [GitLab](/zh-CN/gitlab-ci-cd) 进行 CI/CD。查看[所有界面](/zh-CN/overview#use-claude-code-everywhere)。


727 95 

728您可以使用以下任何账户类型登录:96您可以使用以下任何账户类型登录:

729 97 

730* [Claude Pro、Max、Teams 或 Enterprise](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=quickstart_login)(推荐)98* [Claude Pro、Max、Team 或 Enterprise](https://claude.com/pricing?utm_source=claude_code\&utm_medium=docs\&utm_content=quickstart_login)(推荐)

731* [Claude Console](https://console.anthropic.com/)(具有预付费额度的 API 访问)。首次登录时,Console 中会自动为集中成本跟踪创建一个"Claude Code"工作区。99* [Claude Console](https://console.anthropic.com/)(具有预付费额度的 API 访问)。首次登录时,Console 中会自动为集中成本跟踪创建一个"Claude Code"工作区。

732* [Amazon Bedrock、Google Vertex AI 或 Microsoft Foundry](/zh-CN/third-party-integrations)(企业云提供商)100* [Amazon Bedrock、Google Vertex AI 或 Microsoft Foundry](/zh-CN/third-party-integrations)(企业云提供商)

733 101 


899| `claude -p "query"` | 运行一次性查询,然后退出 | `claude -p "explain this function"` |267| `claude -p "query"` | 运行一次性查询,然后退出 | `claude -p "explain this function"` |

900| `claude -c` | 在当前目录中继续最近的对话 | `claude -c` |268| `claude -c` | 在当前目录中继续最近的对话 | `claude -c` |

901| `claude -r` | 恢复之前的对话 | `claude -r` |269| `claude -r` | 恢复之前的对话 | `claude -r` |

902| `claude commit` | 创建 Git 提交 | `claude commit` |

903| `/clear` | 清除对话历史 | `/clear` |270| `/clear` | 清除对话历史 | `/clear` |

904| `/help` | 显示可用命令 | `/help` |271| `/help` | 显示可用命令 | `/help` |

905| `exit` 或 Ctrl+C | 退出 Claude Code | `exit` |272| `exit` 或 Ctrl+D | 退出 Claude Code | `exit` |

906 273 

907有关完整的命令列表,请参阅 [CLI 参考](/zh-CN/cli-reference)。274有关完整的命令列表,请参阅 [CLI 参考](/zh-CN/cli-reference)。

908 275 


971 338 

972## 获取帮助339## 获取帮助

973 340 

974* **在 Claude Code 中**:输入 `/help` 或询问我如何...341* **在 Claude Code 中**:输入 `/help` 或询问"我如何..."

975* **文档**:您在这里!浏览其他指南342* **文档**:您在这里!浏览其他指南

976* **社区**:加入我们的 [Discord](https://www.anthropic.com/discord) 获取提示和支持343* **社区**:加入我们的 [Discord](https://www.anthropic.com/discord) 获取提示和支持

settings.md +6 −2

Details

211| `modelOverrides` | 将 Anthropic 模型 ID 映射到特定于提供商的模型 ID,例如 Bedrock 推理配置文件 ARN。每个模型选择器条目在调用提供商 API 时使用其映射值。请参阅[按版本覆盖模型 ID](/zh-CN/model-config#override-model-ids-per-version) | `{"claude-opus-4-6": "arn:aws:bedrock:..."}` |211| `modelOverrides` | 将 Anthropic 模型 ID 映射到特定于提供商的模型 ID,例如 Bedrock 推理配置文件 ARN。每个模型选择器条目在调用提供商 API 时使用其映射值。请参阅[按版本覆盖模型 ID](/zh-CN/model-config#override-model-ids-per-version) | `{"claude-opus-4-6": "arn:aws:bedrock:..."}` |

212| `otelHeadersHelper` | 生成动态 OpenTelemetry 标头的脚本。在启动时和定期运行。使用 [`CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS`](/zh-CN/env-vars) 设置刷新间隔。请参阅[动态标头](/zh-CN/monitoring-usage#dynamic-headers) | `/bin/generate_otel_headers.sh` |212| `otelHeadersHelper` | 生成动态 OpenTelemetry 标头的脚本。在启动时和定期运行。使用 [`CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS`](/zh-CN/env-vars) 设置刷新间隔。请参阅[动态标头](/zh-CN/monitoring-usage#dynamic-headers) | `/bin/generate_otel_headers.sh` |

213| `outputStyle` | 配置输出样式以调整系统提示。请参阅[输出样式文档](/zh-CN/output-styles) | `"Explanatory"` |213| `outputStyle` | 配置输出样式以调整系统提示。请参阅[输出样式文档](/zh-CN/output-styles) | `"Explanatory"` |

214| `parentSettingsBehavior` | {/* min-version: 2.1.133 */}(仅 Managed 设置)控制由嵌入主机进程(例如 Agent SDK 或 IDE 扩展)以编程方式提供的 managed 设置在同时存在管理员部署的 managed 层时是否应用。`"first-wins"`:父级提供的设置被丢弃,仅应用管理员层。`"merge"`:父级提供的设置在管理员层下应用,经过筛选以便它们可以收紧策略但不能放松策略。当未部署管理员层时无效。默认:`"first-wins"`。需要 Claude Code v2.1.133 或更高版本 | `"merge"` |

214| `permissions` | 请参阅下表了解权限的结构。 | |215| `permissions` | 请参阅下表了解权限的结构。 | |

215| `plansDirectory` | 自定义 Plan Mode 文件的存储位置。路径相对于项目根目录。默认:`~/.claude/plans` | `"./plans"` |216| `plansDirectory` | 自定义 Plan Mode 文件的存储位置。路径相对于项目根目录。默认:`~/.claude/plans` | `"./plans"` |

216| `pluginTrustMessage` | (仅 Managed 设置)在安装前显示的插件信任警告中附加的自定义消息。使用此添加组织特定的上下文,例如确认来自您内部市场的插件已获批准。 | `"All plugins from our marketplace are approved by IT"` |217| `pluginTrustMessage` | (仅 Managed 设置)在安装前显示的插件信任警告中附加的自定义消息。使用此添加组织特定的上下文,例如确认来自您内部市场的插件已获批准。 | `"All plugins from our marketplace are approved by IT"` |


255 256 

256### Worktree 设置257### Worktree 设置

257 258 

258配置 `--worktree` 如何创建和管理 git worktrees。使用这些设置来减少大型 monorepos 中的磁盘使用和启动时间。259配置 `--worktree` 如何创建和管理 git worktrees。

259 260 

260| 键 | 描述 | 示例 |261| 键 | 描述 | 示例 |

261| :---------------------------- | :------------------------------------------------------------------------------- | :------------------------------------ |262| :---------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------ |

263| `worktree.baseRef` | 新 worktrees 分支的参考。`"fresh"`(默认)从 `origin/<default-branch>` 分支以获得与远程匹配的干净树。`"head"` 从您当前的本地 `HEAD` 分支,因此未推送的提交和特性分支状态存在于 worktree 中。适用于 `--worktree`、`EnterWorktree` 工具和 subagent 隔离 | `"head"` |

262| `worktree.symlinkDirectories` | 要从主存储库符号链接到每个 worktree 的目录,以避免在磁盘上复制大型目录。默认情况下不符号链接任何目录 | `["node_modules", ".cache"]` |264| `worktree.symlinkDirectories` | 要从主存储库符号链接到每个 worktree 的目录,以避免在磁盘上复制大型目录。默认情况下不符号链接任何目录 | `["node_modules", ".cache"]` |

263| `worktree.sparsePaths` | 通过 git sparse-checkout(cone 模式)在每个 worktree 中检出的目录。仅将列出的路径写入磁盘,在大型 monorepos 中更快 | `["packages/my-app", "shared/utils"]` |265| `worktree.sparsePaths` | 通过 git sparse-checkout(cone 模式)在每个 worktree 中检出的目录。仅将列出的路径写入磁盘,在大型 monorepos 中更快 | `["packages/my-app", "shared/utils"]` |

264 266 


318| `network.socksProxyPort` | 如果您想自带代理,使用的 SOCKS5 代理端口。如果未指定,Claude 将运行自己的代理。 | `8081` |320| `network.socksProxyPort` | 如果您想自带代理,使用的 SOCKS5 代理端口。如果未指定,Claude 将运行自己的代理。 | `8081` |

319| `enableWeakerNestedSandbox` | 为无特权 Docker 环境启用较弱的 sandbox(仅 Linux 和 WSL2)。**降低安全性。** 默认:false | `true` |321| `enableWeakerNestedSandbox` | 为无特权 Docker 环境启用较弱的 sandbox(仅 Linux 和 WSL2)。**降低安全性。** 默认:false | `true` |

320| `enableWeakerNetworkIsolation` | (仅 macOS)允许在 sandbox 中访问系统 TLS 信任服务(`com.apple.trustd.agent`)。对于 Go 基础工具(如 `gh`、`gcloud` 和 `terraform`)在使用 `httpProxyPort` 与 MITM 代理和自定义 CA 时验证 TLS 证书是必需的。**通过打开潜在的数据泄露路径降低安全性**。默认:false | `true` |322| `enableWeakerNetworkIsolation` | (仅 macOS)允许在 sandbox 中访问系统 TLS 信任服务(`com.apple.trustd.agent`)。对于 Go 基础工具(如 `gh`、`gcloud` 和 `terraform`)在使用 `httpProxyPort` 与 MITM 代理和自定义 CA 时验证 TLS 证书是必需的。**通过打开潜在的数据泄露路径降低安全性**。默认:false | `true` |

323| `bwrapPath` | (仅 Managed 设置,Linux/WSL2)bubblewrap (`bwrap`) 二进制文件的绝对路径。覆盖通过 `PATH` 的自动检测。仅从 [managed 设置](/zh-CN/settings#settings-precedence)受尊重,不从用户或项目设置。在 managed 环境中 `bwrap` 安装在非标准位置时很有用。 | `/opt/admin/bwrap` |

324| `socatPath` | (仅 Managed 设置,Linux/WSL2)用于 sandbox 网络代理的 `socat` 二进制文件的绝对路径。覆盖通过 `PATH` 的自动检测。仅从 managed 设置受尊重。 | `/opt/admin/socat` |

321 325 

322#### Sandbox 路径前缀326#### Sandbox 路径前缀

323 327 

setup.md +2 −0

Details

398 398 

399支持的 npm 安装平台是 `darwin-arm64`、`darwin-x64`、`linux-x64`、`linux-arm64`、`linux-x64-musl`、`linux-arm64-musl`、`win32-x64` 和 `win32-arm64`。您的包管理器必须允许可选依赖项。如果安装后二进制文件丢失,请参阅[故障排除](/zh-CN/troubleshoot-install#native-binary-not-found-after-npm-install)。399支持的 npm 安装平台是 `darwin-arm64`、`darwin-x64`、`linux-x64`、`linux-arm64`、`linux-x64-musl`、`linux-arm64-musl`、`win32-x64` 和 `win32-arm64`。您的包管理器必须允许可选依赖项。如果安装后二进制文件丢失,请参阅[故障排除](/zh-CN/troubleshoot-install#native-binary-not-found-after-npm-install)。

400 400 

401要升级 npm 安装,请运行 `npm install -g @anthropic-ai/claude-code@latest`。避免使用 `npm update -g`,因为它遵循原始安装的 semver 范围,可能不会将您移动到最新版本。

402 

401<Warning>403<Warning>

402 不要使用 `sudo npm install -g`,因为这可能导致权限问题和安全风险。如果遇到权限错误,请参阅[故障排除权限错误](/zh-CN/troubleshoot-install#permission-errors-during-installation)。404 不要使用 `sudo npm install -g`,因为这可能导致权限问题和安全风险。如果遇到权限错误,请参阅[故障排除权限错误](/zh-CN/troubleshoot-install#permission-errors-during-installation)。

403</Warning>405</Warning>

sub-agents.md +3 −3

Details

262| :---------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |262| :---------------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

263| `name` | Yes | 使用小写字母和连字符的唯一标识符 |263| `name` | Yes | 使用小写字母和连字符的唯一标识符 |

264| `description` | Yes | Claude 何时应该委托给此 subagent |264| `description` | Yes | Claude 何时应该委托给此 subagent |

265| `tools` | No | [Tools](#available-tools) subagent 可以使用。如果省略,继承所有工具 |265| `tools` | No | [Tools](#available-tools) subagent 可以使用。如果省略,继承所有工具。要将 Skills 预加载到上下文中,请使用 `skills` 字段而不是在此处列出 `Skill` |

266| `disallowedTools` | No | 要拒绝的工具,从继承或指定的列表中删除 |266| `disallowedTools` | No | 要拒绝的工具,从继承或指定的列表中删除 |

267| `model` | No | [Model](#choose-a-model) 使用:`sonnet`、`opus`、`haiku`、完整模型 ID(例如,`claude-opus-4-7`)或 `inherit`。默认为 `inherit` |267| `model` | No | [Model](#choose-a-model) 使用:`sonnet`、`opus`、`haiku`、完整模型 ID(例如,`claude-opus-4-7`)或 `inherit`。默认为 `inherit` |

268| `permissionMode` | No | [Permission mode](#permission-modes):`default`、`acceptEdits`、`auto`、`dontAsk`、`bypassPermissions` 或 `plan`。对于 [plugin subagents](#choose-the-subagent-scope) 被忽略 |268| `permissionMode` | No | [Permission mode](#permission-modes):`default`、`acceptEdits`、`auto`、`dontAsk`、`bypassPermissions` 或 `plan`。对于 [plugin subagents](#choose-the-subagent-scope) 被忽略 |

269| `maxTurns` | No | subagent 停止前的最大代理轮数 |269| `maxTurns` | No | subagent 停止前的最大代理轮数 |

270| `skills` | No | [Skills](/zh-CN/skills) 在启动时加载到 subagent 的上下文中。注入完整的技能内容,而不仅仅是可用于调用。Subagents 不继承来自父对话的技能 |270| `skills` | No | [Skills](/zh-CN/skills) 在启动时加载到 subagent 的上下文中。注入完整的技能内容,而不仅仅是描述。Subagents 仍然可以通过 Skill 工具调用未列出的项目、用户和 plugin 技能 |

271| `mcpServers` | No | [MCP servers](/zh-CN/mcp) 对此 subagent 可用。每个条目要么是引用已配置服务器的服务器名称(例如,`"slack"`),要么是内联定义,其中服务器名称为键,完整的 [MCP server config](/zh-CN/mcp#installing-mcp-servers) 为值。对于 [plugin subagents](#choose-the-subagent-scope) 被忽略 |271| `mcpServers` | No | [MCP servers](/zh-CN/mcp) 对此 subagent 可用。每个条目要么是引用已配置服务器的服务器名称(例如,`"slack"`),要么是内联定义,其中服务器名称为键,完整的 [MCP server config](/zh-CN/mcp#installing-mcp-servers) 为值。对于 [plugin subagents](#choose-the-subagent-scope) 被忽略 |

272| `hooks` | No | [Lifecycle hooks](#define-hooks-for-subagents) 限定于此 subagent。对于 [plugin subagents](#choose-the-subagent-scope) 被忽略 |272| `hooks` | No | [Lifecycle hooks](#define-hooks-for-subagents) 限定于此 subagent。对于 [plugin subagents](#choose-the-subagent-scope) 被忽略 |

273| `memory` | No | [Persistent memory scope](#enable-persistent-memory):`user`、`project` 或 `local`。启用跨会话学习 |273| `memory` | No | [Persistent memory scope](#enable-persistent-memory):`user`、`project` 或 `local`。启用跨会话学习 |


418Implement API endpoints. Follow the conventions and patterns from the preloaded skills.418Implement API endpoints. Follow the conventions and patterns from the preloaded skills.

419```419```

420 420 

421每个技能的完整内容被注入到 subagent 的上下文中,而不仅仅是可用于调用Subagents 不继承来自父对话的技能;您必须明确列出它们421每个列出的技能的完整内容被注入到 subagent 的上下文中。此字段控制哪些技能被预加载而不是 subagent 可以访问哪些技能:没有它,subagent 仍然可以在执行期间通过 Skill 工具发现和调用项目、用户和 plugin 技能要防止 subagent 完全调用技能,请从 [`tools`](#available-tools) 列表中省略 `Skill` 或将其添加到 `disallowedTools`

422 422 

423您无法预加载设置了 [`disable-model-invocation: true`](/zh-CN/skills#control-who-invokes-a-skill) 的技能,因为预加载来自 Claude 可以调用的相同技能集。如果列出的技能缺失或被禁用,Claude Code 会跳过它并向调试日志记录警告。423您无法预加载设置了 [`disable-model-invocation: true`](/zh-CN/skills#control-who-invokes-a-skill) 的技能,因为预加载来自 Claude 可以调用的相同技能集。如果列出的技能缺失或被禁用,Claude Code 会跳过它并向调试日志记录警告。

424 424 

Details

107set -as terminal-features 'xterm*:extkeys'107set -as terminal-features 'xterm*:extkeys'

108```108```

109 109 

110`allow-passthrough` 行让通知和进度更新到达 iTerm2、Ghostty 或 Kitty,而不是被 tmux 吞没。`extended-keys` 行让 tmux 区分 Shift+Enter 和纯 Enter,以便换行快捷键工作。110`allow-passthrough` 行让通知和进度更新到达外部终端,而不是被 tmux 吞没。`extended-keys` 行让 tmux 区分 Shift+Enter 和纯 Enter,以便换行快捷键工作。

111 111 

112## 匹配颜色主题112## 匹配颜色主题

113 113 

Details

6 6 

7> 了解 Claude Code 如何与各种第三方服务和基础设施集成,以满足企业部署需求。7> 了解 Claude Code 如何与各种第三方服务和基础设施集成,以满足企业部署需求。

8 8 

9export const ContactSalesCard = ({surface}) => {

10 const utm = content => `utm_source=claude_code&utm_medium=docs&utm_content=${surface}_${content}`;

11 const iconArrowRight = (size = 13) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

12 <line x1="5" y1="12" x2="19" y2="12" />

13 <polyline points="12 5 19 12 12 19" />

14 </svg>;

15 const STYLES = `

16.cc-cs {

17 --cs-slate: #141413;

18 --cs-clay: #d97757;

19 --cs-clay-deep: #c6613f;

20 --cs-gray-000: #ffffff;

21 --cs-gray-700: #3d3d3a;

22 --cs-border-default: rgba(31, 30, 29, 0.15);

23 font-family: inherit;

24}

25.dark .cc-cs {

26 --cs-slate: #f0eee6;

27 --cs-gray-000: #262624;

28 --cs-gray-700: #bfbdb4;

29 --cs-border-default: rgba(240, 238, 230, 0.14);

30}

31.cc-cs-card {

32 display: flex; align-items: center; justify-content: space-between;

33 gap: 16px; padding: 14px 16px; margin: 0;

34 background: var(--cs-gray-000); border: 0.5px solid var(--cs-border-default);

35 border-radius: 8px; flex-wrap: wrap;

36}

37.cc-cs-text { font-size: 13px; color: var(--cs-gray-700); line-height: 1.5; flex: 1; min-width: 240px; }

38.cc-cs-text strong { font-weight: 550; color: var(--cs-slate); }

39.cc-cs-actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }

40.cc-cs-btn-clay {

41 display: inline-flex; align-items: center; gap: 8px;

42 background: var(--cs-clay-deep); color: #fff; border: none;

43 border-radius: 8px; padding: 8px 14px;

44 font-size: 13px; font-weight: 500;

45 transition: background-color 0.15s; white-space: nowrap;

46}

47.cc-cs-btn-clay:hover { background: var(--cs-clay); }

48.cc-cs-btn-ghost {

49 display: inline-flex; align-items: center; gap: 8px;

50 background: transparent; color: var(--cs-gray-700);

51 border: 0.5px solid var(--cs-border-default);

52 border-radius: 8px; padding: 8px 14px;

53 font-size: 13px; font-weight: 500;

54}

55.cc-cs-btn-ghost:hover { background: rgba(0, 0, 0, 0.04); }

56.dark .cc-cs-btn-ghost:hover { background: rgba(255, 255, 255, 0.04); }

57@media (max-width: 720px) {

58 .cc-cs-actions { width: 100%; }

59}

60`;

61 return <div className="cc-cs not-prose">

62 <style>{STYLES}</style>

63 <div className="cc-cs-card">

64 <div className="cc-cs-text">

65 <strong>Deploying Claude Code across your organization?</strong> Talk to sales about enterprise plans, SSO, and centralized billing.

66 </div>

67 <div className="cc-cs-actions">

68 <a href={`https://claude.com/pricing?${utm('view_plans')}#plans-business`} className="cc-cs-btn-ghost">

69 View plans

70 </a>

71 <a href={`https://claude.com/contact-sales?${utm('contact_sales')}`} className="cc-cs-btn-clay">

72 Contact sales {iconArrowRight()}

73 </a>

74 </div>

75 </div>

76 </div>;

77};

78 

9组织可以直接通过 Anthropic 或通过云提供商部署 Claude Code。本页面帮助您选择正确的配置。79组织可以直接通过 Anthropic 或通过云提供商部署 Claude Code。本页面帮助您选择正确的配置。

10 80 

81<ContactSalesCard surface="third_party_overview" />

82 

11## 比较部署选项83## 比较部署选项

12 84 

13对于大多数组织,Claude for Teams 或 Claude for Enterprise 提供最佳体验。团队成员可以通过单一订阅访问 Claude Code 和网页版 Claude,具有集中计费和无需基础设施设置的优势。85对于大多数组织,Claude for Teams 或 Claude for Enterprise 提供最佳体验。团队成员可以通过单一订阅访问 Claude Code 和网页版 Claude,具有集中计费和无需基础设施设置的优势。


241 313 

242### 为云提供商固定模型版本314### 为云提供商固定模型版本

243 315 

244如果您通过 [Bedrock](/zh-CN/amazon-bedrock)、[Vertex AI](/zh-CN/google-vertex-ai) 或 [Foundry](/zh-CN/microsoft-foundry) 部署,请使用 `ANTHROPIC_DEFAULT_OPUS_MODEL`、`ANTHROPIC_DEFAULT_SONNET_MODEL` 和 `ANTHROPIC_DEFAULT_HAIKU_MODEL` 固定特定模型版本。如果不固定,Claude Code 别名会解析为最新版本,当 Anthropic 发布您的账户中尚未启用的新模型时,可能会破坏用户。有关详细信息,请参阅[模型配置](/zh-CN/model-config#pin-models-for-third-party-deployments)。316如果您通过 [Bedrock](/zh-CN/amazon-bedrock)、[Vertex AI](/zh-CN/google-vertex-ai) 或 [Foundry](/zh-CN/microsoft-foundry) 部署,请使用 `ANTHROPIC_DEFAULT_OPUS_MODEL`、`ANTHROPIC_DEFAULT_SONNET_MODEL` 和 `ANTHROPIC_DEFAULT_HAIKU_MODEL` 固定特定模型版本。如果不固定,模型别名会解析为最新版本,当 Anthropic 发布您的账户中尚未启用的新模型时,可能会破坏用户。有关每个提供商在最新版本不可用时的行为,请参阅[模型配置](/zh-CN/model-config#pin-models-for-third-party-deployments)。

245 317 

246### 配置安全策略318### 配置安全策略

247 319 

vs-code.md +3 −1

Details

32 32 

33或在 VS Code 中,按 `Cmd+Shift+X`(Mac)或 `Ctrl+Shift+X`(Windows/Linux)打开扩展视图,搜索"Claude Code",然后点击**安装**。33或在 VS Code 中,按 `Cmd+Shift+X`(Mac)或 `Ctrl+Shift+X`(Windows/Linux)打开扩展视图,搜索"Claude Code",然后点击**安装**。

34 34 

35该扩展也可以安装在其他 VS Code 分支中,如 Windsurf 或 Kiro。在编辑器的扩展视图中搜索"Claude Code",或从 [Open VSX 注册表](https://open-vsx.org/extension/Anthropic/claude-code) 安装。如果您的编辑器无法安装该扩展,请在其集成终端中运行 `claude`。[CLI](/zh-CN/quickstart) 可在任何终端中使用。

36 

35<Note>如果安装后扩展没有出现,请重启 VS Code 或从命令面板运行"Developer: Reload Window"。</Note>37<Note>如果安装后扩展没有出现,请重启 VS Code 或从命令面板运行"Developer: Reload Window"。</Note>

36 38 

37## 开始使用39## 开始使用


318| `environmentVariables` | `[]` | 为 Claude 进程设置环境变量。对于共享配置,请改用 Claude Code 设置。 |320| `environmentVariables` | `[]` | 为 Claude 进程设置环境变量。对于共享配置,请改用 Claude Code 设置。 |

319| `disableLoginPrompt` | `false` | 跳过身份验证提示(用于第三方提供商设置) |321| `disableLoginPrompt` | `false` | 跳过身份验证提示(用于第三方提供商设置) |

320| `allowDangerouslySkipPermissions` | `false` | 添加 [Auto mode](/zh-CN/permission-modes#eliminate-prompts-with-auto-mode) 和 Bypass permissions 到模式选择器。Auto mode 有[计划、管理员、模型和提供商要求](/zh-CN/permission-modes#eliminate-prompts-with-auto-mode),因此即使此切换打开,该选项也可能保持不可用。仅在没有互联网访问的沙箱中使用 Bypass permissions。 |322| `allowDangerouslySkipPermissions` | `false` | 添加 [Auto mode](/zh-CN/permission-modes#eliminate-prompts-with-auto-mode) 和 Bypass permissions 到模式选择器。Auto mode 有[计划、管理员、模型和提供商要求](/zh-CN/permission-modes#eliminate-prompts-with-auto-mode),因此即使此切换打开,该选项也可能保持不可用。仅在没有互联网访问的沙箱中使用 Bypass permissions。 |

321| `claudeProcessWrapper` | - | 用于启动 Claude 进程的可执行文件路径 |323| `claudeProcessWrapper` | - | 用于启动 Claude 进程的可执行文件。当存在时,捆绑的二进制文件路径作为参数传递。如果扩展构建不包含您的平台的二进制文件,请将其设置为单独安装的 `claude` 二进制文件。 |

322 324 

323## VS Code 扩展与 Claude Code CLI325## VS Code 扩展与 Claude Code CLI

324 326