{"id":35553903,"url":"https://github.com/severity1/claude-agent-sdk-go","last_synced_at":"2026-01-23T00:34:58.072Z","repository":{"id":311393257,"uuid":"1043063040","full_name":"severity1/claude-agent-sdk-go","owner":"severity1","description":"Unofficial Go SDK for Claude Code CLI integration. See the Claude Agent SDK documentation for more information. This project has been renamed from claude-code-sdk-go.","archived":false,"fork":false,"pushed_at":"2026-01-10T08:21:31.000Z","size":1333,"stargazers_count":52,"open_issues_count":2,"forks_count":9,"subscribers_count":2,"default_branch":"main","last_synced_at":"2026-01-13T19:44:54.747Z","etag":null,"topics":["agentic-ai","ai","ai-agents","anthropic","claude","claude-code","developer-tools","go","golang","sdk","sdk-go"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/severity1.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-08-23T04:18:56.000Z","updated_at":"2026-01-13T03:07:46.000Z","dependencies_parsed_at":"2025-09-20T10:21:34.566Z","dependency_job_id":null,"html_url":"https://github.com/severity1/claude-agent-sdk-go","commit_stats":null,"previous_names":["severity1/claude-code-sdk-go","severity1/claude-agent-sdk-go"],"tags_count":28,"template":false,"template_full_name":null,"purl":"pkg:github/severity1/claude-agent-sdk-go","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/severity1%2Fclaude-agent-sdk-go","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/severity1%2Fclaude-agent-sdk-go/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/severity1%2Fclaude-agent-sdk-go/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/severity1%2Fclaude-agent-sdk-go/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/severity1","download_url":"https://codeload.github.com/severity1/claude-agent-sdk-go/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/severity1%2Fclaude-agent-sdk-go/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28676145,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-22T20:48:19.482Z","status":"ssl_error","status_checked_at":"2026-01-22T20:48:14.968Z","response_time":144,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agentic-ai","ai","ai-agents","anthropic","claude","claude-code","developer-tools","go","golang","sdk","sdk-go"],"created_at":"2026-01-04T08:13:48.860Z","updated_at":"2026-01-23T00:34:58.067Z","avatar_url":"https://github.com/severity1.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Claude Agent SDK for Go\n\n\u003cdiv align=\"center\"\u003e\n  \u003cimg src=\"gopher.png\" alt=\"Go Gopher\" width=\"200\"/\u003e\n\u003c/div\u003e\n\n\u003cdiv align=\"center\"\u003e\n\n[![CI](https://github.com/severity1/claude-agent-sdk-go/actions/workflows/ci.yml/badge.svg)](https://github.com/severity1/claude-agent-sdk-go/actions/workflows/ci.yml)\n[![Go Reference](https://pkg.go.dev/badge/github.com/severity1/claude-agent-sdk-go.svg)](https://pkg.go.dev/github.com/severity1/claude-agent-sdk-go)\n[![Go Report Card](https://goreportcard.com/badge/github.com/severity1/claude-agent-sdk-go)](https://goreportcard.com/report/github.com/severity1/claude-agent-sdk-go)\n[![codecov](https://codecov.io/gh/severity1/claude-agent-sdk-go/branch/main/graph/badge.svg)](https://codecov.io/gh/severity1/claude-agent-sdk-go)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\n\u003c/div\u003e\n\nUnofficial Go SDK for Claude Code CLI integration. Build production-ready applications that leverage Claude's advanced code understanding, secure file operations, and external tool integrations through a clean, idiomatic Go API with comprehensive error handling and automatic resource management.\n\n**Two powerful APIs for different use cases:**\n- **Query API**: One-shot operations, automation, CI/CD integration  \n- **Client API**: Interactive conversations, multi-turn workflows, streaming responses\n- **WithClient**: Go-idiomatic context manager for automatic resource management\n\n![Claude Agent SDK in Action](cc-sdk-go-in-action-v2.gif)\n\n## Installation\n\n```bash\ngo get github.com/severity1/claude-agent-sdk-go\n```\n\n**Prerequisites:** Go 1.18+, Node.js, Claude Code (`npm install -g @anthropic-ai/claude-code`)\n\n## Key Features\n\n**Two APIs for different needs** - Query for automation, Client for interaction\n**100% Python SDK compatibility** - Same functionality, Go-native design\n**Automatic resource management** - WithClient provides Go-idiomatic context manager pattern\n**Session management** - Isolated conversation contexts with `Query()` and `QueryWithSession()`\n**Built-in tool integration** - File operations, AWS, GitHub, databases, and more\n**Production ready** - Comprehensive error handling, timeouts, resource cleanup\n**Security focused** - Granular tool permissions and access controls\n**Context-aware** - Maintain conversation state across multiple interactions\n**Advanced capabilities** - Permission callbacks, lifecycle hooks, file checkpointing\n\n## Usage\n\n### Query API - One-Shot Operations\nBest for automation, scripting, and tasks with clear completion criteria:\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"errors\"\n    \"fmt\"\n    \"log\"\n\n    \"github.com/severity1/claude-agent-sdk-go\"\n)\n\nfunc main() {\n    fmt.Println(\"Claude Agent SDK - Query API Example\")\n    fmt.Println(\"Asking: What is 2+2?\")\n\n    ctx := context.Background()\n\n    // Create and execute query\n    iterator, err := claudecode.Query(ctx, \"What is 2+2?\")\n    if err != nil {\n        // Use error type helpers for specific error handling\n        if cliErr := claudecode.AsCLINotFoundError(err); cliErr != nil {\n            fmt.Printf(\"Claude CLI not found: %v\\n\", cliErr)\n            fmt.Println(\"Install with: npm install -g @anthropic-ai/claude-code\")\n            return\n        }\n        if connErr := claudecode.AsConnectionError(err); connErr != nil {\n            fmt.Printf(\"Connection failed: %v\\n\", connErr)\n            return\n        }\n        log.Fatalf(\"Query failed: %v\", err)\n    }\n    defer iterator.Close()\n\n    fmt.Println(\"\\nResponse:\")\n\n    // Iterate through messages\n    for {\n        message, err := iterator.Next(ctx)\n        if err != nil {\n            if errors.Is(err, claudecode.ErrNoMoreMessages) {\n                break\n            }\n            log.Fatalf(\"Failed to get message: %v\", err)\n        }\n\n        if message == nil {\n            break\n        }\n\n        // Handle different message types\n        switch msg := message.(type) {\n        case *claudecode.AssistantMessage:\n            for _, block := range msg.Content {\n                if textBlock, ok := block.(*claudecode.TextBlock); ok {\n                    fmt.Print(textBlock.Text)\n                }\n            }\n        case *claudecode.ResultMessage:\n            if msg.IsError {\n                if msg.Result != nil {\n                    log.Printf(\"Error: %s\", *msg.Result)\n                } else {\n                    log.Printf(\"Error: unknown error\")\n                }\n            }\n        }\n    }\n\n    fmt.Println(\"\\nQuery completed!\")\n}\n```\n\n### Client API - Interactive \u0026 Multi-Turn\n**WithClient provides automatic resource management (equivalent to Python's `async with`):**\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"log\"\n\n    \"github.com/severity1/claude-agent-sdk-go\"\n)\n\nfunc main() {\n    fmt.Println(\"Claude Agent SDK - Client Streaming Example\")\n    fmt.Println(\"Asking: Explain Go goroutines with a simple example\")\n\n    ctx := context.Background()\n    question := \"Explain what Go goroutines are and show a simple example\"\n\n    // WithClient handles connection lifecycle automatically\n    err := claudecode.WithClient(ctx, func(client claudecode.Client) error {\n        fmt.Println(\"\\nConnected! Streaming response:\")\n\n        // Simple query uses default session\n        if err := client.Query(ctx, question); err != nil {\n            return fmt.Errorf(\"query failed: %w\", err)\n        }\n\n        // Stream messages in real-time\n        msgChan := client.ReceiveMessages(ctx)\n        for {\n            select {\n            case message := \u003c-msgChan:\n                if message == nil {\n                    return nil // Stream ended\n                }\n\n                switch msg := message.(type) {\n                case *claudecode.AssistantMessage:\n                    // Print streaming text as it arrives\n                    for _, block := range msg.Content {\n                        if textBlock, ok := block.(*claudecode.TextBlock); ok {\n                            fmt.Print(textBlock.Text)\n                        }\n                    }\n                case *claudecode.ResultMessage:\n                    if msg.IsError {\n                        if msg.Result != nil {\n                            return fmt.Errorf(\"error: %s\", *msg.Result)\n                        }\n                        return fmt.Errorf(\"error: unknown error\")\n                    }\n                    return nil // Success, stream complete\n                }\n            case \u003c-ctx.Done():\n                return ctx.Err()\n            }\n        }\n    })\n\n    if err != nil {\n        log.Fatalf(\"Streaming failed: %v\", err)\n    }\n\n    fmt.Println(\"\\n\\nStreaming completed!\")\n}\n```\n\n### Session Management\n\n**Maintain conversation context across multiple queries with session management:**\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"log\"\n\n    \"github.com/severity1/claude-agent-sdk-go\"\n)\n\nfunc main() {\n    fmt.Println(\"Claude Agent SDK - Session Management Example\")\n\n    ctx := context.Background()\n\n    err := claudecode.WithClient(ctx, func(client claudecode.Client) error {\n        fmt.Println(\"\\nDemonstrating isolated sessions:\")\n\n        // Session A: Math conversation\n        sessionA := \"math-session\"\n        if err := client.QueryWithSession(ctx, \"Remember this: x = 5\", sessionA); err != nil {\n            return err\n        }\n\n        // Session B: Programming conversation\n        sessionB := \"programming-session\"\n        if err := client.QueryWithSession(ctx, \"Remember this: language = Go\", sessionB); err != nil {\n            return err\n        }\n\n        // Query each session - they maintain separate contexts\n        fmt.Println(\"\\nQuerying math session:\")\n        if err := client.QueryWithSession(ctx, \"What is x * 2?\", sessionA); err != nil {\n            return err\n        }\n\n        fmt.Println(\"\\nQuerying programming session:\")\n        if err := client.QueryWithSession(ctx, \"What language did I mention?\", sessionB); err != nil {\n            return err\n        }\n\n        // Default session query (separate from above)\n        fmt.Println(\"\\nDefault session (no context from above):\")\n        return client.Query(ctx, \"What did I just ask about?\") // Won't know about x or Go\n    })\n\n    if err != nil {\n        log.Fatalf(\"Session demo failed: %v\", err)\n    }\n\n    fmt.Println(\"Session management demo completed!\")\n}\n```\n\n**Traditional Client API (still supported):**\n\n\u003cdetails\u003e\n\u003csummary\u003eClick to see manual resource management approach\u003c/summary\u003e\n\n```go\nfunc traditionalClientExample() {\n    ctx := context.Background()\n    \n    client := claudecode.NewClient()\n    if err := client.Connect(ctx); err != nil {\n        log.Fatalf(\"Failed to connect: %v\", err)\n    }\n    defer client.Disconnect() // Manual cleanup required\n    \n    // Use client...\n}\n```\n\u003c/details\u003e\n\n## Tool Integration \u0026 External Services\n\nIntegrate with file systems, cloud services, databases, and development tools:\n\n**Core Tools** (built-in file operations):\n```go\n// File analysis and documentation generation\nclaudecode.Query(ctx, \"Read all Go files and create API documentation\",\n    claudecode.WithAllowedTools(\"Read\", \"Write\"))\n```\n\n**MCP Tools** (external service integrations):\n```go\n// AWS infrastructure automation\nclaudecode.Query(ctx, \"List my S3 buckets and analyze their security settings\",\n    claudecode.WithAllowedTools(\"mcp__aws-api-mcp__call_aws\", \"mcp__aws-api-mcp__suggest_aws_commands\", \"Write\"))\n```\n\n## Configuration Options\n\nCustomize Claude's behavior with functional options:\n\n**Tool \u0026 Permission Control:**\n```go\nclaudecode.Query(ctx, prompt,\n    claudecode.WithAllowedTools(\"Read\", \"Write\"),\n    claudecode.WithPermissionMode(claudecode.PermissionModeAcceptEdits))\n```\n\n**System Behavior:**\n```go\nclaudecode.Query(ctx, prompt,\n    claudecode.WithSystemPrompt(\"You are a senior Go developer\"),\n    claudecode.WithModel(\"claude-sonnet-4-5\"),\n    claudecode.WithMaxTurns(10))\n```\n\n**Environment Variables** (new in v0.2.5):\n```go\n// Proxy configuration\nclaudecode.NewClient(\n    claudecode.WithEnv(map[string]string{\n        \"HTTP_PROXY\":  \"http://proxy.example.com:8080\",\n        \"HTTPS_PROXY\": \"http://proxy.example.com:8080\",\n    }))\n\n// Individual variables\nclaudecode.NewClient(\n    claudecode.WithEnvVar(\"DEBUG\", \"1\"),\n    claudecode.WithEnvVar(\"CUSTOM_PATH\", \"/usr/local/bin\"))\n```\n\n**Context \u0026 Working Directory:**\n```go\nclaudecode.Query(ctx, prompt,\n    claudecode.WithCwd(\"/path/to/project\"),\n    claudecode.WithAddDirs(\"src\", \"docs\"))\n```\n\n**Session Management** (Client API):\n```go\n// WithClient provides isolated session contexts\nerr := claudecode.WithClient(ctx, func(client claudecode.Client) error {\n    // Default session\n    client.Query(ctx, \"Remember: x = 5\")\n\n    // Named session (isolated context)\n    return client.QueryWithSession(ctx, \"What is x?\", \"math-session\")\n})\n```\n\n**Programmatic Agents:**\n```go\n// Define custom agents for specialized tasks\nclaudecode.Query(ctx, \"Review this codebase for security issues\",\n    claudecode.WithAgent(\"security-reviewer\", claudecode.AgentDefinition{\n        Description: \"Reviews code for security vulnerabilities\",\n        Prompt:      \"You are a security expert focused on OWASP top 10...\",\n        Tools:       []string{\"Read\", \"Grep\", \"Glob\"},\n        Model:       claudecode.AgentModelSonnet,\n    }))\n\n// Multiple agents for complex workflows\nclaudecode.Query(ctx, \"Analyze and improve this code\",\n    claudecode.WithAgents(map[string]claudecode.AgentDefinition{\n        \"code-reviewer\": {\n            Description: \"Reviews code quality and best practices\",\n            Prompt:      \"You are a senior engineer focused on code quality...\",\n            Tools:       []string{\"Read\", \"Grep\"},\n            Model:       claudecode.AgentModelSonnet,\n        },\n        \"test-writer\": {\n            Description: \"Writes comprehensive unit tests\",\n            Prompt:      \"You are a testing expert...\",\n            Tools:       []string{\"Read\", \"Write\", \"Bash\"},\n            Model:       claudecode.AgentModelHaiku,\n        },\n    }))\n```\n\nAvailable agent models: `AgentModelSonnet`, `AgentModelOpus`, `AgentModelHaiku`, `AgentModelInherit`\n\n## Documentation\n\n- [Architecture](ARCHITECTURE.md) - System design and component overview\n- [Contributing](CONTRIBUTING.md) - Development setup and guidelines\n- [API Reference](docs/reference.md) - Complete SDK reference with all types, functions, and examples\n- [Python SDK Parity](docs/parity.md) - Feature comparison with the Python SDK\n- [pkg.go.dev](https://pkg.go.dev/github.com/severity1/claude-agent-sdk-go) - GoDoc reference\n\n## Advanced Features\n\nThe SDK includes advanced capabilities for production use:\n\n- **Permission Callbacks** - Programmatic tool access control ([Example 11](examples/11_permission_callback/))\n- **Lifecycle Hooks** - Intercept tool execution events ([Example 12](examples/12_hooks/))\n- **File Checkpointing** - Track and rewind file changes ([Example 13](examples/13_file_checkpointing/))\n- **SDK MCP Servers** - Create in-process custom tools ([Example 14](examples/14_sdk_mcp_server/))\n- **Stream Diagnostics** - Monitor stream health with `GetStreamIssues()` and `GetStreamStats()`\n\nSee the [examples directory](examples/README.md) for complete documentation.\n\n## When to Use Which API\n\n**Use Query API when you:**\n- Need one-shot automation or scripting\n- Have clear task completion criteria  \n- Want automatic resource cleanup\n- Are building CI/CD integrations\n- Prefer simple, stateless operations\n\n**Use Client API (WithClient) when you:**  \n- Need interactive conversations\n- Want to build context across multiple requests\n- Are creating complex, multi-step workflows\n- Need real-time streaming responses\n- Want to iterate and refine based on previous results\n- **Need automatic resource management (recommended)**\n\n## Examples\n\nSee [`examples/README.md`](examples/README.md) for detailed documentation.\n\n### Getting Started\n| Example | Description |\n|---------|-------------|\n| [`01_quickstart`](examples/01_quickstart/) | Query API fundamentals |\n| [`02_client_streaming`](examples/02_client_streaming/) | WithClient streaming basics |\n| [`03_client_multi_turn`](examples/03_client_multi_turn/) | Multi-turn conversations |\n\n### Tool Integration\n| Example | Description |\n|---------|-------------|\n| [`04_query_with_tools`](examples/04_query_with_tools/) | File operations with Query API |\n| [`05_client_with_tools`](examples/05_client_with_tools/) | Interactive file workflows |\n| [`06_query_with_mcp`](examples/06_query_with_mcp/) | External MCP server integration |\n| [`07_client_with_mcp`](examples/07_client_with_mcp/) | Multi-turn MCP workflows |\n\n### Production Patterns\n| Example | Description |\n|---------|-------------|\n| [`08_client_advanced`](examples/08_client_advanced/) | Error handling, model switching |\n| [`09_context_manager`](examples/09_context_manager/) | WithClient vs manual patterns |\n| [`10_session_management`](examples/10_session_management/) | Session isolation |\n\n### Security \u0026 Lifecycle\n| Example | Description |\n|---------|-------------|\n| [`11_permission_callback`](examples/11_permission_callback/) | Permission callbacks |\n| [`12_hooks`](examples/12_hooks/) | Lifecycle hooks |\n| [`13_file_checkpointing`](examples/13_file_checkpointing/) | File rewind capabilities |\n| [`14_sdk_mcp_server`](examples/14_sdk_mcp_server/) | In-process custom tools |\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fseverity1%2Fclaude-agent-sdk-go","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fseverity1%2Fclaude-agent-sdk-go","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fseverity1%2Fclaude-agent-sdk-go/lists"}