Grant the SDK a tool
By default, the Agent SDK is read-only: Claude can read and search, but it cannot change your files. To let it make edits, you create a ClaudeAgentOptions object listing the tools you want to allow and pass it to query().
A package.json is in your working directory. Complete the script so the SDK is allowed to use the Edit tool and asks Claude to add a description. The script prints package.json before and after, so you can watch the edit happen.
Bài tập này là một phần của khóa học
Claude Code in Action
Hướng dẫn bài tập
- Create
optionsby callingClaudeAgentOptions()withallowed_toolsset to a list containing"Edit". - Pass your
optionsobject toquery()using theoptionsargument.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
# package.json before the SDK runs
print("BEFORE:\n" + open("package.json").read())
async def main():
# The SDK is read-only by default; allow the Edit tool so Claude can write
options = ____
# Pass the options so the permission takes effect
async for message in query(
prompt='Add a "description" field to package.json.',
options=____,
):
print(message)
asyncio.run(main())
# package.json after the SDK runs - the description now appears
print("AFTER:\n" + open("package.json").read())