Quickstart changedagent-sdk/quickstart
Nearest release: v2.1.291, published under an hour after upstream edited the page. Shown because the two are within 24 hours of each other. Nothing here says the release caused the edit.
Upstream edited this page at 6 Oct 2026 03:21 UTC, give or take a minute or two: the time comes from Anthropic’s own sitemap rather than from a commit. This site recorded the change at 20 Oct 2026 18:37 UTC.
Upstream edited
Recorded here
Lines+229added
Lines−245removed
From line
17
where the diff opens
First seen
14 Aug 2026
this site's first read of the page
Recorded edits10to this page, all time
The whole hunk
from line 17, old and new numbered
/
from line 17
1717
1818## Setup
1919
20<Steps>
21 <Step title="Create a project folder">
22 Create a new directory for this quickstart:
20**1. Create a project folder**
2321
24 ```bash theme={null}
25 mkdir my-agent
26 cd my-agent
27 ```
22Create a new directory for this quickstart:
2823
29 For your own projects, you can run the SDK from any folder; it will have access to files in that directory and its subdirectories by default.
30 </Step>
24```bash theme={null}
25mkdir my-agent
26cd my-agent
27```
3128
32 <Step title="Install the SDK">
33 Install the Agent SDK package for your language:
29For your own projects, you can run the SDK from any folder; it will have access to files in that directory and its subdirectories by default.
3430
35 <Tabs>
36 <Tab title="TypeScript (new project)">
37 ```bash theme={null}
38 npm init -y
39 npm pkg set type=module
40 npm install @anthropic-ai/claude-agent-sdk
41 npm install --save-dev tsx
42 ```
31**2. Install the SDK**
4332
44 Setting `"type": "module"` in `package.json` lets your agent script use top-level `await`, and [tsx](https://tsx.hirok.io) runs TypeScript files directly. npm prints `added N packages` when the install succeeds.
45 </Tab>
33Install the Agent SDK package for your language:
4634
47 <Tab title="TypeScript (existing project)">
48 ```bash theme={null}
49 npm install @anthropic-ai/claude-agent-sdk
50 npm install --save-dev tsx
51 ```
35**TypeScript (new project)**
5236
53 [tsx](https://tsx.hirok.io) runs TypeScript files directly. If your project uses CommonJS, name your agent script `agent.mts` instead of `agent.ts`. The `.mts` extension makes tsx treat the file as an ES module, so top-level `await` works without converting your whole project to ES modules. Use `agent.mts` in place of `agent.ts` in the create and run steps later in this quickstart.
54 </Tab>
37```bash theme={null}
38npm init -y
39npm pkg set type=module
40npm install @anthropic-ai/claude-agent-sdk
41npm install --save-dev tsx
42```
5543
56 <Tab title="Python (uv)">
57 [Install uv](https://docs.astral.sh/uv/), a fast Python package manager that handles virtual environments automatically. Then initialize a project and add the SDK:
44Setting `"type": "module"` in `package.json` lets your agent script use top-level `await`, and [tsx](https://tsx.hirok.io) runs TypeScript files directly. npm prints `added N packages` when the install succeeds.
5845
59 ```bash theme={null}
60 uv init
61 uv add claude-agent-sdk
62 ```
63 </Tab>
46**TypeScript (existing project)**
6447
65 <Tab title="Python (pip)">
66 Create and activate a virtual environment, then install the package.
48```bash theme={null}
49npm install @anthropic-ai/claude-agent-sdk
50npm install --save-dev tsx
51```
6752
68 On macOS or Linux:
53[tsx](https://tsx.hirok.io) runs TypeScript files directly. If your project uses CommonJS, name your agent script `agent.mts` instead of `agent.ts`. The `.mts` extension makes tsx treat the file as an ES module, so top-level `await` works without converting your whole project to ES modules. Use `agent.mts` in place of `agent.ts` in the create and run steps later in this quickstart.
6954
70 ```bash theme={null}
71 python3 -m venv .venv
72 source .venv/bin/activate
73 pip install claude-agent-sdk
74 ```
55**Python (uv)**
7556
76 On Windows:
57[Install uv](https://docs.astral.sh/uv/), a fast Python package manager that handles virtual environments automatically. Then initialize a project and add the SDK:
7758
78 ```powershell theme={null}
79 py -m venv .venv
80 .venv\Scripts\Activate.ps1
81 pip install claude-agent-sdk
82 ```
59```bash theme={null}
60uv init
61uv add claude-agent-sdk
62```
8363
84 If PowerShell blocks `Activate.ps1` with an execution policy error, run `Set-ExecutionPolicy -Scope Process RemoteSigned` first.
85 </Tab>
86 </Tabs>
64**Python (pip)**
8765
88 <Note>
89 Both the TypeScript and Python SDKs bundle a native Claude Code binary, so most installs need no separate Claude Code install. Some installs have no bundled binary:
66Create and activate a virtual environment, then install the package.
9067
91 * If pip installs the Python SDK's source distribution instead of a platform wheel, for example on ARM64 Windows, no binary is bundled. [Install Claude Code natively](/docs/en/setup#install-claude-code). The Python SDK finds it on your `PATH`.
92 * The TypeScript SDK installs its binary through npm optional dependencies, so an install that skips them, for example `npm ci --omit=optional`, gets no binary even on a supported platform. Reinstall without skipping optional dependencies, or [install Claude Code natively](/docs/en/setup#install-claude-code) and set `pathToClaudeCodeExecutable` to its path.
93 </Note>
94 </Step>
68On macOS or Linux:
9569
96 <Step title="Set your API key">
97 Get an API key from the [Claude Console](https://platform.claude.com/), then set it as an environment variable in the shell where you'll run your agent:
70```bash theme={null}
71python3 -m venv .venv
72source .venv/bin/activate
73pip install claude-agent-sdk
74```
9875
99 <Tabs>
100 <Tab title="macOS / Linux">
101 ```bash theme={null}
102 export ANTHROPIC_API_KEY=your-api-key
103 ```
104 </Tab>
76On Windows:
10577
106 <Tab title="Windows (PowerShell)">
107 ```powershell theme={null}
108 $env:ANTHROPIC_API_KEY = "your-api-key"
109 ```
110 </Tab>
111 </Tabs>
78```powershell theme={null}
79py -m venv .venv
80.venv\Scripts\Activate.ps1
81pip install claude-agent-sdk
82```
11283
113 The SDK reads the key from the environment of the process that runs your agent; it doesn't load `.env` files automatically. If you keep the key in a `.env` file, load it yourself, for example with the `dotenv` package, before calling the SDK.
84If PowerShell blocks `Activate.ps1` with an execution policy error, run `Set-ExecutionPolicy -Scope Process RemoteSigned` first.
11485
115 The SDK also supports authentication via third-party API providers:
86> [!NOTE]
87>
88> Both the TypeScript and Python SDKs bundle a native Claude Code binary, so most installs need no separate Claude Code install. Some installs have no bundled binary:
89>
90> * If pip installs the Python SDK's source distribution instead of a platform wheel, for example on ARM64 Windows, no binary is bundled. [Install Claude Code natively](/docs/en/setup#install-claude-code). The Python SDK finds it on your `PATH`.
91> * The TypeScript SDK installs its binary through npm optional dependencies, so an install that skips them, for example `npm ci --omit=optional`, gets no binary even on a supported platform. Reinstall without skipping optional dependencies, or [install Claude Code natively](/docs/en/setup#install-claude-code) and set `pathToClaudeCodeExecutable` to its path.
11692
117 * **Amazon Bedrock**: set `CLAUDE_CODE_USE_BEDROCK=1` environment variable and configure AWS credentials
118 * **Claude Platform on AWS**: set `CLAUDE_CODE_USE_ANTHROPIC_AWS=1` and `ANTHROPIC_AWS_WORKSPACE_ID`, then configure AWS credentials
119 * **Google Cloud's Agent Platform**: set `CLAUDE_CODE_USE_VERTEX=1` environment variable and configure Google Cloud credentials
120 * **Microsoft Foundry**: set `CLAUDE_CODE_USE_FOUNDRY=1` environment variable and configure Azure credentials
93**3. Set your API key**
12194
122 See the setup guides for [Amazon Bedrock](/docs/en/amazon-bedrock), [Claude Platform on AWS](/docs/en/claude-platform-on-aws), [Google Cloud's Agent Platform](/docs/en/google-vertex-ai), or [Microsoft Foundry](/docs/en/microsoft-foundry) for details.
95Get an API key from the [Claude Console](https://platform.claude.com/), then set it as an environment variable in the shell where you'll run your agent:
12396
124 <Note>
125 Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK. Use the API key authentication methods described in this document instead.
126 </Note>
127 </Step>
128</Steps>
97**macOS / Linux**
12998
99```bash theme={null}
100export ANTHROPIC_API_KEY=your-api-key
101```
102
103**Windows (PowerShell)**
104
105```powershell theme={null}
106$env:ANTHROPIC_API_KEY = "your-api-key"
107```
108
109The SDK reads the key from the environment of the process that runs your agent; it doesn't load `.env` files automatically. If you keep the key in a `.env` file, load it yourself, for example with the `dotenv` package, before calling the SDK.
110
111The SDK also supports authentication via third-party API providers:
112
113* **Amazon Bedrock**: set `CLAUDE_CODE_USE_BEDROCK=1` environment variable and configure AWS credentials
114* **Claude Platform on AWS**: set `CLAUDE_CODE_USE_ANTHROPIC_AWS=1` and `ANTHROPIC_AWS_WORKSPACE_ID`, then configure AWS credentials
115* **Google Cloud's Agent Platform**: set `CLAUDE_CODE_USE_VERTEX=1` environment variable and configure Google Cloud credentials
116* **Microsoft Foundry**: set `CLAUDE_CODE_USE_FOUNDRY=1` environment variable and configure Azure credentials
117
118See the setup guides for [Amazon Bedrock](/docs/en/amazon-bedrock), [Claude Platform on AWS](/docs/en/claude-platform-on-aws), [Google Cloud's Agent Platform](/docs/en/google-vertex-ai), or [Microsoft Foundry](/docs/en/microsoft-foundry) for details.
119
120> [!NOTE]
121>
122> Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK. Use the API key authentication methods described in this document instead.
123
130124## Create a buggy file
131125
132126This quickstart walks you through building an agent that can find and fix bugs in code. First, you need a file with some intentional bugs for the agent to fix. Create `utils.py` in the `my-agent` directory and paste the following code:
from line 146
152146
153147Create `agent.py` if you're using the Python SDK, or `agent.ts` for TypeScript. Use `agent.mts` instead if your existing project uses CommonJS:
154148
155<CodeGroup>
156 ```python Python theme={null}
157 import asyncio
158 from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage
149```python Python theme={null}
150import asyncio
151from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage
159152
160153
161 async def main():
162 # Agentic loop: streams messages as Claude works
163 async for message in query(
164 prompt="Review utils.py for bugs that would cause crashes. Fix any issues you find.",
165 options=ClaudeAgentOptions(
166 allowed_tools=["Read", "Edit", "Glob"], # Auto-approve these tools
167 permission_mode="acceptEdits", # Auto-approve file edits
168 ),
169 ):
170 # Print human-readable output
171 if isinstance(message, AssistantMessage):
172 for block in message.content:
173 if hasattr(block, "text"):
174 print(block.text) # Claude's reasoning
175 elif hasattr(block, "name"):
176 print(f"Tool: {block.name}") # Tool being called
177 elif isinstance(message, ResultMessage):
178 print(f"Done: {message.subtype}") # Final result
154async def main():
155 # Agentic loop: streams messages as Claude works
156 async for message in query(
157 prompt="Review utils.py for bugs that would cause crashes. Fix any issues you find.",
158 options=ClaudeAgentOptions(
159 allowed_tools=["Read", "Edit", "Glob"], # Auto-approve these tools
160 permission_mode="acceptEdits", # Auto-approve file edits
161 ),
162 ):
163 # Print human-readable output
164 if isinstance(message, AssistantMessage):
165 for block in message.content:
166 if hasattr(block, "text"):
167 print(block.text) # Claude's reasoning
168 elif hasattr(block, "name"):
169 print(f"Tool: {block.name}") # Tool being called
170 elif isinstance(message, ResultMessage):
171 print(f"Done: {message.subtype}") # Final result
179172
180173
181 asyncio.run(main())
182 ```
174asyncio.run(main())
175```
183176
184 ```typescript TypeScript theme={null}
185 import { query } from "@anthropic-ai/claude-agent-sdk";
177```typescript TypeScript theme={null}
178import { query } from "@anthropic-ai/claude-agent-sdk";
186179
187 // Agentic loop: streams messages as Claude works
188 for await (const message of query({
189 prompt: "Review utils.py for bugs that would cause crashes. Fix any issues you find.",
190 options: {
191 allowedTools: ["Read", "Edit", "Glob"], // Auto-approve these tools
192 permissionMode: "acceptEdits" // Auto-approve file edits
193 }
194 })) {
195 // Print human-readable output
196 if (message.type === "assistant" && message.message?.content) {
197 for (const block of message.message.content) {
198 if ("text" in block) {
199 console.log(block.text); // Claude's reasoning
200 } else if ("name" in block) {
201 console.log(`Tool: ${block.name}`); // Tool being called
202 }
180// Agentic loop: streams messages as Claude works
181for await (const message of query({
182 prompt: "Review utils.py for bugs that would cause crashes. Fix any issues you find.",
183 options: {
184 allowedTools: ["Read", "Edit", "Glob"], // Auto-approve these tools
185 permissionMode: "acceptEdits" // Auto-approve file edits
186 }
187})) {
188 // Print human-readable output
189 if (message.type === "assistant" && message.message?.content) {
190 for (const block of message.message.content) {
191 if ("text" in block) {
192 console.log(block.text); // Claude's reasoning
193 } else if ("name" in block) {
194 console.log(`Tool: ${block.name}`); // Tool being called
203195 }
204 } else if (message.type === "result") {
205 console.log(`Done: ${message.subtype}`); // Final result
206196 }
197 } else if (message.type === "result") {
198 console.log(`Done: ${message.subtype}`); // Final result
207199 }
208 ```
209</CodeGroup>
200}
201```
210202
211203This code has three main parts:
212204
from line 212
220212
221213The message handling inside the loop filters for human-readable output. Without filtering, you'd see raw message objects including system initialization and internal state, which is useful for debugging but noisy otherwise.
222214
223<Note>
224 This example uses streaming to show progress in real-time. If you don't need live output (for example, for background jobs or CI pipelines), you can collect all messages at once. See [Streaming vs. single-turn mode](/docs/en/agent-sdk/streaming-vs-single-mode) for details.
225</Note>
215> [!NOTE]
216>
217> This example uses streaming to show progress in real-time. If you don't need live output (for example, for background jobs or CI pipelines), you can collect all messages at once. See [Streaming vs. single-turn mode](/docs/en/agent-sdk/streaming-vs-single-mode) for details.
226218
227219### Run your agent
228220
229221Your agent is ready. Run it with the following command:
230222
231<Tabs>
232 <Tab title="TypeScript">
233 ```bash theme={null}
234 npx tsx agent.ts
235 ```
223**TypeScript**
236224
237 If you named your script `agent.mts`, run `npx tsx agent.mts` instead.
238 </Tab>
225```bash theme={null}
226npx tsx agent.ts
227```
239228
240 <Tab title="Python (uv)">
241 ```bash theme={null}
242 uv run agent.py
243 ```
244 </Tab>
229If you named your script `agent.mts`, run `npx tsx agent.mts` instead.
245230
246 <Tab title="Python (pip)">
247 With your virtual environment still activated:
231**Python (uv)**
248232
249 ```bash theme={null}
250 python agent.py
251 ```
252 </Tab>
253</Tabs>
233```bash theme={null}
234uv run agent.py
235```
254236
237**Python (pip)**
238
239With your virtual environment still activated:
240
241```bash theme={null}
242python agent.py
243```
244
255245As it works, the agent prints its reasoning and each tool it calls, ending with `Done: success`. After running, check `utils.py`. You'll see defensive code handling empty lists and null users. Your agent autonomously:
256246
2572471. **Read** `utils.py` to understand the code
from line 250
260250
261251This is what makes the Agent SDK different: Claude executes tools directly instead of asking you to implement them.
262252
263<Note>
264 If you see an authentication error such as `Not logged in` or `Invalid API key`, make sure you've set the `ANTHROPIC_API_KEY` environment variable in the shell where you run your agent. The SDK doesn't load `.env` files automatically.
253> [!NOTE]
254>
255> If you see an authentication error such as `Not logged in` or `Invalid API key`, make sure you've set the `ANTHROPIC_API_KEY` environment variable in the shell where you run your agent. The SDK doesn't load `.env` files automatically.
256>
257> For the causes and fixes behind these and other authentication errors, see [Authentication errors](/docs/en/errors#authentication-errors) in the Error reference.
265258
266 For the causes and fixes behind these and other authentication errors, see [Authentication errors](/docs/en/errors#authentication-errors) in the Error reference.
267</Note>
268
269259### Try other prompts
270260
271261Now that your agent is set up, try some different prompts:
from line 270
280270
281271**Add web search capability:**
282272
283<CodeGroup>
284 ```python Python theme={null}
285 options = ClaudeAgentOptions(
286 allowed_tools=["Read", "Edit", "Glob", "WebSearch"], permission_mode="acceptEdits"
287 )
288 ```
273```python Python theme={null}
274options = ClaudeAgentOptions(
275 allowed_tools=["Read", "Edit", "Glob", "WebSearch"], permission_mode="acceptEdits"
276)
277```
289278
290 ```typescript TypeScript hidelines={1,-1} theme={null}
291 const _ = {
292 options: {
293 allowedTools: ["Read", "Edit", "Glob", "WebSearch"],
294 permissionMode: "acceptEdits"
295 }
296 };
297 ```
298</CodeGroup>
279```typescript TypeScript hidelines={1,-1} theme={null}
280const _ = {
281 options: {
282 allowedTools: ["Read", "Edit", "Glob", "WebSearch"],
283 permissionMode: "acceptEdits"
284 }
285};
286```
299287
300288**Give Claude a custom system prompt:**
301289
302<CodeGroup>
303 ```python Python theme={null}
304 options = ClaudeAgentOptions(
305 allowed_tools=["Read", "Edit", "Glob"],
306 permission_mode="acceptEdits",
307 system_prompt="You are a senior Python developer. Always follow PEP 8 style guidelines.",
308 )
309 ```
290```python Python theme={null}
291options = ClaudeAgentOptions(
292 allowed_tools=["Read", "Edit", "Glob"],
293 permission_mode="acceptEdits",
294 system_prompt="You are a senior Python developer. Always follow PEP 8 style guidelines.",
295)
296```
310297
311 ```typescript TypeScript hidelines={1,-1} theme={null}
312 const _ = {
313 options: {
314 allowedTools: ["Read", "Edit", "Glob"],
315 permissionMode: "acceptEdits",
316 systemPrompt: "You are a senior Python developer. Always follow PEP 8 style guidelines."
317 }
318 };
319 ```
320</CodeGroup>
298```typescript TypeScript hidelines={1,-1} theme={null}
299const _ = {
300 options: {
301 allowedTools: ["Read", "Edit", "Glob"],
302 permissionMode: "acceptEdits",
303 systemPrompt: "You are a senior Python developer. Always follow PEP 8 style guidelines."
304 }
305};
306```
321307
322308**Run commands in the terminal:**
323309
324<CodeGroup>
325 ```python Python theme={null}
326 options = ClaudeAgentOptions(
327 allowed_tools=["Read", "Edit", "Glob", "Bash"], permission_mode="acceptEdits"
328 )
329 ```
310```python Python theme={null}
311options = ClaudeAgentOptions(
312 allowed_tools=["Read", "Edit", "Glob", "Bash"], permission_mode="acceptEdits"
313)
314```
330315
331 ```typescript TypeScript hidelines={1,-1} theme={null}
332 const _ = {
333 options: {
334 allowedTools: ["Read", "Edit", "Glob", "Bash"],
335 permissionMode: "acceptEdits"
336 }
337 };
338 ```
339</CodeGroup>
316```typescript TypeScript hidelines={1,-1} theme={null}
317const _ = {
318 options: {
319 allowedTools: ["Read", "Edit", "Glob", "Bash"],
320 permissionMode: "acceptEdits"
321 }
322};
323```
340324
341325With `Bash` enabled, try: `"Write unit tests for utils.py, run them, and fix any failures"`
342326
No line in this hunk matches that.