2025 年 6 月,我想用 Claude Code 做个东西。用 SDK 看起来是把它的编程工具接进自己应用的最快办法。我记得读过那篇 Reddit 帖子后,还以为 SDK 刚刚发布。1 评论里讨论的是用脚本调用命令行界面并读取 JSON 输出。其实 5 月 19 日 Hacker News 上就有这个界面了。Python 包更新一些,我查它的两天前,也就是 6 月 12 日,Anthropic 上传了 claude-code-sdk 0.0.10。2
我卡住的问题是:Claude 要执行命令时会发生什么?我问 DeepSeek 怎么处理权限,得到的是有关 API 密钥的回答。API 密钥让应用能访问模型;我想要的是让使用应用的人看到命令,并决定要不要运行。当天晚上我又问了一遍。3
when execute command it needs permission from user, how to handle this programmatically using sdk
2025 年 6 月的 SDK 把审批请求发到哪里?
假设我请智能体运行项目测试。它提议用 shell 工具 Bash 执行 npm test。我希望应用显示这条一字不差的命令,等用户作决定后再执行。把智能体的流式 JSON 打印出来只能得到记录。我该把用户的回答发到哪里?当时打开的示例覆盖文件处理、脚本、流式 JSON 和 CLI 选项。4
在 Python SDK 0.0.10 中,query() 会把 Claude Code CLI 作为子进程启动。包装层做了两件独立的事:要求以 stream-json 输出,并把 Python 选项 permission_prompt_tool_name 转换为 CLI 参数 --permission-prompt-tool。CLI 将它描述为 “MCP tool to use for permission prompts (only works with --print)”,即用于权限提示的 MCP 工具,仅支持 --print。Python 包装层启动子进程时本来就会提供 --print。56
为一条命令接上能工作的审批工具
如果在 Linux 桌面上接入当年 6 月的接口,我会这样做。准备 Python 3.10 及以上版本的虚拟环境,确保 PATH 中有已登录的 Claude Code CLI 1.0.24,并安装 Zenity 显示确认窗口。把 Python 依赖一起安装。固定 Pydantic 版本,是为了让这个较老的 MCP 版本与验证库兼容。67
python -m pip install claude-code-sdk==0.0.10 mcp==1.9.3 pydantic==2.11.5 pydantic-settings==2.9.1
把下面两个 Python 文件放在同一个目录。
先把审批工具存为 review.py。模型上下文协议(MCP) 让 CLI 调用另一个进程中有名字的工具。这里工具收到 Bash 和完整的提议输入,例如 {"command": "npm test"},然后如实展示。用户点击 Run once 时,Zenity 返回退出码零;点击 Decline 或关闭窗口都视为拒绝。
import json
import subprocess
from mcp.server.fastmcp import FastMCP
server = FastMCP("review")
@server.tool()
def approve(tool_name: str, input: dict) -> str:
"""Ask the user whether Claude Code may run this particular command."""
decision = {"behavior": "deny", "message": "User declined the command."}
if tool_name != "Bash":
return json.dumps({"behavior": "deny", "message": "This dialog reviews Bash only."})
try:
dialog = subprocess.run([
"zenity", "--question", "--no-markup", "--default-cancel",
"--title=Allow Claude Code to use Bash?",
"--ok-label=Run once", "--cancel-label=Decline",
"--text", json.dumps(input, indent=2),
])
except OSError:
return json.dumps({"behavior": "deny", "message": "Approval dialog unavailable."})
if dialog.returncode == 0:
decision = {"behavior": "allow", "updatedInput": input}
return json.dumps(decision)
if __name__ == "__main__":
server.run(transport="stdio")
然后在应用的 app.py 中注册该工具。把桌面会话环境变量传给子进程,让它能打开对话框,同时用标准输入输出传递 MCP 消息。服务器名 review 和函数名 approve 组成 CLI 工具名 mcp__review__approve。别把 Bash 加入允许列表,这样在既有权限规则要求用户决定时,命令才能到达对话框。568
import asyncio
import os
import sys
from pathlib import Path
from claude_code_sdk import ClaudeCodeOptions, query
async def main():
server_file = Path(__file__).with_name("review.py").resolve()
display_vars = ("DISPLAY", "XAUTHORITY", "WAYLAND_DISPLAY", "XDG_RUNTIME_DIR",
"DBUS_SESSION_BUS_ADDRESS")
review_server = {
"command": sys.executable,
"args": [str(server_file)],
"env": {key: os.environ[key] for key in display_vars if key in os.environ},
}
options = ClaudeCodeOptions(
mcp_servers={"review": review_server},
permission_prompt_tool_name="mcp__review__approve",
)
async for message in query(prompt="Run npm test in this project.", options=options):
print(message)
if __name__ == "__main__":
asyncio.run(main())
在项目目录运行 python app.py。命令需要审批时,用户阅读对话框,CLI 等待 MCP 回复。FastMCP 把 approve 返回的字符串放入一个文本块,CLI 1.0.24 会从中解析 JSON 决策。点击 Run once,Claude Code 收到审阅过的输入并执行命令。点击 Decline,它会收到理由并跳过该调用。对话框本身不会启动 npm test。67
Claude Coder 扩展使用了这套权限 API 吗?
我看过 Anthropic 的编辑器集成和项目记忆指南。9 Kodu 的 Claude Coder 扩展刚好能提供我想象的交互,我打开了它的 Marketplace 页面。10 我想知道它是否使用 Claude Code SDK,又怎样把权限提示接到 VS Code 按钮。
在 4 月份 Claude Coder 2.3.13 的源码中,扩展只把 Claude 作为模型调用,命令执行由自己实现。它的 manifest 与我当时打开的扩展相符。源码里有两条连接模型的路径,也解释了为什么「Claude SDK」这个名字容易混淆。10
| 在扩展中选择的连接 | 请求怎样从 VS Code 发出去 |
|---|---|
| 直接接 Anthropic | Kodu 调用 Vercel @ai-sdk/anthropic 适配器中的 createAnthropic({apiKey}).languageModel(modelId),再用 ai 包的 streamText 发送消息并读取回复。11 |
| 使用 Kodu 服务 | Kodu 用通用的 @anthropic-ai/sdk 中的消息类型描述 TypeScript 请求。实际网络调用是 axios.post(getKoduInferenceUrl(), …),返回数据流。扩展源码能看到从客户端到 Kodu 服务的第一跳。12 |
两条路径都没有通过 Claude Code SDK 审批或执行命令。扩展从模型返回的流式文本中解析工具标签。识别到 execute_command 请求时,它自己的执行器会发起审批并等待。下面是一条需要点击确认的命令所走的路径。131415
sequenceDiagram
actor User
participant K as Claude Coder in VS Code
participant M as Selected model service
participant T as VS Code terminal
K->>M: Send task and conversation
M-->>K: Stream a request to run npm test
K->>User: Allow npm test?
alt Run once
User->>K: Approve
K->>T: Run npm test
T-->>K: Command output
K->>M: Include the result in the next turn
else Decline
User->>K: Reject
K->>M: Report rejection or user feedback
end
我真正要找的那行代码,原来是执行器检查 yesButtonTapped 的地方。同意后走到 terminalManager.runCommand;拒绝则提前返回,将用户写下的反馈带回对话。如果我的应用用的是 Claude Code SDK,同样两个按钮就应当回答 review.py 里的 MCP 请求,而终端操作由 Claude Code 负责。1513
在后来的 Claude Agent SDK 中该用什么?
后来的 Python 包 claude-agent-sdk 在 ClaudeAgentOptions 上提供 can_use_tool 回调。需要进入回调的 shell 调用,可以从 input_data["command"] 读取提议命令。应用显示命令、等待用户选择,然后返回 PermissionResultAllow(updated_input=input_data) 或 PermissionResultDeny(message="User declined to run the tests.")。Anthropic 的 Python 示例演示了如何在流式会话里接上这个回调。16
到了 8 月,我又研究了自己实现工具执行器需要做什么。6 月时 SDK 吸引我的地方,恰恰是能少写多少代码:我的应用只需征求同意;Claude Code 可以执行获准命令,收集输出并把结果带回对话。
参考资料
Footnotes
-
coding_workflow. (n.d.). Comment on the Claude Code SDK discussion. Reddit, r/ClaudeAI. See the comment on CLI and JSON output. Also see sync. (2025, May 19). Claude Code SDK. Hacker News. ↩
-
Anthropic. (2025, June 12). Claude Code SDK 0.0.10 [Python distribution]. PyPI. Release files and upload dates. ↩
-
Cai, B. (2025, June 14). Handling Permissions in Claude SDK Guide [Private DeepSeek conversation]. Second user message, 18:48 Shanghai time. ↩
-
Anthropic. (n.d.). Agent SDK overview. Claude Code Docs. Saved section links for processing files, script integration, streaming JSON output, and available CLI options. These fragments come from the former SDK guide and may open the top of the revised overview. See also the CLI reference. ↩
-
Anthropic. (2025, June 12). Claude Code SDK for Python (commit
54bff2e). GitHub. Python SDK repository. See the query interface, public options, and construction of the CLI command. ↩ ↩2 -
Anthropic. (2025, June 14). Claude Code 1.0.24 [CLI distribution]. npm. Claude Code repository and versioned package,
cli.js, option text for--permission-prompt-tooland the parser for the first MCP text block. ↩ ↩2 ↩3 ↩4 -
Model Context Protocol. (2025). MCP Python SDK 1.9.3. PyPI. Tools and direct execution. ↩ ↩2
-
Anthropic. (n.d.). Security and Settings. Claude Code Docs. The saved links point to tools available to Claude and permission settings. The June implementation is pinned in the CLI and Python sources above. ↩
-
Anthropic. (n.d.). Use Claude Code in VS Code and How Claude remembers your project. Claude Code Docs. Editor integration and project memory. ↩
-
Kodu AI. (2025, April 30). Claude Coder (commit
60c1a71). GitHub. Visual Studio Marketplace listing, extension manifest and project's link to the Marketplace listing. ↩ ↩2 -
Kodu AI. (2025, April 30). Custom API handler. GitHub. Anthropic model construction and streaming the selected model. ↩
-
Kodu AI. (2025, April 30). Kodu API handler. GitHub. Selecting the handler and typed request body and HTTP call. ↩
-
Kodu AI. (2025, April 30). Task executor. GitHub. Parsing tool requests in the stream and collecting tool results for the conversation. ↩ ↩2
-
Kodu AI. (2025, April 30). AskManager. GitHub. Receiving a response and creating a pending request. ↩
-
Kodu AI. (2025, April 30). Execute command tool. GitHub. Approval, rejection, and terminal execution. ↩ ↩2
-
Anthropic. (n.d.). Handle approvals and user input. Claude Code Docs. Tool approval example, Python tab. ↩