A comprehensive Go SDK providing programmatic access to the Claude Code CLI. This SDK offers idiomatic Go interfaces for subprocess-based Claude Code integration, enabling powerful AI-assisted development workflows directly from Go applications.
Key Highlights:
- β¨ Production Ready - Battle-tested with comprehensive error handling
- π High Performance - Efficient streaming and concurrent operations
- π Type Safe - Full Go type safety with compile-time validation
- π Well Documented - Extensive examples and API documentation
- π Actively Maintained - Regular updates and community support
- π― Overview
- π Feature Parity
- π Getting Started
- π Authentication Setup
- π» Usage Examples
- π οΈ Design Philosophy
- π§ Advanced Features
- π Supported Environments
- π¦ Project Structure
- π Examples
- π― Use Cases
- π§ Troubleshooting
- π€ Contributing
- π License
- π Acknowledgments
- π Support & Community
The Go Claude Code SDK provides a production-ready Go wrapper for the Claude Code CLI, enabling seamless integration of AI-powered coding assistance into your Go applications. Built with Go best practices, it offers type-safe interfaces, concurrent operations, and comprehensive error handling.
β‘ Quick Start: Get up and running in under 2 minutes with our Getting Started guide.
π Looking for specific functionality? Check our Table of Contents below.
Core Capabilities:
- Type-safe interfaces for all Claude Code operations
- Streaming support for real-time responses with channels
- Session management for conversation persistence
- Tool execution including file operations and code analysis
- MCP server integration for extended capabilities
- Project-aware context for intelligent code assistance
- Command system for structured interactions
- Comprehensive error handling with detailed error types
Go-Specific Advantages:
- Context propagation with
context.Contextsupport throughout - Concurrency control with goroutines and proper synchronization
- Resource management with automatic cleanup and defer patterns
- Strong typing with compile-time validation
- Idiomatic error handling following Go conventions
| Feature | Python SDK | TypeScript SDK | Go SDK | Notes |
|---|---|---|---|---|
| Core Features | ||||
| Query Interface | β
query() |
β
query() |
β
QueryMessages() |
Go uses channels for async |
| Streaming Messages | β async iteration | β async iteration | β Channel-based | Idiomatic Go approach |
| Session Management | β
--session |
β
--session |
β Full support | Persistent conversations |
| Message Types | ||||
| Content Blocks | β Full support | β Full support | β Full support | Text, Tool Use, Tool Result |
| Message Roles | β All roles | β All roles | β All roles | User, Assistant, System, Tool |
| Tool Calls | β Native | β Native | β Native | Full tool execution |
| Configuration | ||||
| Permission Modes | β 3 modes | β 3 modes | β 3 modes | Ask, Accept, Reject |
| System Prompts | β Supported | β Supported | β Supported | Custom instructions |
| Max Turns | β Configurable | β Configurable | β Configurable | Conversation limits |
| Advanced Features | ||||
| MCP Server Support | β Full | β Full | β Full | All official servers |
| Project Context | β Auto-detect | β Auto-detect | β Enhanced | Multi-language support |
| Tool Management | β Built-in | β Built-in | β Extended | Additional helpers |
| Command System | β Basic | β Basic | β Extended | Slash commands |
- Strong Type Safety: Compile-time type checking for all operations
- Concurrency Control: Native goroutine support with proper synchronization
- Context Cancellation: First-class
context.Contextsupport throughout - Error Handling: Idiomatic Go error handling with detailed error types
- Performance: Efficient subprocess management and streaming
- Go 1.20 or higher - The SDK uses modern Go features and requires Go 1.20+ (tested up to Go 1.24)
- Claude Code CLI - Install the official Claude Code CLI:
npm install -g @anthropic-ai/claude-code
- Authentication - One of the following:
- Claude subscription (recommended) - Set up with
claude setup-token - Anthropic API key from Anthropic Console
- Claude subscription (recommended) - Set up with
go get github.com/jonwraymond/go-claude-code-sdkGet up and running with the Go Claude Code SDK in under 5 minutes:
go get github.com/jonwraymond/go-claude-code-sdknpm install -g @anthropic-ai/claude-code# Option A: Use Claude subscription (recommended)
claude setup-token
# Option B: Use API key
export ANTHROPIC_API_KEY="test-api-key-not-real-your-key-here"Here's a simple example to get you started:
package main
import (
"context"
"fmt"
"log"
"github.com/jonwraymond/go-claude-code-sdk/pkg/client"
"github.com/jonwraymond/go-claude-code-sdk/pkg/types"
)
func main() {
ctx := context.Background()
// Create configuration with automatic auth detection
config := types.NewClaudeCodeConfig()
// The SDK will automatically detect your auth method
// Create the client
claudeClient, err := client.NewClaudeCodeClient(ctx, config)
if err != nil {
log.Fatal("Failed to create client:", err)
}
defer claudeClient.Close()
// Make a simple query
response, err := claudeClient.Query(ctx, &types.QueryRequest{
Messages: []types.Message{
{Role: types.RoleUser, Content: "Explain Go channels in simple terms"},
},
})
if err != nil {
log.Fatal("Query failed:", err)
}
// Print the response
for _, block := range response.Content {
if block.Type == "text" {
fmt.Println(block.Text)
}
}
}The SDK supports two authentication methods:
# Set up Claude subscription authentication
claude setup-tokenThe SDK will automatically detect and use subscription authentication when available.
# Set your API key as an environment variable
export ANTHROPIC_API_KEY="test-api-key-not-real-your-key-here"Or configure it directly in code:
config := types.NewClaudeCodeConfig()
config.APIKey = "your-api-key"
config.AuthMethod = types.AuthTypeAPIKeySessions allow for persistent conversations with Claude:
// Create a session for persistent conversations
session, err := claudeClient.CreateSession(ctx, &types.SessionConfig{
SessionID: "my-project-session",
Model: "claude-3-5-sonnet-20241022",
})
if err != nil {
log.Fatal("Failed to create session:", err)
}
defer session.Close()
// Use the session for multiple interactions
response1, err := session.Query(ctx, &types.QueryRequest{
Messages: []types.Message{
{Role: types.RoleUser, Content: "Analyze this Go project structure"},
},
})
// Continue the conversation
response2, err := session.Query(ctx, &types.QueryRequest{
Messages: []types.Message{
{Role: types.RoleUser, Content: "Now suggest improvements"},
},
})For real-time responses, use the streaming API:
// Create a streaming request
request := &types.QueryRequest{
Messages: []types.Message{
{Role: types.RoleUser, Content: "Explain goroutines with examples"},
},
Model: "claude-3-5-sonnet-20241022",
}
// Start streaming
stream, err := claudeClient.QueryStream(ctx, request)
if err != nil {
log.Fatal("Failed to start stream:", err)
}
defer stream.Close()
fmt.Print("Claude: ")
for {
chunk, err := stream.Recv()
if err != nil {
log.Printf("Stream error: %v", err)
break
}
if chunk.Done {
fmt.Println("\nβ Response complete")
break
}
// Print content in real-time
fmt.Print(chunk.Content)
}Customize the client with various options:
// Create advanced configuration
config := &types.ClaudeCodeConfig{
Model: "claude-3-5-sonnet-20241022",
WorkingDirectory: "/path/to/your/project",
MaxTokens: 8000,
Temperature: 0.7,
AuthMethod: types.AuthTypeAPIKey,
APIKey: os.Getenv("ANTHROPIC_API_KEY"),
Debug: true,
Timeout: 60 * time.Second,
Environment: map[string]string{
"PROJECT_TYPE": "go-microservice",
"DEBUG_MODE": "true",
},
}
// Apply defaults for any unset values
config.ApplyDefaults()
// Create client with custom config
claudeClient, err := client.NewClaudeCodeClient(ctx, config)The SDK automatically detects your project structure and provides intelligent context:
// Get enhanced project context
projectCtx, err := claudeClient.GetProjectContext(ctx)
if err != nil {
log.Fatal("Failed to get project context:", err)
}
fmt.Printf("Project Details:\n")
fmt.Printf(" Working Directory: %s\n", projectCtx.WorkingDirectory)
fmt.Printf(" Git Repository: %t\n", projectCtx.IsGitRepository)
fmt.Printf(" Project Type: %s\n", projectCtx.ProjectType)
// Use context in conversations
response, err := claudeClient.Query(ctx, &types.QueryRequest{
Messages: []types.Message{
{
Role: types.RoleUser,
Content: fmt.Sprintf("Help me improve this %s project", projectCtx.ProjectType),
},
},
})Robust error handling with context support:
// Create context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Make request with timeout
response, err := claudeClient.Query(ctx, &types.QueryRequest{
Messages: []types.Message{
{Role: types.RoleUser, Content: "Analyze this large codebase"},
},
})
if err != nil {
// Handle different error types
if errors.Is(err, context.DeadlineExceeded) {
log.Println("Request timed out")
} else if claudeErr, ok := err.(*errors.ClaudeCodeError); ok {
log.Printf("Claude Code error: %s (code: %s)", claudeErr.Message, claudeErr.Code)
if claudeErr.IsRetryable() {
log.Println("Error is retryable")
}
} else {
log.Printf("Unexpected error: %v", err)
}
return
}
// Process successful response
for _, block := range response.Content {
if block.Type == "text" {
fmt.Println(block.Text)
}
}Switch between different Claude models for different tasks:
// Use different models for different purposes
configs := map[string]*types.ClaudeCodeConfig{
"analysis": {
Model: "claude-3-5-sonnet-20241022", // Best for complex analysis
MaxTokens: 8000,
Temperature: 0.1, // Lower temperature for precise analysis
},
"creative": {
Model: "claude-3-opus-20240229", // Best for creative tasks
MaxTokens: 4000,
Temperature: 0.7, // Higher temperature for creativity
},
}
// Create clients for different use cases
analysisClient, err := client.NewClaudeCodeClient(ctx, configs["analysis"])
if err != nil {
log.Fatal("Failed to create analysis client:", err)
}
defer analysisClient.Close()
creativeClient, err := client.NewClaudeCodeClient(ctx, configs["creative"])
if err != nil {
log.Fatal("Failed to create creative client:", err)
}
defer creativeClient.Close()
// Use appropriate client for each task
codeAnalysis, _ := analysisClient.Query(ctx, &types.QueryRequest{
Messages: []types.Message{
{Role: types.RoleUser, Content: "Analyze the performance of this algorithm"},
},
})
documentation, _ := creativeClient.Query(ctx, &types.QueryRequest{
Messages: []types.Message{
{Role: types.RoleUser, Content: "Write engaging documentation for this API"},
},
})The Go Claude Code SDK embraces Claude Code's subprocess-based design:
- Direct CLI Integration: Executes
claudecommands via subprocess - Streaming I/O: Real-time parsing of stdout/stderr
- Process Management: Proper lifecycle management with cleanup
- Session Persistence: Leverages Claude Code's
--sessionflag
The SDK follows Go best practices:
- Context Propagation: All operations accept
context.Context - Error Handling: Explicit error returns with typed errors
- Interface Design: Small, composable interfaces
- Concurrency Safety: Thread-safe operations with proper locking
- Resource Management: Automatic cleanup with defer patterns
Strong typing throughout:
// Typed command system
cmd := &types.Command{
Type: types.CommandAnalyze, // Not a string
Args: []string{"src/"},
}
// Typed message roles
msg := types.NewTextMessage(types.MessageRoleUser, "Hello")
// Typed configuration
options := &client.QueryOptions{
PermissionMode: client.PermissionModeAcceptEdits, // Not a string
}// Register a custom tool
customTool := &client.ClaudeCodeToolDefinition{
Name: "my_tool",
Description: "My custom tool",
InputSchema: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"input": map[string]interface{}{"type": "string"},
},
},
}
err = client.Tools().RegisterTool("my_tool", customTool)result, err := client.QueryMessagesSync(ctx, "Build the project", nil)
if err != nil {
switch e := err.(type) {
case *errors.ClaudeCodeError:
if e.IsRetryable() {
// Retry logic
}
case *errors.ValidationError:
// Handle validation error
default:
// Handle other errors
}
}// With timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
messages, err := client.QueryMessages(ctx, "Analyze this codebase", nil)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
log.Println("Operation timed out")
}
}
// With cancellation
ctx, cancel := context.WithCancel(context.Background())
go func() {
// Cancel after some condition
time.Sleep(5 * time.Second)
cancel()
}()
messages, err := client.QueryMessages(ctx, "Long running task", nil)- β Linux - Ubuntu 20.04+, CentOS 8+, Alpine 3.14+
- β macOS - macOS 11.0+ (Big Sur and later)
- β Windows - Windows 10/11, Windows Server 2019+
- β Go 1.20 - Minimum required version
- β Go 1.21 - Fully supported with enhanced features
- β Go 1.22 - Latest features and optimizations
- β Go 1.23 - Stable, fully tested and supported
- β Go 1.24 - Latest version, fully tested and supported
- β Latest Version - Always recommended for best compatibility
- β v1.0.0+ - Minimum supported version
β οΈ Development Versions - May work but not officially supported
- β Linux/macOS: Bash 4.0+, Zsh 5.0+, Fish 3.0+
- β Windows: PowerShell 5.1+, Command Prompt, Git Bash
- β Container: Docker, Podman (with Node.js 18+ base image)
- β Node.js 18+ - Required for Claude Code CLI
- β npm 8+ - For installing Claude Code CLI
β οΈ Yarn/pnpm - May work but npm is recommended
go-claude-code-sdk/
βββ pkg/ # Claude Code CLI wrapper
β βββ client/ # Main CLI client implementation
β βββ types/ # CLI type definitions
β βββ errors/ # Error types and handling
β βββ auth/ # Authentication helpers
βββ examples/ # Example applications
βββ docs/ # Comprehensive documentation
β βββ API.md # Complete API reference
β βββ QUERY_OPTIONS.md # Query configuration guide
β βββ COMPATIBILITY_GUIDE.md # Migration guidance
βββ .github/
β βββ workflows/ # CI/CD configuration
βββ go.mod # Go module definition
βββ LICENSE # MIT License
βββ README.md # This file (overview)
βββ CHANGELOG.md # Version history
βββ CONTRIBUTING.md # Contribution guidelines
The SDK includes comprehensive examples demonstrating various use cases:
| Example | Description | Use Case |
|---|---|---|
| Basic Client | Simple query/response | Getting started, basic AI assistance |
| Streaming Queries | Real-time responses | Long-form content, live feedback |
| Session Lifecycle | Conversation persistence | Multi-turn conversations, context |
| Advanced Client | Custom configuration | Production deployments |
| Authentication Methods | Auth setup | Different deployment scenarios |
| MCP Integration | Tool extensions | Enhanced functionality |
| Command Execution | CLI commands | Automated workflows |
- Basic Client - Client initialization and configuration
- Streaming Queries - Real-time response streaming
- Session Lifecycle - Session management and persistence
- Advanced Client - Advanced features and customization
- Authentication Methods - Different authentication approaches
- MCP Integration - Model Context Protocol server integration
- Command Execution - CLI command execution
To run any example:
# Navigate to the example directory
cd examples/basic_client
# Set up authentication (choose one):
export ANTHROPIC_API_KEY="your-api-key" # API key method
# OR
claude setup-token # Subscription method
# Run the example
go run main.goHere's what you can expect from the basic client example:
π Starting Claude Code SDK Example
β
Client created successfully
π Sending query: "Explain Go channels in simple terms"
π Claude: Go channels are like pipes that allow different parts of your program
(called goroutines) to communicate safely with each other...
β
Query completed successfully
See the examples README for detailed information about each example.
The Go Claude Code SDK is perfect for:
Development Workflows:
- β AI-assisted code review and analysis
- β Automated documentation generation
- β Code refactoring and optimization suggestions
- β Test case generation and validation
Integration Scenarios:
- β CI/CD pipeline integration for code analysis
- β IDE and editor extensions
- β Developer tools and utilities
- β Automated code quality assessment
Application Types:
- β Command-line developer tools
- β Code analysis and linting services
- β Documentation generation systems
- β Educational coding platforms
We welcome contributions from the community! Whether you're fixing bugs, adding features, or improving documentation, your help is appreciated.
- Fork the repository and clone your fork
- Set up the development environment following our Contributing Guidelines
- Create a new branch for your feature or fix
- Make your changes with tests and documentation
- Submit a pull request with a clear description
- π Bug fixes - Help us improve reliability
- β¨ New features - Extend SDK capabilities
- π Documentation - Improve guides and examples
- π§ͺ Testing - Increase test coverage
- π§ Performance - Optimize existing functionality
See our Contributing Guidelines for detailed information about:
- Development setup and workflow
- Code style and standards
- Testing requirements
- Pull request process
This project is licensed under the MIT License - see the LICENSE file for details.
The MIT License allows for:
- β Commercial use
- β Modification and distribution
- β Private use
- β Provided "as is" without warranty
Special thanks to:
- Anthropic for creating Claude and the Claude Code CLI
- The Go Community for excellent tooling, standards, and best practices
- Contributors who have helped improve this SDK
- Early adopters who provided valuable feedback and testing
Problem: go get fails with module not found
go: module github.com/jonwraymond/go-claude-code-sdk: not foundSolution: Ensure you're using Go 1.20+ and the correct module path:
go version # Should be 1.20 or higher
go get -u github.com/jonwraymond/go-claude-code-sdkProblem: "Authentication failed" or "API key not found"
Error: authentication failed: invalid API key
Solutions:
-
For API Key Authentication:
export ANTHROPIC_API_KEY="test-api-key-not-real-your-key-here"
Or set it directly in code:
config := &types.ClaudeCodeConfig{ APIKey: "your-api-key", AuthMethod: types.AuthTypeAPIKey, }
-
For Subscription Authentication:
claude setup-token
Then use:
config := &types.ClaudeCodeConfig{ AuthMethod: types.AuthTypeSubscription, }
Problem: "claude command not found"
Error: exec: "claude": executable file not found in $PATH
Solutions:
- Install Claude Code CLI:
npm install -g @anthropic-ai/claude-code
- Verify installation:
claude --version which claude
- If using a custom path, configure it:
config := &types.ClaudeCodeConfig{ ClaudePath: "/custom/path/to/claude", }
Problem: Session creation fails or sessions don't persist
Error: failed to create session: session directory not accessible
Solutions:
- Ensure write permissions in working directory:
ls -la /path/to/your/project chmod 755 /path/to/your/project
- Use absolute paths:
config := &types.ClaudeCodeConfig{ WorkingDirectory: "/absolute/path/to/project", }
- Check session ID format (must be valid for filesystem):
// Good: alphanumeric with hyphens sessionID := "my-project-session-123" // Bad: contains invalid characters sessionID := "my/project\\session*123"
Problem: Streaming responses hang or timeout
Error: context deadline exceeded while streaming
Solutions:
- Increase timeout:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel()
- Handle context cancellation properly:
stream, err := client.QueryStream(ctx, request) if err != nil { if errors.Is(err, context.DeadlineExceeded) { log.Println("Request timed out - try increasing timeout") } return err }
Problem: Slow response times or high memory usage Solutions:
- Optimize project context:
config := &types.ClaudeCodeConfig{ IncludeProjectContext: false, // For large projects MaxProjectFiles: 100, // Limit files included }
- Use appropriate models:
// For simple queries - faster and cheaper config.Model = "claude-3-haiku-20240307" // For complex analysis - more capable but slower config.Model = "claude-3-5-sonnet-20241022"
- Implement connection pooling for multiple clients:
var clientPool = sync.Pool{ New: func() interface{} { client, _ := client.NewClaudeCodeClient(ctx, config) return client }, }
config := &types.ClaudeCodeConfig{
Debug: true,
LogLevel: "debug",
}# Test CLI directly
claude query "Hello, Claude!"
# Check version compatibility
claude --version
# Test with session
claude query --session test-session "What's my session ID?"# Check connectivity to Anthropic
curl -I https://api.anthropic.com/
# Test with verbose output
claude query --debug "Test connection"- Ensure PowerShell or CMD is properly configured
- Use forward slashes in paths:
/path/to/project - Set environment variables in PowerShell:
$env:ANTHROPIC_API_KEY="your-key"
- Install Claude Code CLI via npm (not Homebrew)
- Ensure
npmglobal bin directory is in PATH:echo $PATH | grep $(npm config get prefix)/bin
- Install Node.js 18+ for Claude Code CLI compatibility
- For Ubuntu/Debian:
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - sudo apt-get install -y nodejs
If you're still experiencing issues:
- Check our GitHub Issues for known problems
- Review the Claude Code CLI documentation
- Enable debug logging and include logs in your issue report
- Provide a minimal reproduction case when reporting bugs
- π Documentation: pkg.go.dev
- π Bug Reports: GitHub Issues
- π¬ Questions & Discussions: GitHub Discussions
- π§ Security Issues: Report privately via email (see SECURITY.md)
- Check existing issues to avoid duplicates
- Review the documentation and troubleshooting guide
- Test with the latest version of the SDK and Claude Code CLI
- Enable debug logging and include relevant logs
- Provide minimal reproduction steps when reporting bugs
- Test with Claude Code CLI directly to isolate SDK vs CLI issues
- Be respectful and inclusive
- Help newcomers get started
- Share knowledge and best practices
- Follow our Code of Conduct
Built with β€οΈ for the Go and Claude Code communities
Empowering developers with AI-assisted coding workflows through idiomatic Go interfaces.
Get Started β’ Examples β’ API Docs β’ Issues