# Claude Code Claude Code 是 Anthropic 开发的基于 TypeScript 的智能代码辅助 CLI 工具。它提供了一个功能丰富的终端用户界面,集成了 AI 驱动的代码生成、文件操作、命令执行和 MCP(Model Context Protocol)协议支持。该项目使用 React + Ink 构建终端 UI,支持会话管理、权限控制、多种工具调用和插件扩展系统。 作为 Anthropic 的官方 CLI 工具,Claude Code 实现了完整的对话式编程体验。核心功能包括:QueryEngine 查询引擎管理对话生命周期,Tool 系统提供文件读写、Bash 命令执行、代码搜索等能力,命令系统支持斜杠命令和技能扩展,以及通过 MCP 协议与外部服务集成。项目采用模块化架构,支持后台任务、子代理和工作流编排。 --- ## QueryEngine - 查询引擎 QueryEngine 是 Claude Code 的核心查询处理引擎,负责管理对话的完整生命周期。它处理用户输入、调用 Claude API、执行工具调用,并维护会话状态。每个对话对应一个 QueryEngine 实例,支持多轮对话和状态持久化。 ```typescript import { QueryEngine, type QueryEngineConfig } from './QueryEngine.js' import type { Message } from './types/message.js' import type { Tools } from './Tool.js' import type { Command } from './commands.js' import type { MCPServerConnection } from './services/mcp/types.js' import type { AppState } from './state/AppState.js' import type { FileStateCache } from './utils/fileStateCache.js' // 配置 QueryEngine const config: QueryEngineConfig = { cwd: process.cwd(), tools: myTools, // 可用工具列表 commands: myCommands, // 可用命令列表 mcpClients: [], // MCP 服务器连接 agents: [], // 代理定义 canUseTool: async (tool, input, context, assistantMessage, toolUseID) => { return { behavior: 'allow', updatedInput: input } }, getAppState: () => appState, setAppState: (updater) => { appState = updater(appState) }, initialMessages: [], // 初始消息历史 readFileCache: fileStateCache, // 文件缓存 customSystemPrompt: undefined, // 自定义系统提示 appendSystemPrompt: undefined, // 追加系统提示 userSpecifiedModel: 'claude-sonnet-4-20250514', thinkingConfig: { type: 'adaptive' }, maxTurns: 100, // 最大对话轮数 maxBudgetUsd: 10.0, // 最大预算(美元) verbose: false, } // 创建 QueryEngine 实例 const engine = new QueryEngine(config) // 提交消息并处理响应流 async function chat(prompt: string) { for await (const message of engine.submitMessage(prompt)) { switch (message.type) { case 'assistant': console.log('Assistant:', message.message.content) break case 'result': console.log('Result:', message.result) console.log('Cost:', message.total_cost_usd) break case 'system': if (message.subtype === 'compact_boundary') { console.log('Context compacted') } break } } } // 中断当前查询 engine.interrupt() // 获取消息历史 const messages = engine.getMessages() // 获取会话 ID const sessionId = engine.getSessionId() ``` --- ## ask - 单次查询便捷函数 ask 函数是 QueryEngine 的便捷包装,用于单次查询场景。它简化了配置流程,适合快速集成和脚本化使用。函数返回异步生成器,可以流式处理响应。 ```typescript import { ask } from './QueryEngine.js' import type { SDKMessage } from './entrypoints/agentSdkTypes.js' // 单次查询示例 async function singleQuery() { const generator = ask({ commands: [], prompt: '请解释 TypeScript 的泛型是什么?', cwd: process.cwd(), tools: availableTools, mcpClients: [], canUseTool: async (tool, input, ctx, msg, id) => ({ behavior: 'allow', updatedInput: input, }), getAppState: () => appState, setAppState: (fn) => { appState = fn(appState) }, getReadFileCache: () => fileCache, setReadFileCache: (cache) => { fileCache = cache }, verbose: false, maxTurns: 50, maxBudgetUsd: 5.0, replayUserMessages: true, includePartialMessages: false, }) // 处理响应流 for await (const message of generator) { if (message.type === 'assistant') { // 处理助手消息 for (const block of message.message.content) { if (block.type === 'text') { process.stdout.write(block.text) } } } else if (message.type === 'result') { console.log('\n--- 查询完成 ---') console.log('耗时:', message.duration_ms, 'ms') console.log('费用: $', message.total_cost_usd.toFixed(4)) } } } ``` --- ## Tool - 工具定义系统 Tool 是 Claude Code 的核心抽象,定义了模型可以调用的各种能力。每个工具包含输入模式、权限检查、执行逻辑和 UI 渲染。使用 buildTool 函数可以创建带有默认值的工具定义。 ```typescript import { buildTool, type Tool, type ToolUseContext, type ToolResult } from './Tool.js' import { z } from 'zod/v4' // 定义自定义工具 const MyCustomTool = buildTool({ name: 'MyCustomTool', // 输入模式定义 inputSchema: z.object({ query: z.string().describe('搜索查询'), maxResults: z.number().optional().default(10), }), // 工具描述(用于权限对话框) async description(input, options) { return `搜索: ${input.query}` }, // 系统提示中的工具说明 async prompt(options) { return `使用此工具进行自定义搜索操作。 参数: - query: 搜索查询字符串 - maxResults: 返回结果数量上限(默认10)` }, // 执行工具调用 async call(input, context, canUseTool, parentMessage, onProgress): Promise> { // 报告进度 onProgress?.({ toolUseID: context.toolUseId!, data: { type: 'bash', phase: 'executing', content: '正在搜索...' }, }) // 执行搜索逻辑 const results = await performSearch(input.query, input.maxResults) return { data: JSON.stringify(results, null, 2), } }, // 权限检查 async checkPermissions(input, context) { // 返回 allow/deny/ask 决策 return { behavior: 'allow', updatedInput: input } }, // 是否只读操作 isReadOnly: () => true, // 是否并发安全 isConcurrencySafe: () => true, // 最大结果大小 maxResultSizeChars: 100000, // UI 渲染方法 userFacingName: (input) => `搜索 ${input?.query ?? ''}`, renderToolUseMessage(input, options) { return 搜索: {input.query} }, renderToolResultMessage(content, progressMessages, options) { return {content} }, mapToolResultToToolResultBlockParam(content, toolUseID) { return { type: 'tool_result', tool_use_id: toolUseID, content: content, } }, }) // 查找工具 import { findToolByName, toolMatchesName } from './Tool.js' const tool = findToolByName(tools, 'MyCustomTool') const matches = toolMatchesName(tool, 'MyCustomTool') ``` --- ## Task - 后台任务管理 Task 系统管理 Claude Code 中的后台任务,包括 Bash 命令、子代理、远程代理等。每个任务有唯一 ID、状态跟踪和输出文件。 ```typescript import { type TaskType, type TaskStatus, type TaskStateBase, generateTaskId, createTaskStateBase, isTerminalTaskStatus, } from './Task.js' // 任务类型 const taskTypes: TaskType[] = [ 'local_bash', // 本地 Bash 命令 'local_agent', // 本地子代理 'remote_agent', // 远程代理 'in_process_teammate', // 进程内协作代理 'local_workflow', // 本地工作流 'monitor_mcp', // MCP 监控 'dream', // Dream 任务 ] // 生成任务 ID const taskId = generateTaskId('local_bash') // 例如: "b1a2b3c4d5" // 创建任务状态 const taskState = createTaskStateBase( taskId, 'local_bash', '运行测试套件', 'tool_use_123', // 可选的工具使用 ID ) console.log(taskState) // { // id: "b1a2b3c4d5", // type: "local_bash", // status: "pending", // description: "运行测试套件", // toolUseId: "tool_use_123", // startTime: 1234567890123, // outputFile: "/path/to/output", // outputOffset: 0, // notified: false // } // 检查任务是否完成 const isDone = isTerminalTaskStatus(taskState.status) // 'completed' | 'failed' | 'killed' 返回 true ``` --- ## Commands - 命令系统 Claude Code 的命令系统支持斜杠命令、技能、插件命令和 MCP 命令。命令分为 `local`(本地执行)、`local-jsx`(渲染 UI)和 `prompt`(发送到模型)三种类型。 ```typescript import { getCommands, findCommand, hasCommand, getCommand, getSkillToolCommands, getMcpSkillCommands, clearCommandsCache, formatDescriptionWithSource, type Command, } from './commands.js' // 获取所有可用命令 const commands = await getCommands(process.cwd()) // 查找特定命令 const helpCommand = findCommand('help', commands) const hasReview = hasCommand('review', commands) // 获取命令(不存在时抛出异常) try { const commitCommand = getCommand('commit', commands) } catch (err) { console.error('命令不存在:', err.message) } // 获取技能工具命令(模型可调用的 prompt 类型命令) const skillCommands = await getSkillToolCommands(process.cwd()) // 定义自定义命令 const myCommand: Command = { type: 'prompt', name: 'my-command', aliases: ['mc'], description: '我的自定义命令', source: 'plugin', loadedFrom: 'plugin', hasUserSpecifiedDescription: true, // prompt 类型命令需要实现此方法 async getPromptForCommand(args, context) { return `执行自定义操作: ${args}` }, // 命令可用性 availability: ['claude-ai', 'console'], // 命令长度估计(用于上下文管理) contentLength: 500, // 进度消息 progressMessage: '正在执行...', } // 格式化命令描述(包含来源) const formattedDesc = formatDescriptionWithSource(myCommand) // 输出: "我的自定义命令 (plugin)" // 清除命令缓存(重新加载插件后) clearCommandsCache() ``` --- ## MCP - Model Context Protocol 集成 MCP 系统管理与外部 MCP 服务器的连接,支持 stdio、SSE、HTTP 和 WebSocket 等传输协议。MCP 服务器可以提供工具、资源和提示。 ```typescript import type { MCPServerConnection, ConnectedMCPServer, FailedMCPServer, McpServerConfig, McpStdioServerConfig, McpSSEServerConfig, McpHTTPServerConfig, ConfigScope, ServerResource, } from './services/mcp/types.js' // Stdio 服务器配置 const stdioConfig: McpStdioServerConfig = { type: 'stdio', command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem', '/path/to/dir'], env: { NODE_ENV: 'production', }, } // SSE 服务器配置 const sseConfig: McpSSEServerConfig = { type: 'sse', url: 'https://mcp.example.com/sse', headers: { 'Authorization': 'Bearer token123', }, oauth: { clientId: 'my-client', callbackPort: 3000, }, } // HTTP 服务器配置 const httpConfig: McpHTTPServerConfig = { type: 'http', url: 'https://mcp.example.com/api', headers: { 'X-API-Key': 'key123', }, } // 处理 MCP 连接状态 function handleMcpConnection(connection: MCPServerConnection) { switch (connection.type) { case 'connected': console.log(`已连接: ${connection.name}`) console.log('能力:', connection.capabilities) console.log('服务器信息:', connection.serverInfo) // 使用 client 调用工具 break case 'failed': console.error(`连接失败: ${connection.name}`, connection.error) break case 'needs-auth': console.log(`需要认证: ${connection.name}`) break case 'pending': console.log(`正在连接: ${connection.name}`) break case 'disabled': console.log(`已禁用: ${connection.name}`) break } } // MCP CLI 状态序列化 import type { MCPCliState, SerializedTool, SerializedClient } from './services/mcp/types.js' const cliState: MCPCliState = { clients: [ { name: 'filesystem', type: 'connected', capabilities: { tools: {} } }, ], configs: { filesystem: { ...stdioConfig, scope: 'user' }, }, tools: [ { name: 'mcp__filesystem__read_file', description: '读取文件内容', isMcp: true, originalToolName: 'read_file', }, ], resources: { filesystem: [ { uri: 'file:///path/to/file', name: '文件', server: 'filesystem' }, ], }, } ``` --- ## AppState - 应用状态管理 AppState 是 Claude Code 的全局状态容器,使用 React Context 和 useSyncExternalStore 实现高效的状态订阅。组件可以选择性订阅状态片段,避免不必要的重渲染。 ```typescript import { AppStateProvider, useAppState, useSetAppState, useAppStateStore, useAppStateMaybeOutsideOfProvider, getDefaultAppState, type AppState, } from './state/AppState.js' // 创建初始状态 const initialState = getDefaultAppState() // 在组件中使用状态 function MyComponent() { // 订阅特定状态片段 const verbose = useAppState(s => s.verbose) const model = useAppState(s => s.mainLoopModel) const toolPermissions = useAppState(s => s.toolPermissionContext) // 获取状态更新函数(不触发重渲染) const setAppState = useSetAppState() // 更新状态 const toggleVerbose = () => { setAppState(prev => ({ ...prev, verbose: !prev.verbose, })) } // 获取完整的 store(用于传递给非 React 代码) const store = useAppStateStore() return (

模型: {model}

) } // 在可能不存在 Provider 的上下文中安全使用 function SafeComponent() { const verbose = useAppStateMaybeOutsideOfProvider(s => s.verbose) // verbose 可能是 undefined return Verbose: {verbose ?? 'N/A'} } // 应用根组件 function App() { return ( { console.log('状态变更:', { from: oldState, to: newState }) }} > ) } ``` --- ## Hooks - 钩子系统 Claude Code 的钩子系统允许在特定事件点执行自定义逻辑,包括工具调用前后、会话开始、停止等时机。钩子可以是 prompt 类型(发送到模型)或 agent 类型(运行子代理验证)。 ```typescript import { hookResponseSchema, addArgumentsToPrompt, createStructuredOutputTool, registerStructuredOutputEnforcement, } from './utils/hooks/hookHelpers.js' import { addFunctionHook } from './utils/hooks/sessionHooks.js' // 钩子响应模式 const responseSchema = hookResponseSchema() // { ok: boolean, reason?: string } // 在提示中替换参数 const prompt = '分析以下输入: $ARGUMENTS' const withArgs = addArgumentsToPrompt(prompt, JSON.stringify({ data: 'test' })) // 输出: "分析以下输入: {"data":"test"}" // 支持索引参数 const indexedPrompt = '第一个参数: $0, 第二个参数: $1' const withIndexedArgs = addArgumentsToPrompt( indexedPrompt, JSON.stringify(['foo', 'bar']), ) // 输出: "第一个参数: foo, 第二个参数: bar" // 创建结构化输出工具(用于钩子验证) const structuredTool = createStructuredOutputTool() // 注册强制结构化输出的钩子 registerStructuredOutputEnforcement(setAppState, sessionId) // 添加自定义函数钩子 addFunctionHook( setAppState, sessionId, 'Stop', // 钩子类型 '', // 匹配器(空表示匹配所有) (messages) => { // 条件函数 return messages.some(m => m.type === 'assistant' && m.message.content.some(c => c.type === 'tool_use') ) }, '请完成工具调用后再停止。', // 失败时的提示 { timeout: 5000 }, // 选项 ) ``` --- ## BashTool - Bash 命令执行 BashTool 是 Claude Code 中最常用的工具之一,允许在持久化 shell 会话中执行 Bash 命令。支持超时控制、后台执行、沙箱隔离等功能。 ```typescript // BashTool 配置和使用示例 import { BASH_TOOL_NAME } from './tools/BashTool/toolName.js' import { getSimplePrompt, getDefaultTimeoutMs, getMaxTimeoutMs } from './tools/BashTool/prompt.js' // 获取默认超时时间 const defaultTimeout = getDefaultTimeoutMs() // 120000ms (2分钟) const maxTimeout = getMaxTimeoutMs() // 600000ms (10分钟) // BashTool 输入示例 const bashInput = { command: 'git status && git diff --stat', description: '检查 Git 仓库状态', timeout: 30000, // 可选超时 run_in_background: false, // 是否后台运行 dangerouslyDisableSandbox: false, // 是否禁用沙箱 } // 后台执行命令 const backgroundInput = { command: 'npm run build', description: '构建项目', run_in_background: true, // 后台任务完成后会收到通知 } // Git 提交示例(使用 HEREDOC) const commitCommand = `git commit -m "$(cat <<'EOF' feat: 添加新功能 实现了用户认证模块的基本功能。 Co-Authored-By: Claude EOF )"` // PR 创建示例 const prCommand = `gh pr create --title "feat: 新功能" --body "$(cat <<'EOF' ## Summary - 添加用户认证功能 - 实现 JWT 令牌验证 ## Test plan - [ ] 单元测试通过 - [ ] 集成测试通过 Generated with Claude Code EOF )"` // 获取工具提示(系统提示中的说明) const toolPrompt = getSimplePrompt() ``` --- ## FileReadTool - 文件读取 FileReadTool 用于读取文件内容,支持行号范围、图片、PDF、Jupyter Notebook 等多种格式。具有智能的文件大小和 token 限制管理。 ```typescript import { FILE_READ_TOOL_NAME } from './tools/FileReadTool/prompt.js' import { getDefaultFileReadingLimits } from './tools/FileReadTool/limits.js' // 获取默认限制 const limits = getDefaultFileReadingLimits() // { maxTokens: number, maxSizeBytes: number } // 基本文件读取 const readInput = { file_path: '/absolute/path/to/file.ts', } // 带行号范围的读取 const rangeInput = { file_path: '/path/to/large-file.ts', offset: 100, // 从第100行开始 limit: 50, // 读取50行 } // 读取图片(自动处理调整大小) const imageInput = { file_path: '/path/to/screenshot.png', // 图片会自动压缩以适应 token 限制 } // 读取 PDF const pdfInput = { file_path: '/path/to/document.pdf', // 支持页码范围,如 "1-5" 或 "1,3,5" } // 读取 Jupyter Notebook const notebookInput = { file_path: '/path/to/analysis.ipynb', // 返回所有单元格及其输出 } // FileReadTool 的输出格式(使用 cat -n 风格) // 示例输出: // 1→import React from 'react' // 2→ // 3→function App() { // 4→ return
Hello
// 5→} ``` --- ## FileEditTool - 文件编辑 FileEditTool 执行精确的字符串替换操作。要求先使用 FileReadTool 读取文件,确保 old_string 在文件中唯一,或使用 replace_all 替换所有出现。 ```typescript import { FILE_EDIT_TOOL_NAME } from './tools/FileEditTool/constants.js' // 基本编辑操作 const editInput = { file_path: '/path/to/file.ts', old_string: 'const foo = 1', new_string: 'const foo = 42', } // 替换所有出现 const replaceAllInput = { file_path: '/path/to/file.ts', old_string: 'oldName', new_string: 'newName', replace_all: true, // 替换文件中所有匹配 } // 保持缩进(从 Read 工具输出复制时的注意事项) // Read 输出格式: " 5→ const x = 1" // 行号前缀 ↑ ↑ 实际内容开始 // old_string 应该只包含实际内容: " const x = 1" // 删除内容(new_string 为空) const deleteInput = { file_path: '/path/to/file.ts', old_string: '// TODO: remove this\n', new_string: '', } // 插入新内容(old_string 为上下文锚点) const insertInput = { file_path: '/path/to/file.ts', old_string: 'import React from \'react\'', new_string: 'import React from \'react\'\nimport { useState } from \'react\'', } ``` --- ## GlobTool - 文件模式匹配 GlobTool 用于根据 glob 模式快速查找文件。支持标准 glob 语法,结果按修改时间排序。 ```typescript import { GLOB_TOOL_NAME } from './tools/GlobTool/prompt.js' // 基本模式匹配 const globInput = { pattern: '**/*.ts', // 所有 TypeScript 文件 path: '/optional/start/path', // 可选的起始路径 } // 常用模式示例 const patterns = [ '**/*.ts', // 所有 .ts 文件 '**/*.{ts,tsx}', // 所有 .ts 和 .tsx 文件 'src/**/*.test.ts', // src 下的测试文件 '**/index.{ts,js}', // 所有入口文件 '!**/node_modules/**', // 排除 node_modules 'src/components/*.tsx', // components 目录下的 TSX 文件 ] // Glob 输出示例: // /path/to/project/src/index.ts // /path/to/project/src/utils/helper.ts // /path/to/project/src/components/Button.tsx // (结果按修改时间降序排列) ``` --- ## GrepTool - 内容搜索 GrepTool 基于 ripgrep 实现高性能的代码搜索,支持正则表达式、文件类型过滤、上下文行显示等功能。 ```typescript import { GREP_TOOL_NAME } from './tools/GrepTool/prompt.js' // 基本搜索 const grepInput = { pattern: 'function\\s+\\w+', // 正则表达式模式 path: '/search/path', // 搜索路径 } // 高级搜索选项 const advancedGrepInput = { pattern: 'TODO|FIXME', path: '/project', glob: '*.{ts,tsx}', // 文件过滤 type: 'ts', // 或使用类型过滤 output_mode: 'content', // 'content' | 'files_with_matches' | 'count' '-i': true, // 忽略大小写 '-n': true, // 显示行号 '-A': 2, // 显示匹配后2行 '-B': 2, // 显示匹配前2行 '-C': 3, // 显示上下文各3行 head_limit: 100, // 限制结果数量 multiline: true, // 多行匹配模式 } // 输出模式示例 // 'files_with_matches' (默认): // /path/to/file1.ts // /path/to/file2.ts // 'content': // /path/to/file1.ts:10: function handleClick() { // /path/to/file1.ts:11: // TODO: implement // /path/to/file1.ts:12: } // 'count': // /path/to/file1.ts:5 // /path/to/file2.ts:2 ``` --- ## 主要使用场景与集成模式 Claude Code 作为 AI 驱动的编程助手,其核心使用场景包括交互式代码开发、自动化脚本执行和 SDK 集成。在交互模式下,用户通过终端 UI 与 Claude 对话,使用斜杠命令(如 `/review`、`/commit`)触发预定义工作流。工具系统允许模型执行文件操作、运行命令、搜索代码库,而权限系统确保操作安全可控。MCP 集成使 Claude Code 可以连接外部服务,扩展其能力边界。 在 SDK 和自动化场景中,QueryEngine 提供了完整的编程接口。开发者可以构建自定义的 AI 工作流,将 Claude Code 嵌入到 CI/CD 管道、IDE 插件或其他开发工具中。ask 函数适合单次查询,而 QueryEngine 类则支持复杂的多轮对话和状态管理。钩子系统允许在关键节点注入自定义逻辑,如验证输出、记录日志或触发外部操作。整个系统采用模块化设计,支持通过插件和技能扩展功能,同时保持核心架构的稳定性和可测试性。