claude-agent-sdk 0.1.17__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. claude_agent_sdk-0.1.17/.gitignore +51 -0
  2. claude_agent_sdk-0.1.17/LICENSE +21 -0
  3. claude_agent_sdk-0.1.17/PKG-INFO +389 -0
  4. claude_agent_sdk-0.1.17/README.md +356 -0
  5. claude_agent_sdk-0.1.17/pyproject.toml +109 -0
  6. claude_agent_sdk-0.1.17/src/claude_agent_sdk/__init__.py +365 -0
  7. claude_agent_sdk-0.1.17/src/claude_agent_sdk/_bundled/.gitignore +3 -0
  8. claude_agent_sdk-0.1.17/src/claude_agent_sdk/_cli_version.py +3 -0
  9. claude_agent_sdk-0.1.17/src/claude_agent_sdk/_errors.py +56 -0
  10. claude_agent_sdk-0.1.17/src/claude_agent_sdk/_internal/__init__.py +1 -0
  11. claude_agent_sdk-0.1.17/src/claude_agent_sdk/_internal/client.py +124 -0
  12. claude_agent_sdk-0.1.17/src/claude_agent_sdk/_internal/message_parser.py +177 -0
  13. claude_agent_sdk-0.1.17/src/claude_agent_sdk/_internal/query.py +621 -0
  14. claude_agent_sdk-0.1.17/src/claude_agent_sdk/_internal/transport/__init__.py +68 -0
  15. claude_agent_sdk-0.1.17/src/claude_agent_sdk/_internal/transport/subprocess_cli.py +672 -0
  16. claude_agent_sdk-0.1.17/src/claude_agent_sdk/_version.py +3 -0
  17. claude_agent_sdk-0.1.17/src/claude_agent_sdk/client.py +377 -0
  18. claude_agent_sdk-0.1.17/src/claude_agent_sdk/py.typed +0 -0
  19. claude_agent_sdk-0.1.17/src/claude_agent_sdk/query.py +126 -0
  20. claude_agent_sdk-0.1.17/src/claude_agent_sdk/types.py +754 -0
  21. claude_agent_sdk-0.1.17/tests/conftest.py +4 -0
  22. claude_agent_sdk-0.1.17/tests/test_changelog.py +85 -0
  23. claude_agent_sdk-0.1.17/tests/test_client.py +123 -0
  24. claude_agent_sdk-0.1.17/tests/test_errors.py +52 -0
  25. claude_agent_sdk-0.1.17/tests/test_integration.py +284 -0
  26. claude_agent_sdk-0.1.17/tests/test_message_parser.py +299 -0
  27. claude_agent_sdk-0.1.17/tests/test_sdk_mcp_integration.py +265 -0
  28. claude_agent_sdk-0.1.17/tests/test_streaming_client.py +835 -0
  29. claude_agent_sdk-0.1.17/tests/test_subprocess_buffering.py +329 -0
  30. claude_agent_sdk-0.1.17/tests/test_tool_callbacks.py +488 -0
  31. claude_agent_sdk-0.1.17/tests/test_transport.py +828 -0
  32. claude_agent_sdk-0.1.17/tests/test_types.py +151 -0
@@ -0,0 +1,51 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ develop-eggs/
9
+ dist/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ lib/
14
+ lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ *.egg-info/
20
+ .installed.cfg
21
+ *.egg
22
+ MANIFEST
23
+
24
+ # Virtual environments
25
+ venv/
26
+ ENV/
27
+ env/
28
+ .venv
29
+ uv.lock
30
+
31
+ # IDEs
32
+ .vscode/
33
+ .idea/
34
+ *.swp
35
+ *.swo
36
+ *~
37
+ **/.DS_Store
38
+
39
+ # Testing
40
+ .tox/
41
+ .coverage
42
+ .coverage.*
43
+ .cache
44
+ .pytest_cache/
45
+ htmlcov/
46
+
47
+ # Type checking
48
+ .mypy_cache/
49
+ .dmypy.json
50
+ dmypy.json
51
+ .pyre/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Anthropic, PBC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,389 @@
1
+ Metadata-Version: 2.4
2
+ Name: claude-agent-sdk
3
+ Version: 0.1.17
4
+ Summary: Python SDK for Claude Code
5
+ Project-URL: Homepage, https://github.com/anthropics/claude-agent-sdk-python
6
+ Project-URL: Documentation, https://docs.anthropic.com/en/docs/claude-code/sdk
7
+ Project-URL: Issues, https://github.com/anthropics/claude-agent-sdk-python/issues
8
+ Author-email: Anthropic <support@anthropic.com>
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: ai,anthropic,claude,sdk
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: anyio>=4.0.0
23
+ Requires-Dist: mcp>=0.1.0
24
+ Requires-Dist: typing-extensions>=4.0.0; python_version < '3.11'
25
+ Provides-Extra: dev
26
+ Requires-Dist: anyio[trio]>=4.0.0; extra == 'dev'
27
+ Requires-Dist: mypy>=1.0.0; extra == 'dev'
28
+ Requires-Dist: pytest-asyncio>=0.20.0; extra == 'dev'
29
+ Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
30
+ Requires-Dist: pytest>=7.0.0; extra == 'dev'
31
+ Requires-Dist: ruff>=0.1.0; extra == 'dev'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # Claude Agent SDK for Python
35
+
36
+ Python SDK for Claude Agent. See the [Claude Agent SDK documentation](https://docs.anthropic.com/en/docs/claude-code/sdk/sdk-python) for more information.
37
+
38
+ ## Installation
39
+
40
+ ```bash
41
+ pip install claude-agent-sdk
42
+ ```
43
+
44
+ **Prerequisites:**
45
+
46
+ - Python 3.10+
47
+
48
+ **Note:** The Claude Code CLI is automatically bundled with the package - no separate installation required! The SDK will use the bundled CLI by default. If you prefer to use a system-wide installation or a specific version, you can:
49
+
50
+ - Install Claude Code separately: `curl -fsSL https://claude.ai/install.sh | bash`
51
+ - Specify a custom path: `ClaudeAgentOptions(cli_path="/path/to/claude")`
52
+
53
+ ## Quick Start
54
+
55
+ ```python
56
+ import anyio
57
+ from claude_agent_sdk import query
58
+
59
+ async def main():
60
+ async for message in query(prompt="What is 2 + 2?"):
61
+ print(message)
62
+
63
+ anyio.run(main)
64
+ ```
65
+
66
+ ## Basic Usage: query()
67
+
68
+ `query()` is an async function for querying Claude Code. It returns an `AsyncIterator` of response messages. See [src/claude_agent_sdk/query.py](src/claude_agent_sdk/query.py).
69
+
70
+ ```python
71
+ from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, TextBlock
72
+
73
+ # Simple query
74
+ async for message in query(prompt="Hello Claude"):
75
+ if isinstance(message, AssistantMessage):
76
+ for block in message.content:
77
+ if isinstance(block, TextBlock):
78
+ print(block.text)
79
+
80
+ # With options
81
+ options = ClaudeAgentOptions(
82
+ system_prompt="You are a helpful assistant",
83
+ max_turns=1
84
+ )
85
+
86
+ async for message in query(prompt="Tell me a joke", options=options):
87
+ print(message)
88
+ ```
89
+
90
+ ### Using Tools
91
+
92
+ ```python
93
+ options = ClaudeAgentOptions(
94
+ allowed_tools=["Read", "Write", "Bash"],
95
+ permission_mode='acceptEdits' # auto-accept file edits
96
+ )
97
+
98
+ async for message in query(
99
+ prompt="Create a hello.py file",
100
+ options=options
101
+ ):
102
+ # Process tool use and results
103
+ pass
104
+ ```
105
+
106
+ ### Working Directory
107
+
108
+ ```python
109
+ from pathlib import Path
110
+
111
+ options = ClaudeAgentOptions(
112
+ cwd="/path/to/project" # or Path("/path/to/project")
113
+ )
114
+ ```
115
+
116
+ ## ClaudeSDKClient
117
+
118
+ `ClaudeSDKClient` supports bidirectional, interactive conversations with Claude
119
+ Code. See [src/claude_agent_sdk/client.py](src/claude_agent_sdk/client.py).
120
+
121
+ Unlike `query()`, `ClaudeSDKClient` additionally enables **custom tools** and **hooks**, both of which can be defined as Python functions.
122
+
123
+ ### Custom Tools (as In-Process SDK MCP Servers)
124
+
125
+ A **custom tool** is a Python function that you can offer to Claude, for Claude to invoke as needed.
126
+
127
+ Custom tools are implemented in-process MCP servers that run directly within your Python application, eliminating the need for separate processes that regular MCP servers require.
128
+
129
+ For an end-to-end example, see [MCP Calculator](examples/mcp_calculator.py).
130
+
131
+ #### Creating a Simple Tool
132
+
133
+ ```python
134
+ from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions, ClaudeSDKClient
135
+
136
+ # Define a tool using the @tool decorator
137
+ @tool("greet", "Greet a user", {"name": str})
138
+ async def greet_user(args):
139
+ return {
140
+ "content": [
141
+ {"type": "text", "text": f"Hello, {args['name']}!"}
142
+ ]
143
+ }
144
+
145
+ # Create an SDK MCP server
146
+ server = create_sdk_mcp_server(
147
+ name="my-tools",
148
+ version="1.0.0",
149
+ tools=[greet_user]
150
+ )
151
+
152
+ # Use it with Claude
153
+ options = ClaudeAgentOptions(
154
+ mcp_servers={"tools": server},
155
+ allowed_tools=["mcp__tools__greet"]
156
+ )
157
+
158
+ async with ClaudeSDKClient(options=options) as client:
159
+ await client.query("Greet Alice")
160
+
161
+ # Extract and print response
162
+ async for msg in client.receive_response():
163
+ print(msg)
164
+ ```
165
+
166
+ #### Benefits Over External MCP Servers
167
+
168
+ - **No subprocess management** - Runs in the same process as your application
169
+ - **Better performance** - No IPC overhead for tool calls
170
+ - **Simpler deployment** - Single Python process instead of multiple
171
+ - **Easier debugging** - All code runs in the same process
172
+ - **Type safety** - Direct Python function calls with type hints
173
+
174
+ #### Migration from External Servers
175
+
176
+ ```python
177
+ # BEFORE: External MCP server (separate process)
178
+ options = ClaudeAgentOptions(
179
+ mcp_servers={
180
+ "calculator": {
181
+ "type": "stdio",
182
+ "command": "python",
183
+ "args": ["-m", "calculator_server"]
184
+ }
185
+ }
186
+ )
187
+
188
+ # AFTER: SDK MCP server (in-process)
189
+ from my_tools import add, subtract # Your tool functions
190
+
191
+ calculator = create_sdk_mcp_server(
192
+ name="calculator",
193
+ tools=[add, subtract]
194
+ )
195
+
196
+ options = ClaudeAgentOptions(
197
+ mcp_servers={"calculator": calculator}
198
+ )
199
+ ```
200
+
201
+ #### Mixed Server Support
202
+
203
+ You can use both SDK and external MCP servers together:
204
+
205
+ ```python
206
+ options = ClaudeAgentOptions(
207
+ mcp_servers={
208
+ "internal": sdk_server, # In-process SDK server
209
+ "external": { # External subprocess server
210
+ "type": "stdio",
211
+ "command": "external-server"
212
+ }
213
+ }
214
+ )
215
+ ```
216
+
217
+ ### Hooks
218
+
219
+ A **hook** is a Python function that the Claude Code _application_ (_not_ Claude) invokes at specific points of the Claude agent loop. Hooks can provide deterministic processing and automated feedback for Claude. Read more in [Claude Code Hooks Reference](https://docs.anthropic.com/en/docs/claude-code/hooks).
220
+
221
+ For more examples, see examples/hooks.py.
222
+
223
+ #### Example
224
+
225
+ ```python
226
+ from claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient, HookMatcher
227
+
228
+ async def check_bash_command(input_data, tool_use_id, context):
229
+ tool_name = input_data["tool_name"]
230
+ tool_input = input_data["tool_input"]
231
+ if tool_name != "Bash":
232
+ return {}
233
+ command = tool_input.get("command", "")
234
+ block_patterns = ["foo.sh"]
235
+ for pattern in block_patterns:
236
+ if pattern in command:
237
+ return {
238
+ "hookSpecificOutput": {
239
+ "hookEventName": "PreToolUse",
240
+ "permissionDecision": "deny",
241
+ "permissionDecisionReason": f"Command contains invalid pattern: {pattern}",
242
+ }
243
+ }
244
+ return {}
245
+
246
+ options = ClaudeAgentOptions(
247
+ allowed_tools=["Bash"],
248
+ hooks={
249
+ "PreToolUse": [
250
+ HookMatcher(matcher="Bash", hooks=[check_bash_command]),
251
+ ],
252
+ }
253
+ )
254
+
255
+ async with ClaudeSDKClient(options=options) as client:
256
+ # Test 1: Command with forbidden pattern (will be blocked)
257
+ await client.query("Run the bash command: ./foo.sh --help")
258
+ async for msg in client.receive_response():
259
+ print(msg)
260
+
261
+ print("\n" + "=" * 50 + "\n")
262
+
263
+ # Test 2: Safe command that should work
264
+ await client.query("Run the bash command: echo 'Hello from hooks example!'")
265
+ async for msg in client.receive_response():
266
+ print(msg)
267
+ ```
268
+
269
+ ## Types
270
+
271
+ See [src/claude_agent_sdk/types.py](src/claude_agent_sdk/types.py) for complete type definitions:
272
+
273
+ - `ClaudeAgentOptions` - Configuration options
274
+ - `AssistantMessage`, `UserMessage`, `SystemMessage`, `ResultMessage` - Message types
275
+ - `TextBlock`, `ToolUseBlock`, `ToolResultBlock` - Content blocks
276
+
277
+ ## Error Handling
278
+
279
+ ```python
280
+ from claude_agent_sdk import (
281
+ ClaudeSDKError, # Base error
282
+ CLINotFoundError, # Claude Code not installed
283
+ CLIConnectionError, # Connection issues
284
+ ProcessError, # Process failed
285
+ CLIJSONDecodeError, # JSON parsing issues
286
+ )
287
+
288
+ try:
289
+ async for message in query(prompt="Hello"):
290
+ pass
291
+ except CLINotFoundError:
292
+ print("Please install Claude Code")
293
+ except ProcessError as e:
294
+ print(f"Process failed with exit code: {e.exit_code}")
295
+ except CLIJSONDecodeError as e:
296
+ print(f"Failed to parse response: {e}")
297
+ ```
298
+
299
+ See [src/claude_agent_sdk/\_errors.py](src/claude_agent_sdk/_errors.py) for all error types.
300
+
301
+ ## Available Tools
302
+
303
+ See the [Claude Code documentation](https://docs.anthropic.com/en/docs/claude-code/settings#tools-available-to-claude) for a complete list of available tools.
304
+
305
+ ## Examples
306
+
307
+ See [examples/quick_start.py](examples/quick_start.py) for a complete working example.
308
+
309
+ See [examples/streaming_mode.py](examples/streaming_mode.py) for comprehensive examples involving `ClaudeSDKClient`. You can even run interactive examples in IPython from [examples/streaming_mode_ipython.py](examples/streaming_mode_ipython.py).
310
+
311
+ ## Migrating from Claude Code SDK
312
+
313
+ If you're upgrading from the Claude Code SDK (versions < 0.1.0), please see the [CHANGELOG.md](CHANGELOG.md#010) for details on breaking changes and new features, including:
314
+
315
+ - `ClaudeCodeOptions` → `ClaudeAgentOptions` rename
316
+ - Merged system prompt configuration
317
+ - Settings isolation and explicit control
318
+ - New programmatic subagents and session forking features
319
+
320
+ ## Development
321
+
322
+ If you're contributing to this project, run the initial setup script to install git hooks:
323
+
324
+ ```bash
325
+ ./scripts/initial-setup.sh
326
+ ```
327
+
328
+ This installs a pre-push hook that runs lint checks before pushing, matching the CI workflow. To skip the hook temporarily, use `git push --no-verify`.
329
+
330
+ ### Building Wheels Locally
331
+
332
+ To build wheels with the bundled Claude Code CLI:
333
+
334
+ ```bash
335
+ # Install build dependencies
336
+ pip install build twine
337
+
338
+ # Build wheel with bundled CLI
339
+ python scripts/build_wheel.py
340
+
341
+ # Build with specific version
342
+ python scripts/build_wheel.py --version 0.1.4
343
+
344
+ # Build with specific CLI version
345
+ python scripts/build_wheel.py --cli-version 2.0.0
346
+
347
+ # Clean bundled CLI after building
348
+ python scripts/build_wheel.py --clean
349
+
350
+ # Skip CLI download (use existing)
351
+ python scripts/build_wheel.py --skip-download
352
+ ```
353
+
354
+ The build script:
355
+
356
+ 1. Downloads Claude Code CLI for your platform
357
+ 2. Bundles it in the wheel
358
+ 3. Builds both wheel and source distribution
359
+ 4. Checks the package with twine
360
+
361
+ See `python scripts/build_wheel.py --help` for all options.
362
+
363
+ ### Release Workflow
364
+
365
+ The package is published to PyPI via the GitHub Actions workflow in `.github/workflows/publish.yml`. To create a new release:
366
+
367
+ 1. **Trigger the workflow** manually from the Actions tab with two inputs:
368
+ - `version`: The package version to publish (e.g., `0.1.5`)
369
+ - `claude_code_version`: The Claude Code CLI version to bundle (e.g., `2.0.0` or `latest`)
370
+
371
+ 2. **The workflow will**:
372
+ - Build platform-specific wheels for macOS, Linux, and Windows
373
+ - Bundle the specified Claude Code CLI version in each wheel
374
+ - Build a source distribution
375
+ - Publish all artifacts to PyPI
376
+ - Create a release branch with version updates
377
+ - Open a PR to main with:
378
+ - Updated `pyproject.toml` version
379
+ - Updated `src/claude_agent_sdk/_version.py`
380
+ - Updated `src/claude_agent_sdk/_cli_version.py` with bundled CLI version
381
+ - Auto-generated `CHANGELOG.md` entry
382
+
383
+ 3. **Review and merge** the release PR to update main with the new version information
384
+
385
+ The workflow tracks both the package version and the bundled CLI version separately, allowing you to release a new package version with an updated CLI without code changes.
386
+
387
+ ## License and terms
388
+
389
+ Use of this SDK is governed by Anthropic's [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms), including when you use it to power products and services that you make available to your own customers and end users, except to the extent a specific component or dependency is covered by a different license as indicated in that component's LICENSE file.