[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-11685":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":8,"htmlUrl":9,"language":10,"languages":8,"totalLinesOfCode":8,"stars":11,"forks":12,"watchers":13,"openIssues":14,"contributorsCount":8,"subscribersCount":15,"size":15,"stars1d":16,"stars7d":17,"stars30d":18,"stars90d":15,"forks30d":15,"starsTrendScore":19,"compositeScore":20,"rankGlobal":8,"rankLanguage":8,"license":8,"archived":21,"fork":21,"defaultBranch":22,"hasWiki":21,"hasPages":21,"topics":8,"createdAt":8,"pushedAt":8,"updatedAt":23,"readmeContent":24,"aiSummary":25,"trendingCount":15,"starSnapshotCount":15,"syncStatus":26,"lastSyncTime":27,"discoverSource":28},11685,"claude-agent-sdk-python","anthropics\u002Fclaude-agent-sdk-python","anthropics",null,"https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-agent-sdk-python","Python",7262,1084,63,141,0,53,135,450,159,109.11,false,"main","2026-06-12 04:00:55","# Claude Agent SDK for Python\n\nPython SDK for Claude Agent. See the [Claude Agent SDK documentation](https:\u002F\u002Fplatform.claude.com\u002Fdocs\u002Fen\u002Fagent-sdk\u002Fpython) for more information.\n\n## Installation\n\n```bash\npip install claude-agent-sdk\n```\n\n**Prerequisites:**\n\n- Python 3.10+\n\n**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:\n\n- Install Claude Code separately: `curl -fsSL https:\u002F\u002Fclaude.ai\u002Finstall.sh | bash`\n- Specify a custom path: `ClaudeAgentOptions(cli_path=\"\u002Fpath\u002Fto\u002Fclaude\")`\n\n## Quick Start\n\n```python\nimport anyio\nfrom claude_agent_sdk import query\n\nasync def main():\n    async for message in query(prompt=\"What is 2 + 2?\"):\n        print(message)\n\nanyio.run(main)\n```\n\n## Basic Usage: query()\n\n`query()` is an async function for querying Claude Code. It returns an `AsyncIterator` of response messages. See [src\u002Fclaude_agent_sdk\u002Fquery.py](src\u002Fclaude_agent_sdk\u002Fquery.py).\n\n```python\nfrom claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, TextBlock\n\n# Simple query\nasync for message in query(prompt=\"Hello Claude\"):\n    if isinstance(message, AssistantMessage):\n        for block in message.content:\n            if isinstance(block, TextBlock):\n                print(block.text)\n\n# With options\noptions = ClaudeAgentOptions(\n    system_prompt=\"You are a helpful assistant\",\n    max_turns=1\n)\n\nasync for message in query(prompt=\"Tell me a joke\", options=options):\n    print(message)\n```\n\n### Using Tools\n\nBy default, Claude has access to the full [Claude Code toolset](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsettings#tools-available-to-claude) (Read, Write, Edit, Bash, and others). `allowed_tools` is a permission allowlist: listed tools are auto-approved, and unlisted tools fall through to `permission_mode` and `can_use_tool` for a decision. It does not remove tools from Claude's toolset. To block specific tools, use `disallowed_tools`. See the [permissions guide](https:\u002F\u002Fplatform.claude.com\u002Fdocs\u002Fen\u002Fagent-sdk\u002Fpermissions) for the full evaluation order.\n\n```python\noptions = ClaudeAgentOptions(\n    allowed_tools=[\"Read\", \"Write\", \"Bash\"],  # auto-approve these tools\n    permission_mode='acceptEdits'  # auto-accept file edits\n)\n\nasync for message in query(\n    prompt=\"Create a hello.py file\",\n    options=options\n):\n    # Process tool use and results\n    pass\n```\n\n### Working Directory\n\n```python\nfrom pathlib import Path\n\noptions = ClaudeAgentOptions(\n    cwd=\"\u002Fpath\u002Fto\u002Fproject\"  # or Path(\"\u002Fpath\u002Fto\u002Fproject\")\n)\n```\n\n## ClaudeSDKClient\n\n`ClaudeSDKClient` supports bidirectional, interactive conversations with Claude\nCode. See [src\u002Fclaude_agent_sdk\u002Fclient.py](src\u002Fclaude_agent_sdk\u002Fclient.py).\n\nUnlike `query()`, `ClaudeSDKClient` additionally enables **custom tools** and **hooks**, both of which can be defined as Python functions.\n\n### Custom Tools (as In-Process SDK MCP Servers)\n\nA **custom tool** is a Python function that you can offer to Claude, for Claude to invoke as needed.\n\nCustom 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.\n\nFor an end-to-end example, see [MCP Calculator](examples\u002Fmcp_calculator.py).\n\n#### Creating a Simple Tool\n\n```python\nfrom claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions, ClaudeSDKClient\n\n# Define a tool using the @tool decorator\n@tool(\"greet\", \"Greet a user\", {\"name\": str})\nasync def greet_user(args):\n    return {\n        \"content\": [\n            {\"type\": \"text\", \"text\": f\"Hello, {args['name']}!\"}\n        ]\n    }\n\n# Create an SDK MCP server\nserver = create_sdk_mcp_server(\n    name=\"my-tools\",\n    version=\"1.0.0\",\n    tools=[greet_user]\n)\n\n# Use it with Claude. allowed_tools pre-approves the tool so it runs\n# without a permission prompt; it does not control tool availability.\noptions = ClaudeAgentOptions(\n    mcp_servers={\"tools\": server},\n    allowed_tools=[\"mcp__tools__greet\"]\n)\n\nasync with ClaudeSDKClient(options=options) as client:\n    await client.query(\"Greet Alice\")\n\n    # Extract and print response\n    async for msg in client.receive_response():\n        print(msg)\n```\n\n#### Benefits Over External MCP Servers\n\n- **No subprocess management** - Runs in the same process as your application\n- **Better performance** - No IPC overhead for tool calls\n- **Simpler deployment** - Single Python process instead of multiple\n- **Easier debugging** - All code runs in the same process\n- **Type safety** - Direct Python function calls with type hints\n\n#### Migration from External Servers\n\n```python\n# BEFORE: External MCP server (separate process)\noptions = ClaudeAgentOptions(\n    mcp_servers={\n        \"calculator\": {\n            \"type\": \"stdio\",\n            \"command\": \"python\",\n            \"args\": [\"-m\", \"calculator_server\"]\n        }\n    }\n)\n\n# AFTER: SDK MCP server (in-process)\nfrom my_tools import add, subtract  # Your tool functions\n\ncalculator = create_sdk_mcp_server(\n    name=\"calculator\",\n    tools=[add, subtract]\n)\n\noptions = ClaudeAgentOptions(\n    mcp_servers={\"calculator\": calculator}\n)\n```\n\n#### Mixed Server Support\n\nYou can use both SDK and external MCP servers together:\n\n```python\noptions = ClaudeAgentOptions(\n    mcp_servers={\n        \"internal\": sdk_server,      # In-process SDK server\n        \"external\": {                # External subprocess server\n            \"type\": \"stdio\",\n            \"command\": \"external-server\"\n        }\n    }\n)\n```\n\n### Hooks\n\nA **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 [Intercept and control agent behavior with hooks](https:\u002F\u002Fplatform.claude.com\u002Fdocs\u002Fen\u002Fagent-sdk\u002Fhooks).\n\nFor more examples, see examples\u002Fhooks.py.\n\n#### Example\n\n```python\nfrom claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient, HookMatcher\n\nasync def check_bash_command(input_data, tool_use_id, context):\n    tool_name = input_data[\"tool_name\"]\n    tool_input = input_data[\"tool_input\"]\n    if tool_name != \"Bash\":\n        return {}\n    command = tool_input.get(\"command\", \"\")\n    block_patterns = [\"foo.sh\"]\n    for pattern in block_patterns:\n        if pattern in command:\n            return {\n                \"hookSpecificOutput\": {\n                    \"hookEventName\": \"PreToolUse\",\n                    \"permissionDecision\": \"deny\",\n                    \"permissionDecisionReason\": f\"Command contains invalid pattern: {pattern}\",\n                }\n            }\n    return {}\n\noptions = ClaudeAgentOptions(\n    allowed_tools=[\"Bash\"],\n    hooks={\n        \"PreToolUse\": [\n            HookMatcher(matcher=\"Bash\", hooks=[check_bash_command]),\n        ],\n    }\n)\n\nasync with ClaudeSDKClient(options=options) as client:\n    # Test 1: Command with forbidden pattern (will be blocked)\n    await client.query(\"Run the bash command: .\u002Ffoo.sh --help\")\n    async for msg in client.receive_response():\n        print(msg)\n\n    print(\"\\n\" + \"=\" * 50 + \"\\n\")\n\n    # Test 2: Safe command that should work\n    await client.query(\"Run the bash command: echo 'Hello from hooks example!'\")\n    async for msg in client.receive_response():\n        print(msg)\n```\n\n## Types\n\nSee [src\u002Fclaude_agent_sdk\u002Ftypes.py](src\u002Fclaude_agent_sdk\u002Ftypes.py) for complete type definitions:\n\n- `ClaudeAgentOptions` - Configuration options\n- `AssistantMessage`, `UserMessage`, `SystemMessage`, `ResultMessage` - Message types\n- `TextBlock`, `ToolUseBlock`, `ToolResultBlock` - Content blocks\n\n## Error Handling\n\n```python\nfrom claude_agent_sdk import (\n    ClaudeSDKError,      # Base error\n    CLINotFoundError,    # Claude Code not installed\n    CLIConnectionError,  # Connection issues\n    ProcessError,        # Process failed\n    CLIJSONDecodeError,  # JSON parsing issues\n)\n\ntry:\n    async for message in query(prompt=\"Hello\"):\n        pass\nexcept CLINotFoundError:\n    print(\"Please install Claude Code\")\nexcept ProcessError as e:\n    print(f\"Process failed with exit code: {e.exit_code}\")\nexcept CLIJSONDecodeError as e:\n    print(f\"Failed to parse response: {e}\")\n```\n\nSee [src\u002Fclaude_agent_sdk\u002F\\_errors.py](src\u002Fclaude_agent_sdk\u002F_errors.py) for all error types.\n\n## Available Tools\n\nSee the [Claude Code documentation](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsettings#tools-available-to-claude) for a complete list of available tools.\n\n## Examples\n\nSee [examples\u002Fquick_start.py](examples\u002Fquick_start.py) for a complete working example.\n\nSee [examples\u002Fstreaming_mode.py](examples\u002Fstreaming_mode.py) for comprehensive examples involving `ClaudeSDKClient`. You can even run interactive examples in IPython from [examples\u002Fstreaming_mode_ipython.py](examples\u002Fstreaming_mode_ipython.py).\n\n## Migrating from Claude Code SDK\n\nIf you're upgrading from the Claude Code SDK (versions \u003C 0.1.0), please see the [CHANGELOG.md](CHANGELOG.md#010) for details on breaking changes and new features, including:\n\n- `ClaudeCodeOptions` → `ClaudeAgentOptions` rename\n- Merged system prompt configuration\n- Settings isolation and explicit control\n- New programmatic subagents and session forking features\n\n## Development\n\nIf you're contributing to this project, run the initial setup script to install git hooks:\n\n```bash\n.\u002Fscripts\u002Finitial-setup.sh\n```\n\nThis 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`.\n\n### Building Wheels Locally\n\nTo build wheels with the bundled Claude Code CLI:\n\n```bash\n# Install build dependencies\npip install build twine\n\n# Build wheel with bundled CLI\npython scripts\u002Fbuild_wheel.py\n\n# Build with specific version\npython scripts\u002Fbuild_wheel.py --version 0.1.4\n\n# Build with specific CLI version\npython scripts\u002Fbuild_wheel.py --cli-version 2.0.0\n\n# Clean bundled CLI after building\npython scripts\u002Fbuild_wheel.py --clean\n\n# Skip CLI download (use existing)\npython scripts\u002Fbuild_wheel.py --skip-download\n```\n\nThe build script:\n\n1. Downloads Claude Code CLI for your platform\n2. Bundles it in the wheel\n3. Builds both wheel and source distribution\n4. Checks the package with twine\n\nSee `python scripts\u002Fbuild_wheel.py --help` for all options.\n\n### Release Workflow\n\nThe package is published to PyPI via the GitHub Actions workflow in `.github\u002Fworkflows\u002Fpublish.yml`. To create a new release:\n\n1. **Trigger the workflow** manually from the Actions tab with two inputs:\n   - `version`: The package version to publish (e.g., `0.1.5`)\n   - `claude_code_version`: The Claude Code CLI version to bundle (e.g., `2.0.0` or `latest`)\n\n2. **The workflow will**:\n   - Build platform-specific wheels for macOS, Linux, and Windows\n   - Bundle the specified Claude Code CLI version in each wheel\n   - Build a source distribution\n   - Publish all artifacts to PyPI\n   - Create a release branch with version updates\n   - Open a PR to main with:\n     - Updated `pyproject.toml` version\n     - Updated `src\u002Fclaude_agent_sdk\u002F_version.py`\n     - Updated `src\u002Fclaude_agent_sdk\u002F_cli_version.py` with bundled CLI version\n     - Auto-generated `CHANGELOG.md` entry\n\n3. **Review and merge** the release PR to update main with the new version information\n\nThe 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.\n\n## License and terms\n\nUse of this SDK is governed by Anthropic's [Commercial Terms of Service](https:\u002F\u002Fwww.anthropic.com\u002Flegal\u002Fcommercial-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.\n","这个项目是Claude Agent的Python SDK，用于与Claude Code进行交互。核心功能包括异步查询接口`query()`和双向交互客户端`ClaudeSDKClient`，支持自定义工具和钩子函数。该SDK自动捆绑了Claude Code CLI，简化了安装流程，并允许用户通过设置工作目录、系统提示等选项来定制Claude的行为。它还提供了详细的权限控制机制，如允许或禁止特定工具的使用。适用于需要集成高级AI助手能力的应用场景，比如自动化脚本编写、代码审查以及基于自然语言处理的任务执行。",2,"2026-06-11 03:32:16","trending"]