Claude 工具审批与用户输入处理机制

介绍在 Claude 代理中通过 canUseTool 回调识别工具审批请求与 AskUserQuestion 提问,并给出批准、修改、记住、拒绝等响应方式及自由文本输入的处理要点。

Claude 在进行一项任务时, 有时需要与用户联系。 在删除文件之前可能需要许可, 或者需要询问用于新工程的哪个数据库。 您的应用程序需要向用户显示这些请求, 以便 Claude 可以继续输入 。 Claude 在两种情况下请求用户输入 : 当需要时 。 **允许使用工具** (如删除文件或运行中的命令),当它有 **澄清问题** (通过 `AskUserQuestion` 工具。两个都触发您 `canUseTool` Callback, 它会暂停执行直到返回回复。 这与克劳德完成并等待您下一封信的正常对话不同。 为了澄清问题, Claude 生成问题和选项。 您的作用是将它们提交用户并返回其选择。您不能将自己的问题添加到此流程中; 如果您需要自己询问用户, 请在应用程序逻辑中单独询问。 回调可以无限期地等待。 执行会暂停, 直到您的回调返回。 如果一个用户的回复时间可能比您的进程更长, 请注册一个 [`PreToolUse` 钩子](<https://code.claude.com/docs/en/agent-sdk/hooks>) 返回该 [`defer` 决定](<https://code.claude.com/docs/en/hooks#defer-a-tool-call-for-later>) 而不是在调用回话中等待, 因此进程可以退出, 并在持续会话的后面恢复 。 此指南将指示您如何检测每种类型的请求, 并作出适当的反应 。 ## Claude 需要输入时检测 传一个 `canUseTool` 在查询选项中调用。 Claude 需要用户输入、接收工具名称和输入作为参数时,调用点火 : ``` from claude_agent_sdk import ClaudeAgentOptions async def handle_tool_request(tool_name, input_data, context): # Prompt user and return allow or deny ... options = ClaudeAgentOptions(can_use_tool=handle_tool_request) ``` ``` import type { CanUseTool } from "@anthropic-ai/claude-agent-sdk"; const handleToolRequest: CanUseTool = async (toolName, input, options) => { // options includes { signal: AbortSignal, suggestions?: PermissionUpdate[] } // Prompt the user here, then return allow or deny return { behavior: "deny", message: "User declined" }; }; const options = { canUseTool: handleToolRequest }; ``` 两次召回火灾: 1. **工具需要核准**Claude打电话说 [权限流量](<https://code.claude.com/docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) 还没有批准或拒绝。检查 `tool_name` 工具(例如, `"Bash"`, `"Write"`). 2. **克劳德问了个问题**克劳德呼叫 `AskUserQuestion` 工具。检查是否 `tool_name == "AskUserQuestion"` 以不同方式处理。如果您指定 `tools` 阵列,包括 `AskUserQuestion` 更多信息,请参见: [处理澄清问题](<https://code.claude.com/docs/en/agent-sdk/user-input#handle-clarifying-questions>). **更早的一步可以允许或拒绝电话 `canUseTool` 运行。** 那个... [权限评估流程](<https://code.claude.com/docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) 检查拒绝规则, 权限模式, 并允许规则在召回之前 。 要检查没有召回而运行的呼叫, 例如文件读取在您的内部 。 [工作目录](<https://code.claude.com/docs/en/permissions#working-directories>),使用一个 [`PreToolUse` 钩子](<https://code.claude.com/docs/en/agent-sdk/hooks>),可以允许、否认或修改。 您也可以使用这个 [`PermissionRequest` 钩子](<https://code.claude.com/docs/en/agent-sdk/hooks#available-hooks>) 以在克劳德等待批准时发送外部通知(Slack, email, push) 。 ## 处理工具批准请求 一旦你通过了一个 `canUseTool` 在您的查询选项中调用, 当克劳德想要使用一个在权限流之前没有获得批准的工具时, 它会点火。 在一些配置中, 例如 `dontAsk` 模式,克劳德代码不称它; [权限如何评估](<https://code.claude.com/docs/en/agent-sdk/permissions#how-permissions-are-evaluated>) 列出它们,并说出电话发生的情况。 您的回调收到三个参数: | 参数 | 说明 | | --- | --- | | `toolName` | 工具的名称克劳德想要使用(例如, `"Bash"`, `"Write"`, `"Edit"`) | | `input` | 参数Claude正在传递到工具上,内容因工具而异. | | `options` (TS) / `context` (彼贤). | 附加上下文,包括任择上下文 `suggestions` (拟议数) `PermissionUpdate` 在 TypeScript 中, `signal` 是一个 `AbortSignal`;在 Python 中,信号字段被保留给将来使用。 [`ToolPermissionContext`](<https://code.claude.com/docs/en/agent-sdk/python#toolpermissioncontext>) 为彼菩萨. | 那个... `input` 对象包含特定工具的参数。常见的例子 : | 工具 | 输入字段 | | --- | --- | | `Bash` | `command`, `description`, `timeout` | | `Write` | `file_path`, `content` | | `Edit` | `file_path`, `old_string`, `new_string` | | `Read` | `file_path`, `offset`, `limit` | 完整的输入方案见SDK参考: [Python 键](<https://code.claude.com/docs/en/agent-sdk/python#tool-input%2Foutput-types>) | [TypeScript](<https://code.claude.com/docs/en/agent-sdk/typescript#tool-input-types>)。您可以向用户显示此信息,以便他们可以决定是否允许或拒绝此动作,然后返回适当的响应。下面的例子要求克劳德创建和删除测试文件。当克劳德尝试每个操作时,回调会打印工具请求到终端,并提示批准y/n。 ``` import asyncio from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query from claude_agent_sdk.types import ( HookMatcher, PermissionResultAllow, PermissionResultDeny, ToolPermissionContext, ) async def can_use_tool( tool_name: str, input_data: dict, context: ToolPermissionContext ) -> PermissionResultAllow | PermissionResultDeny: # Display the tool request print(f"\nTool: {tool_name}") if tool_name == "Bash": print(f"Command: {input_data.get('command')}") if input_data.get("description"): print(f"Description: {input_data.get('description')}") else: print(f"Input: {input_data}") # Get user approval response = input("Allow this action? (y/n): ") # Return allow or deny based on user's response if response.lower() == "y": # Allow: tool executes with the original (or modified) input return PermissionResultAllow(updated_input=input_data) else: # Deny: tool doesn't execute, Claude sees the message return PermissionResultDeny(message="User denied this action") # Required workaround: dummy hook keeps the stream open for can_use_tool async def dummy_hook(input_data, tool_use_id, context): return {"continue_": True} async def prompt_stream(): yield { "type": "user", "message": { "role": "user", "content": "Create a test file in /tmp and then delete it", }, } async def main(): async for message in query( prompt=prompt_stream(), options=ClaudeAgentOptions( can_use_tool=can_use_tool, hooks={"PreToolUse": [HookMatcher(matcher=None, hooks=[dummy_hook])]}, ), ): if isinstance(message, ResultMessage) and message.subtype == "success": print(message.result) asyncio.run(main()) ``` ``` import { query } from "@anthropic-ai/claude-agent-sdk"; import * as readline from "readline"; // Helper to prompt user for input in the terminal function prompt(question: string): Promise<string> { const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); return new Promise((resolve) => rl.question(question, (answer) => { rl.close(); resolve(answer); }) ); } for await (const message of query({ prompt: "Create a test file in /tmp and then delete it", options: { canUseTool: async (toolName, input) => { // Display the tool request console.log(`\nTool: ${toolName}`); if (toolName === "Bash") { console.log(`Command: ${input.command}`); if (input.description) console.log(`Description: ${input.description}`); } else { console.log(`Input: ${JSON.stringify(input, null, 2)}`); } // Get user approval const response = await prompt("Allow this action? (y/n): "); // Return allow or deny based on user's response if (response.toLowerCase() === "y") { // Allow: tool executes with the original (or modified) input return { behavior: "allow", updatedInput: input }; } else { // Deny: tool doesn't execute, Claude sees the message return { behavior: "deny", message: "User denied this action" }; } } } })) { if ("result" in message) console.log(message.result); } ``` 此示例使用一个 `y/n` 流动中除此之外的任何输入 `y` 在实际操作中,您可能构建一个更丰富的UI,让用户修改请求,提供反馈,或完全重定向克劳德。 [响应工具请求](<https://code.claude.com/docs/en/agent-sdk/user-input#respond-to-tool-requests>) 以你所有的方式回应。 ### 响应工具请求 您的回调返回两种响应类型之一 : | 回应 | Python 键 | TypeScript | | --- | --- | --- | | **允许** | `PermissionResultAllow(updated_input=...)` | `{ behavior: "allow", updatedInput }` | | **拒绝** | `PermissionResultDeny(message=...)` | `{ behavior: "deny", message }` | 允许时,该工具会随请求的输入Claude运行,除非您返回一个修改过的输入, `updatedInput` 在 TypeScript 中,或 `updated_input` 在 Python 中。在 v2.1.207 之前, Claude Code 拒绝了省略的允许结果 `updatedInput` 并用校验错误拒绝工具调用。 在拒绝时, 提供一条信息解释原因。 Claude看到此信息并可能调整其方法。 除了允许或拒绝, 您可以修改工具的输入或提供上下文, 帮助 Claude 调整其方法 : - **核准**: 让工具按克劳德的要求执行 - **经修改后核准**:在执行前修改输入(例如,对路径进行消毒,增加限制) - **批准和记住**: 回声一个建议的权限规则, 这样匹配的呼叫在下次跳过时速 - **拒绝**: 封锁工具并告诉克劳德为什么 - **建议的替代方案**: 挡住但引导克劳德向用户想要的东西方向前进 - **完全重定向**: 使用情况 [串流输入](<https://code.claude.com/docs/en/agent-sdk/streaming-vs-single-mode>) 向克劳德发送全新的指令 那个... `ask_user` 财务报告和财务报告 `askUser` 以下片段中的帮助者代表您的应用程序的 UI 。 - 核准 - 经修改后核准 - 批准和记住 - 拒绝 - 建议的替代方案 - 完全重定向 用户批准该动作。通过 `input` 从您的回调不变, 工具正按克劳德的要求执行 。 ``` async def can_use_tool(tool_name, input_data, context): print(f"Claude wants to use {tool_name}") approved = await ask_user("Allow this action?") if approved: return PermissionResultAllow(updated_input=input_data) return PermissionResultDeny(message="User declined") ``` ``` canUseTool: async (toolName, input) => { console.log(`Claude wants to use ${toolName}`); const approved = await askUser("Allow this action?"); if (approved) { return { behavior: "allow", updatedInput: input }; } return { behavior: "deny", message: "User declined" }; }; ``` 用户批准但想要先修改请求。 您可以在工具执行前更改输入。 可用于消毒参数、 添加限制或范围化访问 。 ``` async def can_use_tool(tool_name, input_data, context): if tool_name == "Bash": # User approved, but scope all commands to sandbox sandboxed_input = {**input_data} sandboxed_input["command"] = input_data["command"].replace( "/tmp", "/tmp/sandbox" ) return PermissionResultAllow(updated_input=sandboxed_input) return PermissionResultAllow(updated_input=input_data) ``` ``` canUseTool: async (toolName, input) => { if (toolName === "Bash") { // User approved, but scope all commands to sandbox const sandboxedInput = { ...input, command: input.command.replace("/tmp", "/tmp/sandbox") }; return { behavior: "allow", updatedInput: sandboxedInput }; } return { behavior: "allow", updatedInput: input }; }; ``` 用户批准, 不想再次被问到这种呼叫。 第三个回调参数包含 `suggestions`,一系列现成 [`PermissionUpdate`](<https://code.claude.com/docs/en/agent-sdk/typescript#permissionupdate>) 条目。 Echo one back in `updatedPermissions` 向秘书处提出建议。 `localSettings` 目标规则写入 `.claude/settings.local.json` 因此,未来的会话会跳过匹配呼叫的提示。在 TypeScript 中,跳过总是允许选择一个选项包含的请求 [`suppressAlwaysAllowRule: true`](<https://code.claude.com/docs/en/agent-sdk/typescript#canusetool>)。提示需要代理 SDK v0.3.268 或以后,以及 Python `context` Python 示例要求 `claude-agent-sdk` 0.1.80或后来. ``` async def can_use_tool(tool_name, input_data, context): choice = await ask_user(f"Allow {tool_name}?", ["once", "always", "no"]) if choice == "always": persist = [ s for s in context.suggestions if s.destination == "localSettings" ] return PermissionResultAllow( updated_input=input_data, updated_permissions=persist ) if choice == "once": return PermissionResultAllow(updated_input=input_data) return PermissionResultDeny(message="User declined") ``` ``` canUseTool: async (toolName, input, { suggestions = [] }) => { const choice = await askUser(`Allow ${toolName}?`, ["once", "always", "no"]); if (choice === "always") { const persist = suggestions.filter( (s) => s.destination === "localSettings" ); return { behavior: "allow", updatedInput: input, updatedPermissions: persist }; } if (choice === "once") { return { behavior: "allow", updatedInput: input }; } return { behavior: "deny", message: "User declined" }; }; ``` 用户不希望此动作发生。 屏蔽工具并提供一个解释原因的信息。 Claude看到此信息并可能尝试另一种方法 。 ``` async def can_use_tool(tool_name, input_data, context): approved = await ask_user(f"Allow {tool_name}?") if not approved: return PermissionResultDeny(message="User rejected this action") return PermissionResultAllow(updated_input=input_data) ``` ``` canUseTool: async (toolName, input) => { const approved = await askUser(`Allow ${toolName}?`); if (!approved) { return { behavior: "deny", message: "User rejected this action" }; } return { behavior: "allow", updatedInput: input }; }; ``` 用户不希望这个特定动作, 但有不同的想法。 屏蔽工具并在信息中包含引导。 Claude 将读取此内容, 并根据您的反馈决定如何进行 。 ``` async def can_use_tool(tool_name, input_data, context): if tool_name == "Bash" and "rm" in input_data.get("command", ""): # User doesn't want to delete, suggest archiving instead return PermissionResultDeny( message="User doesn't want to delete files. They asked if you could compress them into an archive instead." ) return PermissionResultAllow(updated_input=input_data) ``` ``` canUseTool: async (toolName, input) => { if (toolName === "Bash" && input.command.includes("rm")) { // User doesn't want to delete, suggest archiving instead return { behavior: "deny", message: "User doesn't want to delete files. They asked if you could compress them into an archive instead." }; } return { behavior: "allow", updatedInput: input }; }; ``` 完全改变方向(不仅仅是一个摇摆),使用 [串流输入](<https://code.claude.com/docs/en/agent-sdk/streaming-vs-single-mode>) 以直接发送 Claude 新的指令。这绕过当前工具请求,并给 Claude 全新的指令以遵循 。 ## 处理澄清问题 当克劳德需要更多的方向 一项任务,有多种有效的方法, 它叫 `AskUserQuestion` 工具。这触发了您的 `canUseTool` 调用 `toolName` 设置为 `AskUserQuestion`。输入中包含 Claude 的问题作为多选择选项,您向用户显示并返回其选择。 澄清问题尤其常见于 [`plan` 模式](<https://code.claude.com/docs/en/agent-sdk/permissions#plan-mode-plan>),其中克劳德在提出计划之前探索了代码库并询问问题。这使得计划模式对于交互工作流程的理想化,在您想要克劳德在进行修改之前收集要求的地方。 以下步骤说明如何处理澄清问题: 1 通过一个 canUseTool 回调 传一个 `canUseTool` 在查询选项中调用。默认情况下, `AskUserQuestion` 。如果您指定了 `tools` 数组以限制克劳德的能力(例如只读的代理 `Read`, `Glob`,以及 `Grep`页:1 `AskUserQuestion` 否则克劳德将无法澄清问题: ``` async for message in query( prompt="Analyze this codebase", options=ClaudeAgentOptions( # Include AskUserQuestion in your tools list tools=["Read", "Glob", "Grep", "AskUserQuestion"], can_use_tool=can_use_tool, ), ): print(message) ``` ``` for await (const message of query({ prompt: "Analyze this codebase", options: { // Include AskUserQuestion in your tools list tools: ["Read", "Glob", "Grep", "AskUserQuestion"], canUseTool: async (toolName, input) => { // Placeholder that approves every call. The Detect AskUserQuestion step replaces it. return { behavior: "allow", updatedInput: input }; } } })) { console.log(message); } ``` 2 检测AskUserQuestion 在你的回话中,检查是否 `toolName` 等于 `AskUserQuestion` 与其他工具不同处理它: ``` async def can_use_tool(tool_name: str, input_data: dict, context): if tool_name == "AskUserQuestion": # Your implementation to collect answers from the user return await handle_clarifying_questions(input_data) # Handle other tools normally return await prompt_for_approval(tool_name, input_data) ``` ``` canUseTool: async (toolName, input) => { if (toolName === "AskUserQuestion") { // Your implementation to collect answers from the user return handleClarifyingQuestions(input); } // Handle other tools normally return promptForApproval(toolName, input); }; ``` 3 解析问题输入 内容包含克劳德的提问。 `questions` 数组。每个问题都有一个 `question` (要显示的文本), `options` (选择),以及 `multiSelect` (是否允许多个选择) : ``` { "questions": [ { "question": "How should I format the output?", "header": "Format", "options": [ { "label": "Summary", "description": "Brief overview" }, { "label": "Detailed", "description": "Full explanation" } ], "multiSelect": false }, { "question": "Which sections should I include?", "header": "Sections", "options": [ { "label": "Introduction", "description": "Opening context" }, { "label": "Conclusion", "description": "Final summary" } ], "multiSelect": true } ] } ``` 见 [提问格式](<https://code.claude.com/docs/en/agent-sdk/user-input#question-format>) 用于完整实地描述。 4 收集用户的答案 向用户提交问题并收集其选择。 您如何做到这一点取决于您的应用程序: 终端提示、 网络表单、 移动对话框等 。 5 返回给克劳德的答案 构建 `answers` 对象作为每个键所在的记录 `question` 文本和每个值都是所选选项的 `label`: | 从问题对象 | 用作 : | | --- | --- | | `question` 字段(例如, `"How should I format the output?"`) | 密钥 | | 选中选项 `label` 字段(例如, `"Summary"`) | 数值 | 对于多选择的问题,通过一系列标签或加入它们 `", "`。如果选中的话。 [支持自由文本输入](<https://code.claude.com/docs/en/agent-sdk/user-input#support-free-text-input>),使用用户的自定义文本作为值。 ``` return PermissionResultAllow( updated_input={ "questions": input_data.get("questions", []), "answers": { "How should I format the output?": "Summary", "Which sections should I include?": ["Introduction", "Conclusion"], }, } ) ``` ``` return { behavior: "allow", updatedInput: { questions: input.questions, answers: { "How should I format the output?": "Summary", "Which sections should I include?": "Introduction, Conclusion" } } }; ``` ### 提问格式 该投入包含克劳德在A.A.A.中提出的问题。 `questions` 数组。每个问题都有这些字段: | 外地 | 说明 | | --- | --- | | `question` | 要显示的问题全文 | | `header` | 问题短标签( 最大 12 字符) | | `options` | 2的矩阵 - 4 选择,每个选择带有 `label` 财务报告和财务报告 `description`. TypeScript:可选 `preview`。见 [选项预览](<https://code.claude.com/docs/en/agent-sdk/user-input#option-previews-typescript>). | | `multiSelect` | 若为: `true`,用户可以选择多个选项 | 您的回调收到的结构 : ``` { "questions": [ { "question": "How should I format the output?", "header": "Format", "options": [ { "label": "Summary", "description": "Brief overview of key points" }, { "label": "Detailed", "description": "Full explanation with examples" } ], "multiSelect": false } ] } ``` #### 选项预览( TypeScript ) `toolConfig.askUserQuestion.previewFormat` 增加一个 `preview` 字段到每个选项,这样您的应用程序就可以在标签旁显示一个视觉模拟。没有这个设置,克劳德就不会产生预览,字段就不存在了。 | `previewFormat` | `preview` 包含 | | --- | --- | | 未设置( 默认) | 字段没有。 Claude 不生成预览 。 | | `"markdown"` | ASCII 艺术和有栅栏的代码块 | | `"html"` | 一个风格 `<div>` 碎片( SDK 拒绝) `<script>`, `<style>`,以及 `<!DOCTYPE>` 在您的回话运行前) | 该格式适用于会话中的所有问题。 `preview` 在可视化比较有帮助的选项上(显示选择、颜色方案), 并省略人们不会选择的选项( 是/ 否确认, 仅文本选择)。 请检查 。 `undefined` 在渲染之前。 ``` import { query } from "@anthropic-ai/claude-agent-sdk"; for await (const message of query({ prompt: "Help me choose a card layout", options: { toolConfig: { askUserQuestion: { previewFormat: "html" } }, canUseTool: async (toolName, input) => { // input.questions[].options[].preview is an HTML string or undefined return { behavior: "allow", updatedInput: input }; } } })) { // ... } ``` 带有 HTML 预览的选项 : ``` { "label": "Compact", "description": "Title and metric value only", "preview": "<div style=\"padding:12px;border:1px solid #ddd;border-radius:8px\"><div style=\"font-size:12px;color:#666\">Active users</div><div style=\"font-size:28px;font-weight:600\">1,284</div></div>" } ``` ### 答复格式 返回一个 `answers` 每个问题的对象映射 `question` 字段到选定选项 `label`: | 外地 | 说明 | | --- | --- | | `questions` | 通过原问题阵列( 工具处理需要) | | `answers` | 键为问题文本和选定标签值的对象 | | `response` | 可选的自由格式回复输入的用户而不是回答结构化问题 | 对于多选择的问题,通过一系列标签或加入它们 `", "`。对于每个问题的自由文本,如 " 其他 " 选项,将用户的文本放入 `answers[question]` 显示于 [支持自由文本输入](<https://code.claude.com/docs/en/agent-sdk/user-input#support-free-text-input>)设置 `response` 只有当您的 UI 允许用户拒绝提问卡并输入一个不是回答任何具体问题的普通回答时。 `response` Claude收到“用户答复:......”而不是每个问题的答复清单。 ``` { "questions": [ // ... ], "answers": { "How should I format the output?": "Summary", "Which sections should I include?": ["Introduction", "Conclusion"] } } ``` #### 支持自由文本输入 Claude 预先定义的选项并不总是覆盖用户想要的。 让用户输入自己的答案 : - 在 Claude 选项后显示接受文本输入的附加“ 其他” 选项 - 使用用户的自定义文本作为答题值( 而不是 " 其他 " 一词) 见 [完整实例](<https://code.claude.com/docs/en/agent-sdk/user-input#complete-example>) 供全面执行。 ### 完整实例 克劳德在需要用户输入时会询问澄清问题。 例如, 当被请求帮助决定移动应用程序的技术堆栈时, 克劳德可能会询问跨平台 vs 本地, 后端偏好, 或者目标平台。 这些问题帮助克劳德做出与用户偏好相匹配的决定而不是猜测。 这个例子处理终端应用程序中的问题 。以下是每个步骤发生的情况: 1. **路径请求**编号: `canUseTool` 如果工具名称是 `"AskUserQuestion"` 和通往专用处理器的路线 2. **显示问题**: 处理器循环通过 `questions` 数组并用编号选项打印每个问题 3. **收集输入**:用户可以输入一个数字来选择一个选项,也可以直接输入免费文本(例如“jquery”,“我不知道”) 4. **地图解答**: 密码检查输入是数字( 使用选项的标签) 还是自由文本( 直接使用文本) 5. **回到克劳德身边**: 答复中包括两个原始内容。 `questions` 数组和 `answers` 绘图 将 TypeScript 版本另存为 `ask.ts` 和运行它与 `npx tsx ask.ts`,或者将 Python 版本保存为 `ask.py` 和运行它与 `python ask.py`. ``` import asyncio from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query from claude_agent_sdk.types import HookMatcher, PermissionResultAllow def parse_response(response: str, options: list) -> str: """Parse user input as option number(s) or free text.""" try: indices = [int(s.strip()) - 1 for s in response.split(",")] labels = [options[i]["label"] for i in indices if 0 <= i < len(options)] return ", ".join(labels) if labels else response except ValueError: return response async def handle_ask_user_question(input_data: dict) -> PermissionResultAllow: """Display Claude's questions and collect user answers.""" answers = {} for q in input_data.get("questions", []): print(f"\n{q['header']}: {q['question']}") options = q["options"] for i, opt in enumerate(options): print(f" {i + 1}. {opt['label']} - {opt['description']}") if q.get("multiSelect"): print(" (Enter numbers separated by commas, or type your own answer)") else: print(" (Enter a number, or type your own answer)") response = input("Your choice: ").strip() answers[q["question"]] = parse_response(response, options) return PermissionResultAllow( updated_input={ "questions": input_data.get("questions", []), "answers": answers, } ) async def can_use_tool( tool_name: str, input_data: dict, context ) -> PermissionResultAllow: # Route AskUserQuestion to our question handler if tool_name == "AskUserQuestion": return await handle_ask_user_question(input_data) # Auto-approve other tools for this example return PermissionResultAllow(updated_input=input_data) async def prompt_stream(): yield { "type": "user", "message": { "role": "user", "content": "Help me decide on the tech stack for a new mobile app", }, } # Required workaround: dummy hook keeps the stream open for can_use_tool async def dummy_hook(input_data, tool_use_id, context): return {"continue_": True} async def main(): async for message in query( prompt=prompt_stream(), options=ClaudeAgentOptions( can_use_tool=can_use_tool, hooks={"PreToolUse": [HookMatcher(matcher=None, hooks=[dummy_hook])]}, ), ): if isinstance(message, ResultMessage) and message.subtype == "success": print(message.result) asyncio.run(main()) ``` ``` import { query } from "@anthropic-ai/claude-agent-sdk"; import type { PermissionResult } from "@anthropic-ai/claude-agent-sdk"; import * as readline from "readline/promises"; // Helper to prompt user for input in the terminal async function prompt(question: string): Promise<string> { const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); const answer = await rl.question(question); rl.close(); return answer; } // Parse user input as option number(s) or free text function parseResponse(response: string, options: any[]): string { const indices = response.split(",").map((s) => parseInt(s.trim()) - 1); const labels = indices .filter((i) => !isNaN(i) && i >= 0 && i < options.length) .map((i) => options[i].label); return labels.length > 0 ? labels.join(", ") : response; } // Display Claude's questions and collect user answers async function handleAskUserQuestion(input: any): Promise<PermissionResult> { const answers: Record<string, string> = {}; for (const q of input.questions) { console.log(`\n${q.header}: ${q.question}`); const options = q.options; options.forEach((opt: any, i: number) => { console.log(` ${i + 1}. ${opt.label} - ${opt.description}`); }); if (q.multiSelect) { console.log(" (Enter numbers separated by commas, or type your own answer)"); } else { console.log(" (Enter a number, or type your own answer)"); } const response = (await prompt("Your choice: ")).trim(); answers[q.question] = parseResponse(response, options); } // Return the answers to Claude (must include original questions) return { behavior: "allow", updatedInput: { questions: input.questions, answers } }; } async function main() { for await (const message of query({ prompt: "Help me decide on the tech stack for a new mobile app", options: { canUseTool: async (toolName, input) => { // Route AskUserQuestion to our question handler if (toolName === "AskUserQuestion") { return handleAskUserQuestion(input); } // Auto-approve other tools for this example return { behavior: "allow", updatedInput: input }; } } })) { if ("result" in message) console.log(message.result); } } main(); ``` ## 限制 - **副剂**: `AskUserQuestion` 目前无法在通过代理工具生成的子剂中找到 - **问题限制**: 每个 `AskUserQuestion` 呼叫支持 1 - 使用 2 的 4 问题 - 4 每个选项 ## 获得用户输入的其他方式 那个... `canUseTool` 调用和 `AskUserQuestion` 工具涵盖大多数批准和澄清设想,但SDK提供了从用户获取投入的其他方式: ### 流转输入 使用( U) [串流输入](<https://code.claude.com/docs/en/agent-sdk/streaming-vs-single-mode>) 当您需要时: - **中断代理任务中段**: 在克劳德工作时发出取消信号或改变方向 - **提供额外背景**: 添加 Claude 需要的信息而不等待它问 - **构建聊天界面**: 让用户在长期操作中发送后续信息 用户在执行过程中与代理人互动,而不仅仅是在批准检查站互动,对对话用户界面而言,流畅的投入是理想的。 ### 自定义工具 使用( U) [自定义工具](<https://code.claude.com/docs/en/agent-sdk/custom-tools>) 当您需要时: - **收集结构化输入**: 构建窗体、向导或超越的多步工作流程 `AskUserQuestion`多选择格式 - **整合外部核准系统**: 连接到现有的售票、工作流程或批准平台 - **执行特定域的互动**: 创建适合应用程序需要的工具, 如代码审查接口或部署核对表 自定义工具会让您完全控制互动, 但需要更多的执行工作 而不是使用内置 `canUseTool` 召回电话。 ## 相关资源 - [配置权限](<https://code.claude.com/docs/en/agent-sdk/permissions>): 设置许可模式和规则 - [用钩子控制执行](<https://code.claude.com/docs/en/agent-sdk/hooks>): 在代理寿命周期的关键点运行自定义代码 - [TypeScript SDK 参考文献](<https://code.claude.com/docs/en/agent-sdk/typescript#canusetool>): 完整 canUseTool API 文档

查看原始来源